r"""
Johann Bernoulli's brachistochrone: the cycloid is the fastest slide
====================================================================

In 1696 Johann Bernoulli challenged the mathematicians of Europe to find
the wire along which a bead slides from rest, under gravity alone, between
two points in the least time. The answer is the cycloid
:math:`x = R(\theta - \sin\theta)`, :math:`y = R(1 - \cos\theta)` (with
:math:`y` downward). It is not the straight line, which is the shortest
path, because falling steeply first builds up speed early.
:func:`~physicskit.classical.systems.variational.minimize_descent_time`
poses the problem directly: it varies the depths of a polygonal wire to
minimize the exact descent time
(:func:`~physicskit.classical.systems.variational.descent_time`) and
recovers the cycloid of
:func:`~physicskit.classical.systems.variational.brachistochrone_curve`.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.classical.systems.variational import brachistochrone_curve, descent_time, minimize_descent_time

g, R = 9.81, 1.0
x_end, y_end = np.pi * R, 2 * R  # the bottom of the first arch
T0 = np.sqrt(R / g)

# %%
# Racing four wires
# -----------------
#
# Each wire ends at the same point; the quarter ellipse, like the cycloid,
# starts straight down. The straight line takes
# :math:`\sqrt{\pi^2 + 4}\,\sqrt{R/g}`, the cycloid :math:`\pi\sqrt{R/g}`.
# The polygon found by the minimizer, started from the straight line,
# lands on the cycloid.

cyc = brachistochrone_curve(x_end, y_end, g=g)
best = minimize_descent_time(x_end, y_end, n=80, g=g, initial="line")
xs = np.linspace(0, x_end, 400)
phi = np.linspace(0, np.pi / 2, 400)
wires = {
    "straight line": (xs, y_end * xs / x_end),
    "parabola $y \\propto \\sqrt{x}$": (xs, y_end * np.sqrt(xs / x_end)),
    "quarter ellipse": (x_end * np.sin(phi), y_end * (1 - np.cos(phi))),
    "cycloid": (cyc.x, cyc.y),
}
fig, ax = plt.subplots(figsize=(9, 5))
for (name, (x, y)), c in zip(wires.items(), ["C0", "C1", "C2", "C3"]):
    ax.plot(x, y, color=c, lw=2, label=f"{name}: T = {descent_time(x, y, g) / T0:.4f} $\\sqrt{{R/g}}$")
ax.plot(best.x, best.y, "k.", ms=4, label=f"minimized polygon (80 segments): T = {best.time / T0:.4f}")
ax.invert_yaxis()
ax.set_aspect("equal")
ax.set_xlabel("x / R")
ax.set_ylabel("depth y / R")
ax.set_title(r"Descent from rest to $(\pi R, 2R)$; cycloid $T = \pi\sqrt{R/g}$")
ax.legend(fontsize=8, loc="upper right")
fig.tight_layout()

# %%
# Convergence of the discrete problem
# ------------------------------------
#
# With :math:`n` segments the minimized time approaches
# :math:`\pi\sqrt{R/g}` from above, and the error falls as :math:`1/n^2`.

ns = np.array([10, 20, 40, 80, 160])
err = np.array([minimize_descent_time(x_end, y_end, n=int(n), g=g).time / (np.pi * T0) - 1 for n in ns])
fig2, ax2 = plt.subplots(figsize=(6, 4))
ax2.loglog(ns, err, "o-", label="minimized polygon")
ax2.loglog(ns, err[0] * (ns[0] / ns) ** 2, "k:", label=r"$\propto n^{-2}$")
ax2.set_xlabel("segments n")
ax2.set_ylabel(r"$T/\pi\sqrt{R/g} - 1$")
ax2.legend()
fig2.tight_layout()

# %%
# Huygens's tautochrone
# ---------------------
#
# The same cycloid has a second property, found by Huygens in 1673. A
# bead released from rest *anywhere* on it reaches the bottom in the same
# time :math:`\pi\sqrt{R/g}`. Beads started higher move faster and
# exactly make up the extra distance.

theta0 = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0])
times = []
for t0 in theta0:
    th = np.linspace(t0, np.pi, 20_001)
    times.append(descent_time(R * (th - np.sin(th)), R * (1 - np.cos(th)), g))
times = np.array(times)
fig3, ax3 = plt.subplots(figsize=(6, 4))
ax3.plot(theta0, times / T0, "o-")
ax3.axhline(np.pi, color="k", ls=":", label=r"$\pi$")
ax3.set_ylim(2.5, 3.5)
ax3.set_xlabel(r"release angle $\theta_0$")
ax3.set_ylabel(r"time to bottom / $\sqrt{R/g}$")
ax3.set_title("Same time from every starting height")
ax3.legend()
fig3.tight_layout()

# %%
# Check
# -----
# Cycloid time pi sqrt(R/g); straight line sqrt(pi^2 + 4) sqrt(R/g); the
# minimized polygon beats every other wire and lies on the cycloid; the
# error falls as 1/n^2; the tautochrone time does not depend on the start.
t_line = descent_time(*wires["straight line"], g)
assert abs(cyc.time / T0 - np.pi) < 1e-12
assert abs(t_line / T0 - np.sqrt(np.pi**2 + 4)) < 1e-12
assert all(best.time < descent_time(*wires[k], g) for k in wires if k != "cycloid")
assert abs(best.time / cyc.time - 1) < 3e-5
assert np.max(np.abs(best.y - np.interp(best.x, cyc.x, cyc.y))) < 1e-3
assert abs(err[-2] / err[-1] - 4) < 0.2
assert np.max(np.abs(times / T0 - np.pi)) < 1e-5
