r"""
Wilson's band theory of semiconductors: carriers across a gap
=============================================================

Wilson (1931) explained semiconductors as insulators with a small band gap
:math:`E_g`: thermal excitation lifts electrons into the conduction band
and leaves holes behind, so the intrinsic carrier density grows as
:math:`n_i = \sqrt{N_cN_v}\,e^{-E_g/2k_BT}`
(:func:`~physicskit.condensed.semiconductors.intrinsic_carrier_density`),
while :math:`np = n_i^2` holds whatever the doping. Impurities add
carriers: an n-type crystal
(:func:`~physicskit.condensed.semiconductors.carrier_densities_doped`)
passes from freeze-out onto its donor plateau :math:`n \approx N_D` and
finally back to intrinsic behaviour, with the Fermi level moving from near
the donor level to midgap.
"""

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

from physicskit.condensed.semiconductors import (
    carrier_densities_doped,
    intrinsic_carrier_density,
    intrinsic_fermi_level,
)

# %%
# The intrinsic density of silicon
# --------------------------------
#
# On an Arrhenius plot :math:`n_i/T^{3/2}` is a straight line of slope
# :math:`-E_g/2k_B`.

T = np.linspace(200, 1000, 200)
ni = intrinsic_carrier_density(T)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
axes[0].semilogy(1000 / T, ni / T**1.5 * 1e-6, lw=2)
axes[0].set_xlabel("1000 / T  (1/K)")
axes[0].set_ylabel(r"$n_i / T^{3/2}$  (cm$^{-3}$ K$^{-3/2}$)")
axes[0].set_title(r"Silicon: activation energy $E_g/2 = 0.56$ eV")

# %%
# The three regimes of an n-type crystal
# --------------------------------------

N_D = 1e22  # 1e16 cm^-3
Ts = np.linspace(20, 1000, 300)
n, p, EF = np.array([carrier_densities_doped(t, N_D, 0.0) for t in Ts]).T
axes[1].semilogy(Ts, n * 1e-6, lw=2, label="electrons n")
axes[1].semilogy(Ts, p * 1e-6, lw=2, label="holes p")
axes[1].semilogy(Ts, intrinsic_carrier_density(Ts) * 1e-6, "k:", label=r"$n_i$")
axes[1].axhline(N_D * 1e-6, color="0.6", lw=0.8, ls="--", label=r"$N_D$")
axes[1].set_ylim(1e8, 1e18)
axes[1].set_xlabel("T (K)")
axes[1].set_ylabel(r"density (cm$^{-3}$)")
axes[1].set_title(r"n-type Si, $N_D = 10^{16}$ cm$^{-3}$: freeze-out, extrinsic, intrinsic")
axes[1].legend(fontsize=8)
fig.tight_layout()

# %%
# The Fermi level
# ---------------
#
# Measured from the valence-band edge: it starts just below the donor level
# :math:`E_c - E_d` and sinks towards the intrinsic level as the crystal
# heats up.

fig2, ax2 = plt.subplots(figsize=(7, 4.5))
ax2.plot(Ts, EF, lw=2, label=r"$E_F$, n-type")
ax2.plot(Ts, intrinsic_fermi_level(Ts), "k:", label=r"$E_i$, intrinsic")
ax2.axhline(1.12, color="0.4", lw=1)
ax2.axhline(1.12 - 0.045, color="0.6", lw=0.8, ls="--", label="donor level")
ax2.axhline(0.0, color="0.4", lw=1)
ax2.set_xlabel("T (K)")
ax2.set_ylabel("energy above $E_v$ (eV)")
ax2.legend(fontsize=8)
fig2.tight_layout()

# %%
# Check
# -----
# Mass action np = n_i^2, the Arrhenius slope E_g/2, and the extrinsic
# plateau n ~ N_D at room temperature.
np.testing.assert_allclose(n * p, intrinsic_carrier_density(Ts) ** 2, rtol=1e-8)
slope = -np.polyfit(1 / T, np.log(ni / T**1.5), 1)[0] * k / e
assert abs(slope - 1.12 / 2) < 1e-10
n300 = carrier_densities_doped(300.0, N_D, 0.0)[0]
assert abs(n300 / N_D - 1) < 1e-2
assert 1.12 - 0.045 - 0.05 < EF[0] < 1.12
