Source code for openairbearing.core.cases

"""Bearing cases: plain, serialisable descriptions of one bearing.

A case is a frozen dataclass of numbers in SI units. It knows how to build
its Film and which position it is normally evaluated at, and nothing else, so
it can be written to JSON, compared, hashed and edited by path:

    case = CircularPad(radius=20e-3)
    case = set_path(case, "porous.kappa", 2e-15)
    film = case.film()

Every field carries its label, unit and display unit (see params.py), from
which ``describe`` builds the field list a form or a table needs.

A field may follow another one while it is not given (the bore pressure of
an annular pad follows the ambient pressure). Its value is then None, in the
case, in the dict of ``case_to_dict`` and in JSON (null), and ``set_path``
takes None to make it follow again.
"""

from __future__ import annotations

import dataclasses
from dataclasses import dataclass, field
from typing import ClassVar

import numpy as np

from . import geometry
from .film import WALLS, Film, Porous
from .gas import FLUIDS, gas_at
from .params import param

__all__ = [
    "KINDS",
    "AnnularPad",
    "CircularPad",
    "Journal",
    "JournalPads",
    "RectangularPad",
    "SphericalBearing",
    "ThrustBushing",
    "ThrustPads",
    "case_from_dict",
    "case_to_dict",
    "describe",
    "get_path",
    "set_path",
]

_um = ("m", "µm", 1e6)
_mm = ("m", "mm", 1e3)
_MPa = ("Pa", "MPa", 1e-6)
FORM_ERRORS = ("none", "linear", "quadratic")
_WALL_HELP = (
    "How the porous wall curves around the film. outside: a sleeve around "
    "the film (a bushing on a shaft), so the area the gas passes through "
    "grows away from the film. inside: a porous shaft or liner inside the "
    "film. flat: a slab, the curvature left out."
)


def _form_error(amplitude: float, kind: str, radial_fraction):
    """Extra gap from a form error of a face, zero where the gap is smallest.

    amplitude is the depth of the error in m and kind one of FORM_ERRORS:
    "linear" (the error grows with the first power of radial_fraction),
    "quadratic" (with its square) or "none". radial_fraction(x) is 0 where
    the error starts and 1 where it ends: the centre and the edge of a
    circular pad (a cone or a spherical cap), the inner and the outer edge
    of an annular face, the centre line and the two edges across x of a
    rectangular pad (a roof or a cylinder). A positive amplitude is a
    concave face (gap largest where the fraction is 0), a negative one
    convex (gap largest where it is 1). Returns a function of the film
    coordinates x, or None for a flat face.
    """
    if kind == "none" or amplitude == 0.0:
        return None
    if kind not in FORM_ERRORS:
        raise ValueError(f"form_error_type must be one of {FORM_ERRORS}")
    n = 1 if kind == "linear" else 2

    def shape(x):
        rho = radial_fraction(x) ** n
        return amplitude * (1.0 - rho) if amplitude > 0.0 else -amplitude * rho

    return shape


def _sliding(ux: float, uy: float):
    """Uniform surface velocity (ux, uy) in m/s as a function of x, or None."""
    if ux == 0.0 and uy == 0.0:
        return None
    return lambda x: (ux, uy)


@dataclass(frozen=True)
class _Case:
    """Fields shared by every case."""

    kind: ClassVar[str] = ""
    title: ClassVar[str] = ""
    hidden: ClassVar[tuple] = ()  # field paths the case sets itself
    help: ClassVar[str] = ""  # what the position coordinates mean, for a form

    # the restrictor
    porous: Porous = field(default_factory=Porous)
    # name of the gas, one of ``gas.FLUIDS``
    gas: str = param("air", "Gas", choices=tuple(FLUIDS))
    # The film is isothermal at this temperature, K: that of the gas entering the
    # bearing, when the bearing has that temperature too.
    temperature: float = param(
        293.15,
        "Gas temperature",
        "K",
        minimum=150.0,
        maximum=600.0,
        help="The film is isothermal at this temperature: that of the gas "
        "entering the bearing, when the bearing has that temperature too.",
    )
    # density and viscosity of the real gas as they vary with pressure, instead of those
    # of an ideal gas
    real_gas: bool = param(
        False,
        "Real-gas properties",
        help="Density and viscosity of the real gas as they vary with "
        "pressure, instead of those of an ideal gas.",
    )
    # absolute supply pressure, Pa
    ps: float = param(0.6e6, "Supply pressure (abs)", *_MPa, minimum=1e3)
    # absolute ambient pressure, Pa
    pa: float = param(101325.0, "Ambient pressure (abs)", *_MPa, minimum=1e3)

    def _common(self) -> dict:
        gas = gas_at(
            self.gas, self.temperature, self.real_gas, p_max=1.2 * max(self.ps, self.pa)
        )
        return {"porous": self.porous, "gas": gas, "ps": self.ps, "pa": self.pa}

    def film(self) -> Film:
        """The film of the case, ready to solve."""
        raise NotImplementedError

    def size(self) -> dict:
        """What the case costs to solve, found without solving it.

        {"film": pressure unknowns of the film, "body": nodes of a porous
        body under it (0 without one), "model": "column", "volume" or
        "body"}. Builds the film, which takes well under a second for every
        mesh the forms allow; a case whose film carries a large body says
        so without building it (``ThrustBushing``).
        """
        film = self.film()
        if film.body is not None:
            return {"film": int(film.basis.N), "body": int(film.body.body.basis.N),
                    "model": "body"}  # fmt: skip
        return {"film": int(film.basis.N), "body": 0, "model": film.porous.model}

    def default_position(self) -> dict:
        """Position the case is evaluated at unless a study says otherwise.

        A dict from the name of each position coordinate of the film to its
        value, in m or rad.
        """
        raise NotImplementedError


@dataclass(frozen=True)
class _ThrustFace(_Case):
    """Fields shared by the thrust faces, whose position is (h, rx, ry)."""

    # The gap of a thrust face is h + rx·y - ry·x + form error
    # (``geometry._thrust_gap``), with x and y from the origin of the face
    # and the form error zero where it leaves the gap smallest. Each kind
    # says where its origin is and where its form error runs.
    help: ClassVar[str] = (
        "Film thickness is the gap of the flat face without tilt: the same "
        "everywhere. Tilt rx and ry turn the runner about the x and y axes "
        "through the centre of the face, so the gap is film thickness + rx·y "
        "- ry·x, and the film thickness is then the gap at the centre. A form "
        "error adds to that and is zero where it leaves the gap smallest (the "
        "edge of a concave face, the centre of a convex one), so without tilt "
        "the film thickness is the smallest gap. Forces and moments are those "
        "on the runner."
    )

    # film thickness h of the default position, m: the gap of the flat face without
    # tilt, to which tilt and form error add (see ``help``)
    gap: float = param(5e-6, "Film thickness", *_um, minimum=1e-8)
    # depth of the form error of the face, m: positive is concave (gap largest where
    # the error starts: the centre, or the inner edge of an annular face), negative
    # convex (gap largest at the outer edge). It adds to the gap, so without tilt
    # the film thickness stays the smallest gap.
    form_error: float = param(
        0.0,
        "Form error (+ concave)",
        *_um,
        help="Depth of the form error of the face. Positive is concave (gap "
        "largest at the centre, or at the inner edge of an annular face), "
        "negative convex (gap largest at the outer edge). It adds to the "
        "gap, so without tilt the film thickness stays the smallest gap.",
    )
    # shape of the form error: "linear" (a cone), "quadratic" (a spherical cap) or
    # "none" (a flat face, whatever form_error says); on an annular face the error
    # runs from the inner edge to the outer one
    form_error_type: str = param(
        "none",
        "Form error shape",
        choices=FORM_ERRORS,
        help="linear: the error grows in proportion to the distance from the "
        "centre (a cone). quadratic: with the square of it (a spherical cap). "
        "On an annular face the distance is counted from the inner edge to "
        "the outer one. none: a flat face, whatever the form error says.",
    )
    # sliding speed along x (the sum of the two surface speeds), m/s
    ux: float = param(0.0, "Sliding speed x", "m/s")
    # the same along y, m/s
    uy: float = param(0.0, "Sliding speed y", "m/s")

    def default_position(self) -> dict:
        return {"h": self.gap, "rx": 0.0, "ry": 0.0}


[docs] @dataclass(frozen=True) class CircularPad(_ThrustFace): """Circular thrust pad (``geometry.circular_pad``).""" kind: ClassVar[str] = "circular_pad" title: ClassVar[str] = "Circular thrust pad" # pad radius, m radius: float = param(18.5e-3, "Pad radius", *_mm, minimum=1e-4) # refinement nrefs of the disc mesh (``meshes.disc``) mesh_refinements: int = param(4, "Mesh refinements", minimum=2, maximum=6)
[docs] def film(self) -> Film: R = self.radius return geometry.circular_pad( R, shape=_form_error( self.form_error, self.form_error_type, lambda x: np.hypot(*x) / R ), velocity=_sliding(self.ux, self.uy), nrefs=self.mesh_refinements, **self._common(), )
[docs] @dataclass(frozen=True) class AnnularPad(_ThrustFace): """Annular thrust pad (``geometry.annular_pad``). The form error runs from the inner edge to the outer one. """ kind: ClassVar[str] = "annular_pad" title: ClassVar[str] = "Annular thrust pad" help: ClassVar[str] = ( "Film thickness is the gap of the flat face without tilt: the same " "everywhere. Tilt rx and ry turn the runner about the x and y axes " "through the axis of the annulus, so the gap is film thickness + rx·y " "- ry·x; the film thickness is then the gap that the plane of the " "runner has on the axis, where there is no film. A form error adds to " "that and runs from the inner edge to the outer one: it is zero at " "the outer edge of a concave face and at the inner edge of a convex " "one, so without tilt the film thickness is the smallest gap. Forces " "and moments are those on the runner." ) # inner radius, m r_in: float = param(10e-3, "Inner radius", *_mm, minimum=1e-4) # outer radius, m r_out: float = param(25e-3, "Outer radius", *_mm, minimum=1e-4) # absolute pressure at the inner edge, Pa; None: the ambient pressure pa, # whatever that is p_inner: float | None = param( None, "Bore pressure (abs)", *_MPa, minimum=1e3, follows="pa", help="Absolute pressure at the inner edge of the face, for a bore " "that is a chamber of its own. Not given, it is the ambient pressure " "and changes with it.", ) # elements around n_circ: int = param(96, "Elements around", minimum=12, maximum=360) # elements across the face n_radial: int = param(16, "Elements across", minimum=4, maximum=96)
[docs] def film(self) -> Film: a, b = self.r_in, self.r_out return geometry.annular_pad( a, b, p_inner=self.p_inner, # None: the builder takes the ambient pressure shape=_form_error( self.form_error, self.form_error_type, lambda x: (np.hypot(*x) - a) / (b - a), ), velocity=_sliding(self.ux, self.uy), n_circ=self.n_circ, n_radial=self.n_radial, **self._common(), )
[docs] @dataclass(frozen=True) class RectangularPad(_ThrustFace): """Rectangular thrust pad (``geometry.rectangular_pad``). The form error varies along x only, from the centre line x = 0 to the edges at x = -lx/2 and lx/2: a roof or a cylindrical face. """ kind: ClassVar[str] = "rectangular_pad" title: ClassVar[str] = "Rectangular thrust pad" help: ClassVar[str] = ( "Film thickness is the gap of the flat face without tilt: the same " "everywhere. Tilt rx and ry turn the runner about the x and y axes " "through the centre of the face, so the gap is film thickness + rx·y " "- ry·x, and the film thickness is then the gap at the centre. A form " "error adds to that and varies along x only: it is zero at the two " "edges across x of a concave face and on the centre line x = 0 of a " "convex one, so without tilt the film thickness is the smallest gap. " "Forces and moments are those on the runner." ) # The form error of this pad varies along x only, so its two fields say so: # the same values and limits as on the other thrust faces, another text. form_error: float = param( 0.0, "Form error (+ concave)", *_um, help="Depth of the form error of the face, which varies along x only. " "Positive is concave (gap largest on the centre line x = 0), negative " "convex (gap largest at the two edges across x). It adds to the gap, " "so without tilt the film thickness stays the smallest gap.", ) form_error_type: str = param( "none", "Form error shape", choices=FORM_ERRORS, help="linear: the error grows in proportion to the distance from the " "centre line x = 0, the same at every y (a roof). quadratic: with the " "square of it (a cylindrical face, its axis along y). none: a flat " "face, whatever the form error says.", ) # length along x, m lx: float = param(40e-3, "Length x", *_mm, minimum=1e-4) # length along y, m ly: float = param(40e-3, "Length y", *_mm, minimum=1e-4) # only the two edges across x are open to ambient: a strip of a pad that is very # long in y infinite: bool = param( False, "Infinitely long in y", help="Only the two edges across x are open to ambient: a strip of a " "pad that is very long in y.", ) # elements along x nx: int = param(32, "Elements in x", minimum=4, maximum=128) # elements along y ny: int = param(32, "Elements in y", minimum=1, maximum=128)
[docs] def film(self) -> Film: half = self.lx / 2.0 edges = ("left", "right") if self.infinite else None kwargs = {} if edges is None else {"open_edges": edges} return geometry.rectangular_pad( self.lx, self.ly, shape=_form_error( self.form_error, self.form_error_type, lambda x: np.abs(x[0]) / half ), velocity=_sliding(self.ux, self.uy), nx=self.nx, ny=self.ny, **kwargs, **self._common(), )
def _bore_form(case): """Form errors of the bore of a journal case, as a gap shape.""" return geometry.bore_form( case.radius, case.length, conicity=case.conicity, roundness=case.roundness, lobes=case.lobes, lobe_angle=case.lobe_angle, crowning=case.crowning, )
[docs] @dataclass(frozen=True) class Journal(_Case): """Full journal bearing (``geometry.journal``), with form errors of the bore.""" kind: ClassVar[str] = "journal" title: ClassVar[str] = "Journal bearing" help: ClassVar[str] = ( "Displacement x and y move the shaft off the bushing axis; tilt rx and ry " "turn it about axes through the middle of the bearing. Forces and moments " "are those of the film on the shaft, so a restoring force is negative. " "Form errors of the bore add to the gap and leave the clearance as the " "tightest one: conicity along the axis, out of roundness with two or " "three lobes around it, and crowning as a parabola along the axis." ) # film radius, m radius: float = param(20e-3, "Film radius", *_mm, minimum=1e-4) # bearing length, m length: float = param(40e-3, "Length", *_mm, minimum=1e-4) # radial clearance with the shaft centred, m: the tightest one when the bore has # form errors clearance: float = param(12e-6, "Radial clearance", *_um, minimum=1e-8) # shaft speed, rad/s omega: float = param(0.0, "Shaft speed", "rad/s", "rpm", 30.0 / np.pi) # how the porous wall curves around the film: "outside", "inside" or "flat" # (``geometry.journal``) wall: str = param( "outside", "Porous wall curvature", choices=WALLS, help=_WALL_HELP ) # conicity of the bore, m: the gap opens by this much along the axis, toward +z if # positive conicity: float = param(0.0, "Conicity (+ opens to +z)", *_um) # out of roundness of the bore, m: the gap varies around it between 0 and this much roundness: float = param(0.0, "Out of roundness", *_um, minimum=0.0) # number of lobes of the out of roundness (2 is oval) lobes: int = param(2, "Lobes", choices=(2, 3)) # angle of a tight spot of the out of roundness, rad lobe_angle: float = param(0.0, "Angle of a tight spot", "rad", "°", 180.0 / np.pi) # crowning, m: a parabola along the axis that opens toward both ends if positive, in # the middle if negative crowning: float = param(0.0, "Crowning (+ opens at ends)", *_um) # elements around n_circ: int = param(96, "Elements around", minimum=12, maximum=360) # elements along the axis n_axial: int = param(16, "Elements along", minimum=4, maximum=96)
[docs] def film(self) -> Film: return geometry.journal( self.radius, self.length, self.clearance, omega=self.omega, wall=self.wall, shape=_bore_form(self), n_circ=self.n_circ, n_axial=self.n_axial, **self._common(), )
[docs] def default_position(self) -> dict: return {"x": 0.0, "y": 0.0, "rx": 0.0, "ry": 0.0}
_deg = ("rad", "°", 180.0 / np.pi)
[docs] @dataclass(frozen=True) class ThrustPads(_ThrustFace): """Thrust face of annular-sector pads (``geometry.thrust_pads``). The form error runs from the inner radius to the outer one. """ kind: ClassVar[str] = "thrust_pads" title: ClassVar[str] = "Thrust pads (annular sectors)" help: ClassVar[str] = ( "Equally spaced sector pads of an annulus; the stator between them is " "relieved, so every pad edge is at ambient pressure. Film thickness is " "the gap of flat pads without tilt, the same on every pad. Tilt rx " "and ry turn the runner about the x and y axes through the bearing " "axis, where there is no film, so the gap is film thickness + rx·y - " "ry·x. A form error runs from the inner radius to the outer one. The " "forces are those of all pads together. Pad taper tilts every pad " "about its own centre: it is the rise of the gap across the pad, and " "a positive value closes the gap toward increasing angle (or radius). " "Form error and taper only add to the gap, so without tilt the gap is " "nowhere below the film thickness." ) # inner radius, m r_in: float = param(10e-3, "Inner radius", *_mm, minimum=1e-4) # outer radius, m r_out: float = param(25e-3, "Outer radius", *_mm, minimum=1e-4) # number of pads, equally spaced n_pads: int = param(3, "Number of pads", minimum=1, maximum=24) # angle spanned by one pad, rad pad_angle: float = param(np.deg2rad(100.0), "Pad angle", *_deg, minimum=0.02) # angle of the centre of the first pad from the x axis, rad offset: float = param(0.0, "Angle of the first pad centre", *_deg) # rise of the gap across the arc of a pad, m: every pad is tilted about its own # centre, and a positive value closes the gap toward +theta taper: float = param(0.0, "Pad taper along arc", *_um) # the same across the pad, m: a positive value closes the gap toward the outer # radius taper_radial: float = param(0.0, "Pad taper radial", *_um) # elements along the arc of a pad n_circ: int = param(20, "Elements along a pad", minimum=4, maximum=96) # elements across a pad n_radial: int = param(12, "Elements across", minimum=4, maximum=96)
[docs] def film(self) -> Film: a, b = self.r_in, self.r_out return geometry.thrust_pads( a, b, self.n_pads, self.pad_angle, offset=self.offset, taper=self.taper, taper_radial=self.taper_radial, shape=_form_error( self.form_error, self.form_error_type, lambda x: (np.hypot(*x) - a) / (b - a), ), velocity=_sliding(self.ux, self.uy), n_circ=self.n_circ, n_radial=self.n_radial, **self._common(), )
[docs] @dataclass(frozen=True) class JournalPads(_Case): """Journal bearing of partial-arc pads (``geometry.journal_pads``).""" kind: ClassVar[str] = "journal_pads" title: ClassVar[str] = "Journal pads (partial arcs)" help: ClassVar[str] = ( "Equally spaced partial-arc pads around the shaft; the bushing between " "them is relieved, so every pad edge is at ambient pressure. The first " "pad is centred at its angle from the x axis. Displacement, tilt and " "forces are those of the shaft, as for a full journal. Pad taper tilts " "every pad about its own centre: it is the rise of the gap across the " "pad, and a positive value closes the gap toward increasing angle (the " "direction of positive shaft speed) or along +z." ) # film radius, m radius: float = param(20e-3, "Film radius", *_mm, minimum=1e-4) # bearing length, m length: float = param(40e-3, "Length", *_mm, minimum=1e-4) # radial clearance with the shaft centred, m: the smallest gap of each pad when the # pads are tapered or the bore has form errors clearance: float = param(12e-6, "Radial clearance", *_um, minimum=1e-8) # number of pads, equally spaced n_pads: int = param(3, "Number of pads", minimum=1, maximum=24) # angle spanned by one pad, rad pad_angle: float = param(np.deg2rad(100.0), "Pad angle", *_deg, minimum=0.02) # angle of the centre of the first pad from the x axis, rad offset: float = param(0.0, "Angle of the first pad centre", *_deg) # shaft speed, rad/s omega: float = param(0.0, "Shaft speed", "rad/s", "rpm", 30.0 / np.pi) # rise of the gap across the arc of a pad, m: every pad is tilted about its own # centre, and a positive value closes the gap toward +theta, the direction of # positive shaft speed taper: float = param(0.0, "Pad taper along arc", *_um) # the same along the axis, m: a positive value closes the gap toward +z taper_axial: float = param(0.0, "Pad taper axial", *_um) # conicity of the bore, m: the gap opens by this much along the axis, toward +z if # positive conicity: float = param(0.0, "Conicity (+ opens to +z)", *_um) # out of roundness of the bore, m: the gap varies around it between 0 and this much roundness: float = param(0.0, "Out of roundness", *_um, minimum=0.0) # number of lobes of the out of roundness (2 is oval) lobes: int = param(2, "Lobes", choices=(2, 3)) # angle of a tight spot of the out of roundness, rad lobe_angle: float = param(0.0, "Angle of a tight spot", "rad", "°", 180.0 / np.pi) # crowning, m: a parabola along the axis that opens toward both ends if positive, in # the middle if negative crowning: float = param(0.0, "Crowning (+ opens at ends)", *_um) # how the porous wall curves around the film: "outside", "inside" or "flat" # (``geometry.journal``) wall: str = param( "outside", "Porous wall curvature", choices=WALLS, help=_WALL_HELP ) # elements along the arc of a pad n_circ: int = param(20, "Elements along a pad", minimum=4, maximum=96) # elements along the axis n_axial: int = param(12, "Elements along the axis", minimum=4, maximum=96)
[docs] def film(self) -> Film: return geometry.journal_pads( self.radius, self.length, self.clearance, self.n_pads, self.pad_angle, offset=self.offset, omega=self.omega, taper=self.taper, taper_axial=self.taper_axial, shape=_bore_form(self), wall=self.wall, n_circ=self.n_circ, n_axial=self.n_axial, **self._common(), )
[docs] def default_position(self) -> dict: return {"x": 0.0, "y": 0.0, "rx": 0.0, "ry": 0.0}
[docs] @dataclass(frozen=True) class SphericalBearing(_Case): """Band of a spherical bearing (``geometry.spherical_bearing``).""" kind: ClassVar[str] = "spherical_bearing" title: ClassVar[str] = "Spherical bearing" help: ClassVar[str] = ( "The film is a band of a sphere between two angles measured from the pole " "on the +z axis; 90° is the equator. Displacement x, y, z moves the ball " "centre in the socket. Forces are those of the film on the ball." ) # radius of the sphere, m radius: float = param(25e-3, "Sphere radius", *_mm, minimum=1e-4) # radial clearance with the ball centred, m clearance: float = param(12e-6, "Radial clearance", *_um, minimum=1e-8) # polar angle from the +z axis at which the band starts, rad; the pole itself is # excluded polar_from: float = param( 0.3, "Band start from pole", "rad", "°", 180.0 / np.pi, minimum=1e-3 ) # polar angle at which the band ends, rad (pi/2 is the equator) polar_to: float = param(np.pi / 2, "Band end from pole", "rad", "°", 180.0 / np.pi) # spin speed about z, rad/s omega: float = param(0.0, "Spin speed", "rad/s", "rpm", 30.0 / np.pi) # how the porous seat curves around the film: "outside", "inside" or "flat" wall: str = param( "outside", "Porous wall curvature", choices=WALLS, help=_WALL_HELP ) # elements around n_theta: int = param(48, "Elements around", minimum=12, maximum=360) # elements along the band n_polar: int = param(24, "Elements along band", minimum=4, maximum=96)
[docs] def film(self) -> Film: return geometry.spherical_bearing( self.radius, self.clearance, self.polar_from, self.polar_to, omega=self.omega, wall=self.wall, n_theta=self.n_theta, n_polar=self.n_polar, **self._common(), )
[docs] def default_position(self) -> dict: return {"x": 0.0, "y": 0.0, "z": 0.0}
[docs] @dataclass(frozen=True) class ThrustBushing(_Case): """Journal and thrust face as one film (``geometry.thrust_bushing``).""" kind: ClassVar[str] = "thrust_bushing" title: ClassVar[str] = "Thrust bushing (journal with thrust face)" # one film, so one slip factor and one restrictor model: those of the # bore; the bushing refuses a Knudsen skin hidden: ClassVar[tuple] = ( "porous_thrust.slip", "porous_thrust.model", "porous.knudsen_resistance", "porous_thrust.knudsen_resistance", ) help: ClassVar[str] = ( "The bore and its thrust face are one connected film that meets at the " "inner corner. The rotor round and bushing chamfer leave a ring-shaped " "channel there, which lets gas flow around the shaft; set both to zero " "for a sharp corner. z is the bushing axis and positive z closes the " "thrust gap; x and y move the shaft sideways; tilts are about the corner " "end of the axis. Forces and moments are those on the shaft and runner." ) # restrictor of the bore porous: Porous = field(default_factory=lambda: Porous(kappa=5e-15, hp=3e-3)) # restrictor of the thrust face; its slip and model are replaced by those of the # bore's porous_thrust: Porous = field( default_factory=lambda: Porous(kappa=5e-15, hp=4.5e-3) ) # diameter of the bore, m bore_diameter: float = param(35.020e-3, "Bore diameter", *_mm, minimum=1e-4) # diameter of the shaft, m: smaller than the bore's by twice the radial clearance shaft_diameter: float = param(35.000e-3, "Shaft diameter", *_mm, minimum=1e-4) # length of the bore, m length: float = param(66.68e-3, "Bore length", *_mm, minimum=1e-4) # outer diameter of the thrust face, m thrust_diameter: float = param(76.2e-3, "Thrust face diameter", *_mm, minimum=1e-4) # thrust film thickness at z = 0, m thrust_gap: float = param(3.81e-6, "Thrust film thickness", *_um, minimum=1e-8) # shaft speed, rad/s omega: float = param(0.0, "Shaft speed", "rad/s", "rpm", 30.0 / np.pi) # radius of the round where the shaft meets the runner, m rotor_round: float = param(0.2e-3, "Rotor corner round", *_mm, minimum=0.0) # leg of the 45° chamfer on the corner of the bushing, m: larger than the round, if # there is one bushing_chamfer: float = param(0.5e-3, "Bushing corner chamfer", *_mm, minimum=0.0) # the corner is held at ambient pressure vented: bool = param(False, "Corner vented to ambient") # how the porous wall of the bore curves, as for a journal wall: str = param("outside", "Bore wall curvature", choices=WALLS, help=_WALL_HELP) # "bonded": a sleeve and a thrust ring with a sealed joint between them. # "monolithic": one piece of porous material, with flow in it around the corner # (``geometry.thrust_bushing``). construction: str = param("bonded", "Porous part", choices=("bonded", "monolithic")) # elements around n_theta: int = param(48, "Elements around", minimum=12, maximum=360) # lines of nodes along the bore, outside the chamfer n_journal: int = param(60, "Nodes along bore", minimum=8, maximum=200) # lines of nodes across the thrust face, outside the chamfer n_thrust: int = param(30, "Nodes across thrust", minimum=8, maximum=200) def _arguments(self) -> dict: common = self._common() return dict( porous_journal=common.pop("porous"), porous_thrust=dataclasses.replace( self.porous_thrust, slip=self.porous.slip, model=self.porous.model ), omega=self.omega, rotor_round=self.rotor_round, bushing_chamfer=self.bushing_chamfer, vented=self.vented, wall=self.wall, construction=self.construction, n_theta=self.n_theta, n_journal=self.n_journal, n_thrust=self.n_thrust, **common, ) def _dimensions(self) -> tuple: return ( self.bore_diameter, self.shaft_diameter, self.length, self.thrust_diameter, self.thrust_gap, ) # fmt: skip
[docs] def film(self) -> Film: return geometry.thrust_bushing(*self._dimensions(), **self._arguments())
[docs] def size(self) -> dict: counts = geometry.thrust_bushing_size(*self._dimensions(), **self._arguments()) if counts["body"]: return counts | {"model": "body"} return counts | {"model": self.porous.model}
[docs] def default_position(self) -> dict: return dict.fromkeys(("x", "y", "z", "rx", "ry", "rz"), 0.0)
KINDS = { cls.kind: cls for cls in ( CircularPad, AnnularPad, RectangularPad, Journal, ThrustPads, JournalPads, SphericalBearing, ThrustBushing, ) } # ------------------------------------------------------------- serialisation
[docs] def case_to_dict(case) -> dict: """JSON-ready dict of a case, with its kind. A field that follows another one and was not given is None (null in JSON). """ return {"kind": case.kind, **dataclasses.asdict(case)}
def _coerce(owner, name: str, value): """value as the type of the field ``name`` of the dataclass ``owner``. JSON gives 0 for 0.0: a number is stored as the type of the value the field has now. A field that follows another one (``param(follows=...)``) holds a float or None: None stays None, which makes it follow again, and a number is stored as a float. """ default = getattr(owner, name) if "follows" in type(owner).__dataclass_fields__[name].metadata: return None if value is None else float(value) if isinstance(default, bool): return bool(value) if isinstance(default, int): return int(round(value)) if isinstance(default, float): return float(value) return value def _checked(owner, name: str, value): """value, after checking it against the limits declared on the field.""" meta = type(owner).__dataclass_fields__[name].metadata label = meta.get("label", name) if "choices" in meta and value not in meta["choices"]: raise ValueError(f"{label} must be one of {list(meta['choices'])}.") if isinstance(value, bool) or not isinstance(value, (int, float)): return value if value != value or value in (float("inf"), float("-inf")): raise ValueError(f"{label} must be a finite number.") scale, unit = meta.get("scale", 1.0), meta.get("display", "") for key, bad, word in ( ("minimum", lambda v, m: v < m, "at least"), ("maximum", lambda v, m: v > m, "at most"), ): if key in meta and bad(value, meta[key]): limit = f"{meta[key] * scale:g} {unit}".strip() raise ValueError(f"{label} must be {word} {limit}.") return value def _merge(obj, data: dict): """Copy of a dataclass with the fields in data changed, limits checked. Fields that data leaves out keep the value they have in obj, at every level of nesting. A field that the geometry sets itself (the curvature of a restrictor wall, for example) cannot be given another value here: a document may carry it, as one written by ``case_to_dict`` does, but only with the value it already has. """ fields = {f.name: f for f in dataclasses.fields(obj)} unknown = set(data) - set(fields) if unknown: raise ValueError(f"{type(obj).__name__} has no field {sorted(unknown)}") changes = {} for name, value in data.items(): current = getattr(obj, name) if fields[name].metadata.get("internal"): if value != current: raise ValueError( f"{type(obj).__name__}.{name} is set by the geometry of the " "bearing and cannot be given." ) elif not dataclasses.is_dataclass(current): changes[name] = _checked(obj, name, _coerce(obj, name, value)) else: changes[name] = _merge(current, value) return dataclasses.replace(obj, **changes)
[docs] def case_from_dict(data: dict): """Case from a dict with a "kind", as written by ``case_to_dict``. Missing fields take the case's defaults. An unknown kind or field, or a value outside the limits declared on its field, is a ValueError. """ data = dict(data) kind = data.pop("kind", None) if kind not in KINDS: raise ValueError(f"Unknown case kind {kind!r}; known: {sorted(KINDS)}") return _merge(KINDS[kind](), data)
[docs] def get_path(case, path: str): """Value of a field by dotted path, for example "porous.kappa".""" value = case for name in path.split("."): if not dataclasses.is_dataclass(value) or not hasattr(value, name): raise ValueError(f"{type(case).__name__} has no field {path!r}") value = getattr(value, name) return value
[docs] def set_path(case, path: str, value): """Copy of the case with one field changed, by dotted path. The value is stored as the type of the field and checked against the limits declared on it: outside them, or for an unknown path, it is a ValueError. None is a value only for a field that follows another one ("p_inner" of an annular pad), which then follows it again. """ head, _, rest = path.partition(".") if not dataclasses.is_dataclass(case) or head not in { f.name for f in dataclasses.fields(case) }: raise ValueError(f"{type(case).__name__} has no field {path!r}") current = getattr(case, head) if rest: new = set_path(current, rest, value) else: new = _checked(case, head, _coerce(case, head, value)) return dataclasses.replace(case, **{head: new})
[docs] def describe(case_or_kind) -> list: """Field list of a case or kind: path, label, units, default and limits. One dict per field, with "path", "label", "type", "default", "unit", "display", "scale" and, where declared, "minimum", "maximum", "choices" and "help". Fields the case or the geometry sets itself are left out. This is what a form or a parameter picker is generated from. A field that follows another one while it is not given also has "follows", the path of that field. Its "type" is "float" and its "default" is the value it then takes with the defaults of the kind (that of the field it follows), so that a form can show it as a number; in the case itself the default is None. A form that leaves such a field out of the document it sends gets the following value, whatever the other field is set to. """ cls = KINDS[case_or_kind] if isinstance(case_or_kind, str) else type(case_or_kind) def walk(obj, prefix): rows = [] for f in dataclasses.fields(obj): value = getattr(obj, f.name) path = prefix + f.name if path in cls.hidden: continue if dataclasses.is_dataclass(value): rows.extend(walk(value, path + ".")) continue if f.metadata.get("internal"): continue # set by the geometry, not by the user meta = dict(f.metadata) if "follows" in meta: # siblings: the field it follows is in the same dataclass meta["follows"] = prefix + meta["follows"] if value is None: value = float(getattr(obj, f.metadata["follows"])) rows.append( { "path": path, "label": meta.pop("label", f.name), "type": type(value).__name__, "default": value, **meta, } ) return rows return walk(cls(), "")