"""Journal bearing with form errors of the bore
============================================

A round bore is compared with a two-lobed (oval) and a three-lobed bore and
with a conical one, all of 2 µm amplitude. The shaft is moved along x and the
restoring force and supply flow are plotted against eccentricity.
"""

import matplotlib.pyplot as plt
import numpy as np

from openairbearing import core
from openairbearing.plots import COLOURS

# the series of every plot in blue, red, black and grey, in that order
plt.rcParams["axes.prop_cycle"] = plt.cycler(color=COLOURS)

RADIUS = 25e-3
LENGTH = 89e-3
CLEARANCE = 15e-6  # radial, at the tightest point of the bore
ERROR = 2e-6
PS = 0.6e6 + 101325.0
# 11 L/min of free air through the bare bushing
# (the sleeve is a cylindrical shell: the same wall as the bearing model uses)
POROUS = core.Porous.from_free_flow(
    11.0 / 6e4,
    area=2 * np.pi * RADIUS * LENGTH,
    p_supply=PS,
    hp=4.5e-3,
    radius=RADIUS,
    wall="outside",
)


def lobes(n):
    """Bore radius error with n lobes: 0 at the tight spots, ERROR between them."""
    return lambda x: 0.5 * ERROR * (1.0 - np.cos(n * x[0] / RADIUS))


def cone(x):
    """Bore opening linearly from one end to the other."""
    return ERROR * (x[1] / LENGTH + 0.5)


SHAPES = {"round": None, "oval": lobes(2), "three lobes": lobes(3), "conical": cone}


def main(n_points=13):
    eccentricity = np.linspace(0.0, 0.8 * CLEARANCE, n_points)
    fig, axes = plt.subplots(1, 3, figsize=(13, 4))
    for name, shape in SHAPES.items():
        film = core.journal(
            RADIUS, LENGTH, CLEARANCE, porous=POROUS, ps=PS, shape=shape
        )
        states = [core.solve_static(film, [e, 0.0, 0.0, 0.0]) for e in eccentricity]
        force = np.array([-s.force("x") for s in states])
        um = eccentricity * 1e6
        axes[0].plot(um, force, label=name)
        axes[1].plot(um, np.gradient(force, eccentricity) * 1e-6, label=name)
        axes[2].plot(um, [s.flow_normal * 6e4 for s in states], label=name)
    for ax, label in zip(
        axes,
        ["Restoring force [N]", "Radial stiffness [N/µm]", "Supply flow [L/min]"],
        strict=True,
    ):
        ax.set_xlabel("Shaft displacement along x [µm]")
        ax.set_ylabel(label)
    axes[0].legend()
    fig.tight_layout()
    plt.show()


if __name__ == "__main__":
    main()
