"""Circular thrust pad with form errors of the face
================================================

A flat pad is compared with a concave, a convex and a saddle-shaped face of
the same 2 µm amplitude. Film thickness is the smallest gap in every case.
The concave and convex shapes are built-in case options; the saddle shows
how any shape function of position can be passed to a geometry builder.
"""

import matplotlib.pyplot as plt
import numpy as np

from openairbearing import core
from openairbearing.core import cases
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 = 18e-3
ERROR = 2e-6


def saddle(x):
    """Zero on one diagonal pair of lobes, ERROR on the other; smallest gap 0."""
    return 0.5 * ERROR * (1.0 + (x[0] ** 2 - x[1] ** 2) / RADIUS**2)


def make_films():
    base = cases.CircularPad(radius=RADIUS)
    common = dict(porous=base.porous, ps=base.ps, pa=base.pa)
    return {
        "flat": base.film(),
        "concave": cases.set_path(
            cases.set_path(base, "form_error", ERROR), "form_error_type", "quadratic"
        ).film(),
        "convex": cases.set_path(
            cases.set_path(base, "form_error", -ERROR), "form_error_type", "quadratic"
        ).film(),
        "saddle": core.circular_pad(RADIUS, shape=saddle, **common),
    }


def main(n_gaps=25):
    gaps = np.linspace(1e-6, 12e-6, n_gaps)
    fig, axes = plt.subplots(1, 3, figsize=(13, 4))
    for name, film in make_films().items():
        states = [core.solve_static(film, [h, 0.0, 0.0]) for h in gaps]
        load = np.array([s.force("h") for s in states])
        axes[0].plot(gaps * 1e6, load, label=name)
        axes[1].plot(gaps * 1e6, -np.gradient(load, gaps) * 1e-6, label=name)
        axes[2].plot(gaps * 1e6, [s.flow_normal * 6e4 for s in states], label=name)
    for ax, label in zip(
        axes, ["Load [N]", "Stiffness [N/µm]", "Supply flow [L/min]"], strict=True
    ):
        ax.set_xlabel("Smallest film thickness [µm]")
        ax.set_ylabel(label)
    axes[0].legend()
    fig.tight_layout()
    plt.show()


if __name__ == "__main__":
    main()
