r"""
Ambipolar diffusion: a plasma slab decaying to its walls
===========================================================

Electrons, being light, diffuse out of a plasma much faster than ions.
If they did so freely the plasma would charge positive, so instead an
electric field builds up that holds the electrons back and pulls the ions
out, and the two leave together. Setting the electron and ion fluxes
:math:`\Gamma_j = \pm\mu_j nE - D_j\nabla n` equal gives the ambipolar
field and a single diffusion coefficient (Chen, section 5.2)

.. math::

    E = \frac{D_i - D_e}{\mu_i + \mu_e}\frac{\nabla n}{n}, \qquad
    D_a = \frac{\mu_i D_e + \mu_e D_i}{\mu_i + \mu_e}.

With the Einstein relation :math:`\mu = eD/kT` and :math:`T_e = T_i`,
:math:`D_a \approx 2D_i`. A slab of width :math:`L` between absorbing walls
then relaxes to its lowest mode :math:`\cos(\pi x/L)`, which decays in
:math:`\tau = (L/\pi)^2/D_a`. This example runs
:func:`~physicskit.plasma.collisions.simulate_ambipolar_slab_decay` from a
flat profile.
"""

# %%
import matplotlib.pyplot as plt
import numpy as np

from physicskit.plasma.collisions import ambipolar_diffusion_coefficient, simulate_ambipolar_slab_decay

# %%
# Diffusion coefficients
# -------------------------
# A weakly ionized argon discharge at 1 eV: :math:`D_e = 10^3 D_i`, and
# mobilities from the Einstein relation with :math:`kT/e = 1` V.
T = 1.0
D_i = 0.01
D_e = 1e3 * D_i
mu_e, mu_i = D_e / T, D_i / T
D_a = ambipolar_diffusion_coefficient(D_e, D_i, mu_e, mu_i)
print(f"D_e = {D_e:.2f}, D_i = {D_i:.3f}, D_a = {D_a:.4f} m^2/s  (D_a / D_i = {D_a / D_i:.4f})")

# %%
# The slab
# -----------
L = 0.05
tau = (L / np.pi) ** 2 / D_a
x, t, n = simulate_ambipolar_slab_decay(lambda x: 1e16 * np.ones_like(x), L, D_e, D_i, mu_e, mu_i, 3 * tau, steps=3000, n_save=31)
center = n[:, n.shape[1] // 2]
rate = -np.polyfit(t[10:], np.log(center[10:]), 1)[0]
print(f"lowest-mode decay time: simulated {1 / rate * 1e3:.4f} ms, (L/pi)^2/D_a = {tau * 1e3:.4f} ms")

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(14, 4))
for k in (0, 1, 3, 6, 10, 20, 30):
    ax1.plot(x * 100, n[k] / 1e16, label=f"t = {t[k] / tau:.1f} τ")
ax1.set_xlabel("x [cm]")
ax1.set_ylabel(r"$n / n_0$")
ax1.set_title("Profile relaxes to cos(πx/L)")
ax1.legend(fontsize=7)

ax2.semilogy(t / tau, center / center[0], "o", ms=3, label="simulation (center)")
ax2.semilogy(t / tau, center[10] / center[0] * np.exp(-(t - t[10]) / tau), "k--", label=r"$e^{-t/\tau}$")
ax2.set_xlabel(r"$t/\tau$")
ax2.set_ylabel(r"$n(0, t)/n_0$")
ax2.set_title(r"$\tau = (L/\pi)^2/D_a$")
ax2.legend(fontsize=8)

# %%
# The ambipolar field
# ----------------------
# From the late profile, :math:`E = (D_i - D_e)/(\mu_i + \mu_e)\,\partial_x\ln n`
# points outward and is about :math:`(kT/e)\,\pi\tan(\pi x/L)/L`, large
# near the walls where the density is small.
inner = slice(5, -5)
E = (D_i - D_e) / (mu_i + mu_e) * np.gradient(np.log(n[-1][inner]), x[inner])
ax3.plot(x[inner] * 100, E, label="from simulated profile")
ax3.plot(x[inner] * 100, T * (D_e - D_i) / (D_e + D_i) * np.pi / L * np.tan(np.pi * x[inner] / L), "k--", label="cosine mode")
ax3.set_xlabel("x [cm]")
ax3.set_ylabel("E [V/m]")
ax3.set_title("Ambipolar field")
ax3.legend(fontsize=8)
fig.tight_layout()

plt.show()

# %%
# Check
# -----
# D_a = 2 D_i (to 1/1000 for D_e = 1000 D_i) at equal temperatures, and the
# slab's lowest mode decays in (L / pi)^2 / D_a.
assert abs(D_a / D_i - 2 * 1e3 / (1 + 1e3)) < 1e-12 and abs(D_a / D_i - 2) < 2e-3
assert abs(rate * tau - 1) < 1e-3
assert np.allclose(n[-1] / n[-1].max(), np.cos(np.pi * x / L), atol=2e-3)
