"""Measured against modelled static performance of a circular porous pad
=====================================================================

Reproduces Figures 5 and 6 of [1]: load, stiffness and flow over film
thickness at three supply pressures, and the pressure profile at 6 µm. The
measurements are in ex05_experiment_data; the model is the closed form for a
flat parallel pad.

[1] M. Miettinen, V. Vainio, R. Theska, R. Viitala, On the static performance
    of aerostatic elements, Precision Engineering 89 (2024) 1-10.
    doi:10.1016/j.precisioneng.2024.05.017.
"""

import csv
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

from openairbearing import core
from openairbearing.core import reference

DATA = Path(__file__).with_name("ex05_experiment_data")
RADIUS = 36.83e-3 / 2
POROUS = core.Porous(kappa=1.44e-15, hp=4.5e-3)
PA = 101325.0
COLOURS = {0.6: "black", 0.4: "red", 0.2: "blue"}  # gauge supply pressure, MPa
PROFILE_GAP = 6e-6


def measured(quantity, ps_mpa):
    """Two columns of one measurement file, as arrays (# lines are comments)."""
    with open(DATA / f"bearing_{quantity}_{ps_mpa}MPa.csv", newline="") as handle:
        data = (line for line in handle if not line.startswith("#"))
        rows = list(csv.reader(data))[1:]
    return np.array(rows, dtype=float).T


def main(n_gaps=57):
    gaps = np.linspace(1e-6, 15e-6, n_gaps)
    fig, axes = plt.subplots(2, 2, figsize=(10, 8))
    for ps_mpa, colour in COLOURS.items():
        ps = PA + ps_mpa * 1e6
        pads = [reference.circular_pad(RADIUS, h, porous=POROUS, ps=ps) for h in gaps]
        stiff = [
            reference.stiffness(reference.circular_pad, h, RADIUS, porous=POROUS, ps=ps)
            for h in gaps
        ]
        profile = reference.circular_pad(RADIUS, PROFILE_GAP, porous=POROUS, ps=ps)
        um = gaps * 1e6
        curves = [
            (axes[0, 0], um, [p.load for p in pads], "w"),
            (axes[0, 1], um, np.array(stiff) * 1e-6, "k"),
            (axes[1, 0], um, [p.flow_normal * 6e4 for p in pads], "q"),
            (axes[1, 1], profile.x * 1e3, (profile.p - PA) * 1e-6, "p"),
        ]
        for ax, x, y, quantity in curves:
            ax.plot(x, y, color=colour, label=f"model, {ps_mpa} MPa")
            ax.plot(*measured(quantity, ps_mpa), "o", color=colour, mfc="none")
    labels = [
        ("Film thickness [µm]", "Load [N]"),
        ("Film thickness [µm]", "Stiffness [N/µm]"),
        ("Film thickness [µm]", "Flow [L/min]"),
        ("Radius [mm]", f"Gauge pressure at {PROFILE_GAP * 1e6:.0f} µm [MPa]"),
    ]
    for ax, (xlabel, ylabel) in zip(axes.ravel(), labels, strict=True):
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
    axes[0, 0].legend(title="circles: measured")
    fig.tight_layout()
    plt.show()


if __name__ == "__main__":
    main()
