r"""
Shockley's p-n junction: depletion layer and the diode law
==========================================================

Shockley (1949) worked out the abrupt p-n junction. Diffusion empties a
*depletion layer* of carriers, leaving the bare dopant charge, whose field
builds up the potential :math:`V_{bi} = (k_BT/q)\ln(N_AN_D/n_i^2)` across
a width :math:`W = \sqrt{2\varepsilon(V_{bi}-V)(N_A+N_D)/qN_AN_D}`
(:func:`~physicskit.condensed.semiconductors.pn_junction`). A numerical
solution of Poisson's equation with Boltzmann carriers
(:func:`~physicskit.condensed.semiconductors.solve_pn_poisson`) shows how
good the depletion approximation is. Minority-carrier diffusion out of the
layer gives the rectifying diode law :math:`J = J_s(e^{qV/k_BT} - 1)`
(:func:`~physicskit.condensed.semiconductors.shockley_current`).
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.constants import e, k

from physicskit.condensed.semiconductors import pn_junction, shockley_current, solve_pn_poisson

N_A = N_D = 1e22  # 1e16 cm^-3
n_i = 1e16  # 1e10 cm^-3
jn = pn_junction(N_A, N_D, n_i=n_i)
sol = solve_pn_poisson(N_A, N_D, n_i=n_i)
x_um = sol.x * 1e6

# %%
# Charge, field and potential
# ---------------------------

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
axes[0].plot(x_um, sol.charge_density / e * 1e-6, lw=2, label="Poisson")
axes[0].plot(x_um, jn.charge_density(sol.x) / e * 1e-6, "k--", lw=1, label="depletion approx.")
axes[0].set_ylabel(r"$\rho / q$  (cm$^{-3}$)")
axes[1].plot(x_um, sol.electric_field * 1e-5, lw=2)
axes[1].plot(x_um, jn.electric_field(sol.x) * 1e-5, "k--", lw=1)
axes[1].set_ylabel("E (kV/cm)")
axes[2].plot(x_um, sol.potential, lw=2)
axes[2].plot(x_um, jn.potential(sol.x), "k--", lw=1)
axes[2].set_ylabel(r"$\phi$ (V)")
for ax in axes:
    ax.set_xlim(-0.6, 0.6)
    ax.set_xlabel(r"x ($\mu$m)")
axes[0].legend(fontsize=8)
axes[1].set_title(rf"$V_{{bi}} = {jn.built_in_potential:.3f}$ V, $W = {jn.depletion_width * 1e6:.3f}$ $\mu$m")
fig.tight_layout()

# %%
# Reverse bias widens the layer as :math:`\sqrt{V_{bi} - V}`
# ------------------------------------------------------------

V = np.linspace(-10, 0.5, 100)
W = np.array([pn_junction(N_A, N_D, n_i=n_i, V=v).depletion_width for v in V])
VT = k * 300 / e
I = shockley_current(np.linspace(-0.2, 0.7, 200), I_s=1e-12)
fig2, axes2 = plt.subplots(1, 2, figsize=(11, 4.5))
axes2[0].plot(V, W * 1e6, lw=2)
axes2[0].set_xlabel("bias V (V)")
axes2[0].set_ylabel(r"W ($\mu$m)")
axes2[0].set_title("Depletion width")
axes2[1].semilogy(np.linspace(-0.2, 0.7, 200), np.abs(I), lw=2)
axes2[1].set_xlabel("bias V (V)")
axes2[1].set_ylabel("|I| (A)")
axes2[1].set_title(r"Diode law, $I_s = 1$ pA: 60 mV per decade")
fig2.tight_layout()

# %%
# Check
# -----
# V_bi = (kT/q) ln(N_A N_D / n_i^2) = 0.714 V, W = 0.43 um for silicon at
# 1e16 cm^-3; the numerical band bending equals V_bi; charge balance
# x_n N_D = x_p N_A; and one decade of diode current per ln(10) kT/q.
assert abs(jn.built_in_potential - VT * np.log(N_A * N_D / n_i**2)) < 1e-12
assert abs(jn.built_in_potential - 0.714) < 2e-3
assert abs(jn.depletion_width / 0.43e-6 - 1) < 0.01
assert abs((sol.potential[-1] - sol.potential[0]) / jn.built_in_potential - 1) < 1e-6
assert abs(jn.x_n * N_D - jn.x_p * N_A) < 1e-9 * jn.x_n * N_D
ratio = shockley_current(0.5 + np.log(10) * VT, 1e-12) / shockley_current(0.5, 1e-12)
assert abs(ratio - 10) < 1e-6
