"""Multi-geometry parameter sweep and sensitivity analysis
=======================================================

Circular, annular and (optionally) rectangular porous pads are swept over
their face dimensions, restrictor thickness, permeability and supply
pressure. For every case the peak of the stiffness curve is located exactly
(not read off a grid), which gives four metrics:

1. maximum stiffness, k_max
2. film thickness at maximum stiffness
3. k_max per face area
4. k_max per perimeter (edge length open to ambient)

The peak is searched for between 0.5 and 20 µm. A design whose stiffness is
still rising at either end of that band has its optimum film outside what a
bearing can run at; such designs are counted and left out of the ranking and
the level means, because their "maximum" would only be where the search
stopped.

Rule of thumb that comes out of the sweep: the film thickness of maximum
stiffness is about 0.9 (kappa w² / hp)^(1/3), with w the radius of a circular
pad or the land width of an annular one. Permeability therefore has to be
matched to the face size; the sweep spaces it logarithmically for that reason.

Outputs: the best cases, the span of each metric over the levels of each
parameter, and a figure of the mean of each metric at each parameter level.

Circular and annular pads use the closed forms of ``core.reference``;
rectangular pads are solved with finite elements, which is much slower, so
they are left out unless asked for: main(geometries=("rectangular",)).

Set OAB_QUICK=1, or call main(quick=True), for a small sweep solved in this
process.
"""

import os
from concurrent.futures import ProcessPoolExecutor
from itertools import product, repeat

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize_scalar

from openairbearing import core
from openairbearing.core import reference
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)

PA = 101325.0
H_BAND = (0.5e-6, 20e-6)  # film thicknesses a bearing can sensibly run at, m
PERMEABILITY = 3  # index of the permeability column of a case
# (low, high) of the two face dimensions of each geometry, m
FACES = {
    "circular": ((0.0, 0.0), (10e-3, 200e-3)),  # (no bore, radius)
    "annular": ((4e-3, 100e-3), (10e-3, 200e-3)),  # (inner, outer radius)
    "rectangular": ((10e-3, 200e-3), (10e-3, 200e-3)),  # (length x, length y)
}
# restrictor thickness m, permeability m², supply pressure Pa (abs)
SHARED = ((2e-3, 8e-3), (1e-16, 1e-14), (PA + 0.4e6, PA + 0.6e6))
# label and display factor of the five parameters and the four metrics
PARAMS = (
    ("ri or lx [mm]", 1e3),
    ("ro or ly [mm]", 1e3),
    ("Restrictor thickness [mm]", 1e3),
    ("Permeability [m²]", 1.0),
    ("Supply pressure, abs [MPa]", 1e-6),
)
METRICS = (
    ("k_max [N/µm]", 1e-6),
    ("Film thickness at k_max [µm]", 1e6),
    ("k_max / area [N/(µm·mm²)]", 1e-12),
    ("k_max / perimeter [N/(µm·mm)]", 1e-9),
)


def make_cases(geometry, n_levels, max_cases, rng):
    """Rows of (a, b, hp, kappa, ps): the full grid, or a random part of it."""
    levels = [np.unique(np.linspace(*r, n_levels)) for r in FACES[geometry] + SHARED]
    levels[PERMEABILITY] = np.geomspace(*SHARED[1], n_levels)
    cases = np.array(list(product(*levels)))
    if geometry == "annular":
        cases = cases[cases[:, 0] < 0.95 * cases[:, 1]]
    if len(cases) > max_cases:
        cases = cases[np.sort(rng.choice(len(cases), max_cases, replace=False))]
    return cases


def metrics(geometry, a, b, hp, kappa, ps):
    """(k_max, film thickness at k_max, k_max/area, k_max/perimeter, inside).

    SI units. inside is 1.0 when the stiffness peak lies within H_BAND and 0.0
    when stiffness is still rising at one end of it.
    """
    kwargs = {"porous": core.Porous(kappa, hp), "ps": ps, "pa": PA}
    area, perimeter = np.pi * (b**2 - a**2), 2.0 * np.pi * (a + b)
    if geometry == "circular":

        def stiffness(h):
            return reference.stiffness(reference.circular_pad, h, b, **kwargs)

    elif geometry == "annular":

        def stiffness(h):
            return reference.stiffness(reference.annular_pad, h, a, b, **kwargs)

    else:
        film = core.rectangular_pad(a, b, nx=20, ny=20, **kwargs)
        area, perimeter = a * b, 2.0 * (a + b)

        def stiffness(h):
            return core.stiffness(film, [h, 0.0, 0.0])[0, 0]

    # Bracket the peak on a coarse logarithmic grid, then refine inside it.
    grid = np.geomspace(*H_BAND, 13)
    i = int(np.argmax([stiffness(h) for h in grid]))
    lo, hi = grid[max(i - 1, 0)], grid[min(i + 1, len(grid) - 1)]
    best = minimize_scalar(
        lambda log_h: -stiffness(np.exp(log_h)),
        bounds=(np.log(lo), np.log(hi)),
        method="bounded",
        options={"xatol": 1e-4},
    )
    h, k = float(np.exp(best.x)), -float(best.fun)
    inside = float(H_BAND[0] * 1.02 < h < H_BAND[1] / 1.02)
    return k, h, k / area, k / perimeter, inside


def level_means(x, y):
    """Mean of y at each distinct value of the parameter x."""
    levels = np.unique(x)
    return levels, np.array([y[x == level].mean() for level in levels])


def print_summary(geometry, cases, results, outside):
    low, high = outside
    print(
        f"\n{geometry}: {len(cases)} cases with the stiffness peak inside "
        f"{H_BAND[0] * 1e6:g}-{H_BAND[1] * 1e6:g} µm; left out: {low} peaking "
        f"below it, {high} above it."
    )
    if len(cases) == 0:
        return
    print("  Best by k_max / area:")
    for i in np.argsort(-results[:, 2])[:5]:
        shown = [v * scale for v, (_, scale) in zip(results[i], METRICS, strict=True)]
        print(
            f"  k_max {shown[0]:8.2f} N/µm at {shown[1]:5.2f} µm, "
            f"per area {shown[2]:.3e}, per perimeter {shown[3]:.3e}, "
            f"ps {(cases[i, 4] - PA) * 1e-6:.2f} MPa gauge"
        )
    print("  Span of the level means, relative to the overall mean:")
    header = ("k_max", "h at k_max", "k_max/area", "k_max/perim.")
    print(f"  {'':28s}" + "".join(f"{name:>14s}" for name in header))
    for j, (label, _) in enumerate(PARAMS):
        if np.ptp(cases[:, j]) == 0.0:
            continue  # a circular pad has no inner radius to vary
        spans = [np.ptp(level_means(cases[:, j], y)[1]) / y.mean() for y in results.T]
        print(f"  {label:28s}" + "".join(f"{span:>14.1%}" for span in spans))


def plot_sensitivity(sweep):
    """Mean of each metric (rows) at each level of each parameter (columns)."""
    fig, axes = plt.subplots(len(METRICS), len(PARAMS), figsize=(16, 11), sharey="row")
    for geometry, (cases, results) in sweep.items():
        for (i, (metric, m_scale)), (j, (param, p_scale)) in product(
            enumerate(METRICS), enumerate(PARAMS)
        ):
            x, y = level_means(cases[:, j], results[:, i])
            if x.size > 1:  # a circular pad has no inner radius to vary
                axes[i, j].plot(x * p_scale, y * m_scale, "o-", label=geometry)
            axes[i, j].set(xlabel=param, ylabel=metric if j == 0 else None)
            if j == PERMEABILITY:
                axes[i, j].set_xscale("log")
    axes[0, 1].legend()
    fig.tight_layout()
    return fig


def main(quick=None, geometries=("circular", "annular"), workers=None):
    quick = bool(os.environ.get("OAB_QUICK")) if quick is None else quick
    workers = workers or (1 if quick else os.cpu_count())
    n_levels, max_cases = (3, 15) if quick else (5, 500)
    rng = np.random.default_rng(67)
    sweep = {}
    for geometry in geometries:
        cases = make_cases(geometry, n_levels, max_cases, rng)
        args = (repeat(geometry), *cases.T)
        if workers > 1:
            with ProcessPoolExecutor(workers) as pool:
                results = list(pool.map(metrics, *args, chunksize=8))
        else:
            results = list(map(metrics, *args))
        results = np.array(results)
        inside = results[:, 4] > 0.5
        outside = (
            int(np.sum(~inside & (results[:, 1] < np.sqrt(H_BAND[0] * H_BAND[1])))),
            int(np.sum(~inside & (results[:, 1] > np.sqrt(H_BAND[0] * H_BAND[1])))),
        )
        sweep[geometry] = (cases[inside], results[inside, :4])
        print_summary(geometry, *sweep[geometry], outside)
    plot_sensitivity(sweep)
    plt.show()
    return sweep


if __name__ == "__main__":
    main()
