r"""
Circle map: the complete devil's staircase at K = 1
===================================================

Plotted against :math:`\Omega`, the winding number of the sine circle map
:math:`\theta_{n+1} = \theta_n + \Omega - (K/2\pi)\sin 2\pi\theta_n` is
flat on every mode-locked interval. Every rational has a step, so the
curve is a devil's staircase. Below :math:`K = 1` the steps leave gaps of
positive total length, where the motion is quasiperiodic. Jensen, Bak and
Bohr (1983) showed that at the critical coupling :math:`K = 1` the steps
fill the whole :math:`\Omega` axis. What is left between them is a Cantor
set of measure zero whose fractal dimension, :math:`D \approx 0.87`, is
universal: it is the same for every circle map with a cubic inflection
point.
"""

from math import gcd

import matplotlib.pyplot as plt
import numpy as np

from physicskit.chaos.systems.maps import mode_locking_interval, winding_number

# %%
# The staircase
# -------------
#
# The winding number from
# :func:`~physicskit.chaos.systems.maps.winding_number` on a fine grid of
# :math:`\Omega`, at :math:`K = 1` and at :math:`K = 0.5`, where the steps
# are narrower and the curve rises between them. The inset zooms into the
# region between the 1/2 and 1/3 steps.

Omega = np.linspace(0, 1, 2001)
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
for K, color in [(0.5, "C1"), (1.0, "C0")]:
    axes[0].plot(Omega, winding_number(K, Omega), color=color, lw=1, label=f"K = {K}")
axes[0].plot(Omega, Omega, "k:", lw=0.8, label="K = 0")
axes[0].set_xlabel(r"$\Omega$")
axes[0].set_ylabel("winding number W")
axes[0].set_title("Devil's staircase of the sine circle map")
axes[0].legend(fontsize=8, loc="upper left")
inset = axes[0].inset_axes([0.57, 0.08, 0.4, 0.4])
Omega_zoom = np.linspace(0.35, 0.465, 1500)
inset.plot(Omega_zoom, winding_number(1.0, Omega_zoom, n_iter=4000), lw=0.8)
inset.set_xticks([0.35, 0.465])
inset.set_yticks([1 / 3, 0.5])
inset.set_yticklabels(["1/3", "1/2"])
inset.tick_params(labelsize=7)

# %%
# Scaling of the gaps
# -------------------
#
# The exact width of every step with :math:`q \leq 30` is found by
# :func:`~physicskit.chaos.systems.maps.mode_locking_interval`. If
# :math:`S(r)` is the total width of all steps wider than :math:`r`, the
# part of the axis not yet covered at resolution :math:`r` needs
# :math:`N(r) = (1 - S(r))/r` intervals of size :math:`r`, and
# :math:`N(r) \propto r^{-D}` defines the dimension of the unlocked set.

widths = []
for q in range(1, 31):
    for p in range(q):
        if gcd(p, q) == 1:
            lo, hi = mode_locking_interval(p, q, 1.0)
            widths.append(hi - lo)
widths = np.array(widths)
r = np.logspace(-4, -2.2, 10)
N = np.array([(1 - widths[widths > ri].sum()) / ri for ri in r])
slope, intercept = np.polyfit(np.log(r), np.log(N), 1)
D = -slope
axes[1].loglog(r, N, "o", label="steps with q ≤ 30")
axes[1].loglog(r, np.exp(intercept) * r**slope, "k--", label=f"fit: D = {D:.3f}")
axes[1].set_xlabel("resolution r")
axes[1].set_ylabel(r"$N(r) = (1 - S(r))/r$")
axes[1].set_title("Unlocked set at K = 1: D ≈ 0.87")
axes[1].legend(fontsize=8)
fig.tight_layout()

# %%
# Check
# -----
# At K = 1 the staircase is monotone and flat on the 1/2 step, the steps
# with q <= 30 already cover over 70% of the axis (against under 50% at
# K = 0.5, where the gaps keep a positive measure), and the unlocked set has
# dimension D = 0.87 (Jensen, Bak and Bohr 1983).
W1 = winding_number(1.0, Omega)
assert np.all(np.diff(W1) > -1e-3)
lo, hi = mode_locking_interval(1, 2, 1.0)
assert np.allclose(winding_number(1.0, np.linspace(lo, hi, 9)[1:-1], n_iter=20000), 0.5, atol=1e-4)
widths_half = [np.subtract(*mode_locking_interval(p, q, 0.5)[::-1]) for q in range(1, 16) for p in range(q) if gcd(p, q) == 1]
assert widths.sum() > 0.7 and sum(widths_half) < 0.5
assert abs(D - 0.87) < 0.02
