"""Fit the molar heat capacities of N2 and CO from the NIST-JANAF tables to
models of their vibration and rotation, and compare the fitted vibrational
constants with those from spectroscopy.

N2_Cp.csv and CO_Cp.csv hold the molar constant-pressure heat capacity of each
gas (J K-1 mol-1) as a function of temperature (K).
"""

from functools import partial

import matplotlib.pyplot as plt
import numpy as np
from scipy.constants import R, physical_constants
from scipy.optimize import curve_fit

# The second radiation constant, hc/kB, in cm K.
c2 = physical_constants["second radiation constant"][0] * 100

# The spectroscopic constants we, wexe, Be, alpha_e and De of the ground
# electronic state of each molecule, in cm-1, from K. P. Huber and
# G. Herzberg, Constants of Diatomic Molecules (1979), via the NIST Chemistry
# WebBook.
CONSTANTS = {
    "N2": (2358.57, 14.324, 1.998241, 0.017318, 5.76e-6),
    "CO": (2169.81358, 13.28831, 1.93128087, 0.01750441, 6.12147e-6),
}

JMAX = 400  # the largest rotational quantum number in the sums over levels


def read_Cp(filename):
    """The temperatures (K) and molar heat capacities (J K-1 mol-1) in the CSV
    file filename."""
    return np.genfromtxt(filename, delimiter=",", skip_header=1, unpack=True)


def fit(model, T, Cp, p0):
    """Fit model(T, *params) to the heat capacities Cp, starting from the
    parameters p0; return the fitted parameters, their standard errors and
    the root-mean-square residual."""
    popt, pcov = curve_fit(model, T, Cp, p0=p0)
    rms = np.sqrt(np.mean((Cp - model(T, *popt))**2))
    return popt, np.sqrt(np.diag(pcov)), rms


def Cp_harmonic(T, nu):
    """The molar heat capacity with a harmonic vibration of wavenumber nu
    (cm-1)."""
    x = c2 * nu / T
    return 7 * R / 2 + R * x**2 * np.exp(x) / np.expm1(x)**2


def heat_capacity(E, g, T):
    """The contribution to the molar heat capacity of the levels with energies
    E (cm-1, relative to the lowest) and degeneracies g, at the temperatures
    T: R times the variance of E/kBT."""
    x = c2 * E[:, None] / T
    p = g[:, None] * np.exp(-x)
    p /= p.sum(axis=0)
    mean_x = (p * x).sum(axis=0)
    return R * ((p * x**2).sum(axis=0) - mean_x**2)


def morse_levels(we, wexe):
    """The vibrational quantum numbers of the bound levels of a Morse
    oscillator, and their energies (cm-1) relative to v = 0."""
    vmax = int(we / (2 * wexe) - 0.5)
    v = np.arange(vmax + 1)
    return v, we * v - wexe * v * (v + 1)


def Cp_anharmonic(T, we, wexe):
    """The molar heat capacity with the vibration of a Morse oscillator."""
    v, E = morse_levels(we, wexe)
    return 7 * R / 2 + heat_capacity(E, np.ones_like(E), T)


def Cp_rovib(T, we, wexe, Be, alpha_e, De):
    """The molar heat capacity with the rotational and vibrational levels
    together, including rotation-vibration interaction (alpha_e) and
    centrifugal distortion (De)."""
    v, G = morse_levels(we, wexe)
    Bv = Be - alpha_e * (v[:, None] + 0.5)
    J = np.arange(JMAX + 1)
    JJ = J * (J + 1)
    E = G[:, None] + Bv * JJ - De * JJ**2
    g = np.broadcast_to(2 * J + 1, E.shape)
    # Keep the levels below the maximum of each rotational term-value curve,
    # beyond which the energy falls with J.
    bound = 2 * De * JJ < Bv
    return 5 * R / 2 + heat_capacity(E[bound], g[bound], T)


def report(label, popt, perr, rms):
    """Print the fitted parameters, their standard errors and the
    root-mean-square residual of a fit."""
    params = "".join(f"{p:10.2f} ± {e:<6.2f}" for p, e in zip(popt, perr))
    print(f"{label:28s}{params:38s}{rms:6.3f}")


if __name__ == "__main__":
    for molecule, (we, wexe, Be, alpha_e, De) in CONSTANTS.items():
        T, Cp = read_Cp(f"{molecule}_Cp.csv")
        print(f"{molecule}: we = {we} cm-1, wexe = {wexe} cm-1 and"
              f" we - 2wexe = {we - 2 * wexe:.2f} cm-1 (spectroscopy)")
        print(f"{'Model':28s}{'we / cm-1':>14s}{'wexe / cm-1':>19s}"
              f"{'rms / J K-1 mol-1':>23s}")

        # Each model, with the data it is fitted to and the starting values
        # of its parameters. For the harmonic model, the parameter in the
        # column headed we is the vibrational wavenumber, nu. The
        # rovibrational models take Be, alpha_e and De at their spectroscopic
        # values, or set alpha_e or De to zero. The tabulated values above
        # 4800 K include a contribution from excited electronic states.
        low, ground = T <= 1500, T < 4800
        rovib = partial(Cp_rovib, Be=Be, alpha_e=alpha_e, De=De)
        models = {
            "Harmonic": (Cp_harmonic, T, Cp, [2000]),
            "Harmonic, T <= 1500 K": (Cp_harmonic, T[low], Cp[low], [2000]),
            "Morse oscillator": (Cp_anharmonic, T, Cp, [2000, 10]),
            "Rovibrational, alpha_e only":
                (partial(Cp_rovib, Be=Be, alpha_e=alpha_e, De=0), T, Cp,
                 [2000, 10]),
            "Rovibrational, De only":
                (partial(Cp_rovib, Be=Be, alpha_e=0, De=De), T, Cp,
                 [2000, 10]),
            "Rovibrational": (rovib, T, Cp, [2000, 10]),
            "Rovibrational, T < 4800 K":
                (rovib, T[ground], Cp[ground], [2000, 10]),
        }
        fits = {}
        for label, (model, Tfit, Cpfit, p0) in models.items():
            popt, perr, rms = fit(model, Tfit, Cpfit, p0)
            report(label, popt, perr, rms)
            fits[label] = model(T, *popt)

        # The rovibrational model with the spectroscopic constants, unfitted.
        res = Cp - rovib(T, we, wexe)
        print(f"Spectroscopic constants: largest |residual| below 4800 K"
              f" {np.abs(res[ground]).max():.3f} J K-1 mol-1; residual at"
              f" {T[-1]:.0f} K {res[-1]:.3f} J K-1 mol-1\n")

        # Plot the data and three of the fits, and their residuals.
        fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True,
                                       height_ratios=(3, 1))
        ax1.plot(T, Cp, "+", label="NIST-JANAF")
        for label in ("Harmonic", "Morse oscillator", "Rovibrational"):
            ax1.plot(T, fits[label], label=label)
            ax2.plot(T, Cp - fits[label])
        ax1.set_title(molecule)
        ax1.set_ylabel(r"$C_{p,\mathrm{m}}\;/\;\mathrm{J\,K^{-1}\,mol^{-1}}$")
        ax1.legend()
        ax2.set_xlabel(r"$T\;/\;\mathrm{K}$")
        ax2.set_ylabel("Residual")
        plt.show()
