r"""
Faraday's dielectrics: a capacitor half filled with an insulator
================================================================

In 1837 Michael Faraday filled the gap of a spherical capacitor with
shellac, sulfur and glass and found that it held more charge at the same
voltage. He called the ratio the *specific inductive capacity*, today's
relative permittivity :math:`\varepsilon_r`, and explained it by the
insulator's particles polarizing in the field. Mossotti (1850) and
Clausius (1879) later tied :math:`\varepsilon_r` to the polarizability of
those particles.

A slab filling half the gap of a parallel-plate capacitor behaves like two
capacitors in series, and one filling half the area like two in parallel:

.. math::

    C_{\rm series} = \frac{\varepsilon_0 A}{d/2 + d/(2\varepsilon_r)},
    \qquad
    C_{\rm parallel} = \frac{(\varepsilon_r + 1)\,\varepsilon_0 A}{2d}.

:func:`~physicskit.fields.solve_poisson_dielectric` solves
:math:`\nabla\cdot(\varepsilon\nabla\phi) = -\rho` on a grid with a
position-dependent :math:`\varepsilon_r`, and the charge on a plate is the
displacement flux :math:`\mathbf D = -\varepsilon\nabla\phi` leaving it.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.fields import solve_poisson_dielectric
from physicskit.fields.electrodynamics import EPS0
from physicskit.fields.electrostatics import electric_field_from_potential

eps_r, V = 5.0, 1.0

# %%
# Dielectric filling half the gap (series)
# ----------------------------------------
# The plates are at x = 0 (held at V) and x = d (grounded). The side walls
# take the 1D piecewise-linear potential, as if the plates were infinite.

n, h = 101, 0.01
eps_s = np.ones((n, 21))
eps_s[: n // 2, :] = eps_r
phi0 = np.zeros(eps_s.shape)
phi0[0, :] = V
xi = np.cumsum(np.r_[0.0, h / eps_s[:-1, 0]])
phi0[:, 0] = phi0[:, -1] = V * (1 - xi / xi[-1])
sol_s = solve_poisson_dielectric(np.zeros(eps_s.shape), eps_s, h, phi0=phi0, tol=1e-12)
d_s = (n - 1) * h
j = eps_s.shape[1] // 2
sigma = EPS0 * 2 / (1 / eps_s[0, j] + 1 / eps_s[1, j]) * (sol_s.phi[0, j] - sol_s.phi[1, j]) / h
C_series = EPS0 / (d_s / 2 + d_s / (2 * eps_r))
print(f"series:   C/A = {sigma / V:.4e} F/m^2, closed form {C_series:.4e}")

# %%
# Dielectric filling half the area (parallel)
# -------------------------------------------

n, ny, h = 51, 201, 0.02
x = np.arange(n) * h
d_p = x[-1]
eps_p = np.ones((n, ny))
eps_p[:, : ny // 2] = eps_r
phi0 = np.zeros((n, ny))
phi0[0, :] = V
phi0[:, 0] = phi0[:, -1] = V * (1 - x / d_p)
sol_p = solve_poisson_dielectric(np.zeros((n, ny)), eps_p, h, phi0=phi0, tol=1e-12)
D = EPS0 * eps_p * electric_field_from_potential(sol_p.phi, h)[0]
A = (ny - 2) * h
Q = np.sum(D[n // 2, 1:-1]) * h
C_parallel = (eps_r + 1) * EPS0 * A / (2 * d_p)
print(f"parallel: C   = {Q / V:.4e} F/m,   closed form {C_parallel:.4e}")

fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(11, 4.5))
xs = np.arange(eps_s.shape[0]) * 0.01
ax0.plot(xs, sol_s.phi[:, j], "k-", label="grid solution")
ax0.axvspan(0, xs[50], color="tab:blue", alpha=0.15, label=rf"$\varepsilon_r = {eps_r:g}$")
ax0.set_xlabel("x (m)")
ax0.set_ylabel(r"$\phi$ (V)")
ax0.set_title("series: the field drops by $\\varepsilon_r$ inside the slab")
ax0.legend()
im = ax1.imshow(D.T * 1e12, origin="lower", extent=[0, d_p, 0, (ny - 1) * h], aspect="auto", cmap="viridis")
ax1.axhline((ny // 2) * h, color="w", ls="--")
ax1.set_xlabel("x (m)")
ax1.set_ylabel("y (m)")
ax1.set_title(r"parallel: $D_x$ is $\varepsilon_r$ times larger in the dielectric")
fig.colorbar(im, ax=ax1, label=r"$D_x$ (pC/m$^2$)")
fig.tight_layout()
plt.show()

# %%
# Check
# -----
# The half-gap slab gives the series capacitance and the half-area slab
# the parallel capacitance, each to 1%.
assert sol_s.converged and sol_p.converged
assert abs(sigma / V / C_series - 1) < 0.01
assert abs(Q / V / C_parallel - 1) < 0.01
