"""The equilibrium constant of the water-gas shift reaction,
CO(g) + H2O(g) = CO2(g) + H2(g), found by minimising the Gibbs energy of the
reacting mixture.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.constants import R
from scipy.optimize import minimize_scalar
from scipy.special import xlogy

Tref = 298.15    # Reference temperature, K
pstd = 1         # Standard pressure, bar
p = 1            # Total pressure, bar


class Compound:
    """
    A class representing a chemical compound with defined
    formula and phase.
    """

    def __init__(self, formula, phase, DfHmo, Smo, Cp_coeffs):
        """
        Initialize the Compound object with its formula,
        phase, standard molar enthalpy of formation (kJ.mol-1), standard
        molar entropy (J.K-1.mol-1) and heat capacity temperature-dependence
        coefficients.
        """
        self.formula, self.phase = formula, phase
        self.DfHmo, self.Smo = DfHmo, Smo
        self.Cp_coeffs = dict(zip("ABCD", Cp_coeffs))

    def __repr__(self):
        """String representation of the Compound."""
        return f"{self.formula}({self.phase})"


# Data from the NIST-JANAF tables: DfHmo and Smo at Tref, and the coefficients
# of least-squares fits of Cp = A + Bt + Ct^2 + Dt^3 (J.K-1.mol-1), where
# t = T / 1000 K, to the heat capacities between 298.15 and 2000 K.
C = Compound('C', 'gr', 0, 5.740, [-3.58404139, 49.8518786, -31.20790025, 6.7641595])
O2 = Compound('O2', 'g', 0, 205.147, [25.15899701, 15.45182265, -7.08291124, 1.24519819])
H2 = Compound('H2', 'g', 0, 130.680, [29.35864238, -2.30374938, 4.0864225, -0.84549361])
H2O = Compound('H2O', 'g', -241.826, 188.834, [31.65695517, 3.84459406, 8.47064074, -2.77385035])
CO = Compound('CO', 'g', -110.527, 197.653, [27.48525388, 4.25879701, 2.50107857, -1.24204472])
CO2 = Compound('CO2', 'g', -393.522, 213.795, [23.04911248, 56.90377511, -31.87688451, 6.4056037])


class Reaction:
    """
    A class representing a chemical reaction between
    reactant and product Compounds.
    """

    def __init__(self, reactants, products):
        """
        Initialize the Reaction object with reactants and
        products provided as dictionaries of
        Compound: stoichiometry key-value pairs.
        """

        self.reactants = reactants
        self.products = products
        # For convenience, create a dictionary of all
        # species with positive stoichiometries for products
        # and negative stoichiometries for reactants.
        self.species = self.products.copy()
        for compound, stoich in reactants.items():
            self.species[compound] = -stoich

    def calc_DrSmo_ref(self):
        """Return the standard molar entropy of reaction in J.K-1.mol-1."""
        DrSmo = 0
        for compound, stoich in self.species.items():
            DrSmo += stoich * compound.Smo
        return DrSmo

    def calc_DrHmo_ref(self):
        """Return the standard molar enthalpy of reaction in kJ.mol-1."""
        DrHmo = 0
        for compound, stoich in self.species.items():
            DrHmo += stoich * compound.DfHmo
        return DrHmo

    def calc_DrGmo_ref(self):
        """
        Return the standard molar Gibbs energy of reaction in kJ.mol-1 at
        the reference temperature, Tref.
        """
        return self.calc_DrHmo_ref() - Tref * self.calc_DrSmo_ref() / 1000


# The formation reactions for CO2(g), CO(g), and H2O(g).
CO2_formation = Reaction({C: 1, O2: 1}, {CO2: 1})
CO_formation = Reaction({C: 1, O2: 0.5}, {CO: 1})
H2O_formation = Reaction({H2: 1, O2: 0.5}, {H2O: 1})
formation_reactions = {"CO2(g)": CO2_formation,
                       "CO(g)": CO_formation,
                       "H2O(g)": H2O_formation}

# The standard molar enthalpies and Gibbs energies of formation at Tref, in
# kJ.mol-1. They are zero for H2(g), an element in its reference state.
DfHmo_ref = {
    "CO(g)": CO_formation.calc_DrHmo_ref(),
    "CO2(g)": CO2_formation.calc_DrHmo_ref(),
    "H2O(g)": H2O_formation.calc_DrHmo_ref(),
    "H2(g)": 0
}
DfGmo_ref = {
    "CO(g)": CO_formation.calc_DrGmo_ref(),
    "CO2(g)": CO2_formation.calc_DrGmo_ref(),
    "H2O(g)": H2O_formation.calc_DrGmo_ref(),
    "H2(g)": 0
}

# The coefficients, A, B, C and D, of the heat capacity of formation of each
# species (zero for H2(g)).
DfCp = {formula: dict.fromkeys("ABCD", 0) for formula in DfHmo_ref}
for formula, formation_reaction in formation_reactions.items():
    for compound, stoich in formation_reaction.species.items():
        for c in "ABCD":
            DfCp[formula][c] += stoich * compound.Cp_coeffs[c]


def g(T, formula):
    """
    Return g(T) in kJ.K-1.mol-1 for the species formula: its heat capacity
    of formation integrated twice with respect to temperature.
    """
    DA, DB, DC, DD = (DfCp[formula][c] for c in "ABCD")
    t, tref = T/1000, Tref/1000
    dinv = 1/t - 1/tref
    return (DA * (np.log(t / tref) + tref * dinv)
            + DB/2 * (t - tref + tref**2 * dinv)
            + DC/3 * ((t**2 - tref**2) / 2 + tref**3 * dinv)
            + DD/4 * ((t**3 - tref**3) / 3 + tref**4 * dinv)
           ) / 1000


def calc_DfGmo(T, formula):
    """
    Return the standard molar Gibbs energy of formation of the species formula
    in kJ.mol-1 at temperature T, from the integrated Gibbs-Helmholtz equation.
    """
    DfGmo_over_T = (DfGmo_ref[formula] / Tref
                    + DfHmo_ref[formula] * (1/T - 1/Tref)
                    - g(T, formula)
                   )
    return DfGmo_over_T * T


# Start with 1 mol of CO(g) and 1 mol of H2O(g) only.
nin = {"CO(g)": 1, "H2O(g)": 1, "CO2(g)": 0, "H2(g)": 0}


def calc_G_over_RT(xi, T):
    """
    Return G/RT in mol at temperature T and extent of reaction xi (the amount
    of CO(g) that has reacted, in mol).
    """
    nout = {"CO(g)": nin["CO(g)"] - xi,
            "H2O(g)": nin["H2O(g)"] - xi,
            "CO2(g)": nin["CO2(g)"] + xi,
            "H2(g)": nin["H2(g)"] + xi}
    ntot = sum(nout.values())
    G_over_RT = 0
    for formula, n in nout.items():
        DfGmo = calc_DfGmo(T, formula)
        x = n / ntot
        # xlogy(n, y) is n ln(y), taken to be zero for n = 0, so that G is
        # defined at xi = 0 and xi = 1.
        G_over_RT += n * DfGmo * 1000 / (R * T) + xlogy(n, x * p / pstd)
    return G_over_RT


def get_xi_eq(T):
    """Return the extent of reaction at equilibrium, in mol, at temperature T."""
    res = minimize_scalar(calc_G_over_RT, bounds=(0, 1), args=(T,),
                          method="bounded", options={"xatol": 1e-9})
    return res.x


def get_K(T):
    """Return the equilibrium constant at temperature T from the composition
    that minimises G."""
    xi = get_xi_eq(T)
    # For the initial composition nin, x(CO2) = x(H2) = xi/2 and
    # x(CO) = x(H2O) = (1 - xi)/2.
    return xi**2 / (1 - xi)**2


def get_K_from_DrGmo(T):
    """Return the equilibrium constant at temperature T as exp(-DrGmo/RT)."""
    DrGmo = (calc_DfGmo(T, "CO2(g)") + calc_DfGmo(T, "H2(g)")
             - calc_DfGmo(T, "CO(g)") - calc_DfGmo(T, "H2O(g)"))
    return np.exp(-DrGmo * 1000 / (R * T))


# The standard molar Gibbs energies of formation of CO2(g), CO(g) and H2O(g),
# in kJ.mol-1, from the NIST-JANAF tables.
DfGmo_JANAF = {500: (-394.939, -155.414, -219.051),
               1000: (-395.886, -200.275, -192.590),
               1500: (-396.288, -243.740, -164.376),
               2000: (-396.333, -286.034, -135.528)}


def get_K_JANAF(T):
    """Return the equilibrium constant at temperature T from the NIST-JANAF
    tables."""
    DfGmo_CO2, DfGmo_CO, DfGmo_H2O = DfGmo_JANAF[T]
    DrGmo = DfGmo_CO2 - DfGmo_CO - DfGmo_H2O
    return np.exp(-DrGmo * 1000 / (R * T))


def get_K_Callaghan(T):
    """Return the equilibrium constant at temperature T from Callaghan's fit."""
    return 10**(-2.4198 + 0.0003855*T + 2180.6/T)


def plot_G_over_RT(T, ax):
    """
    Plot G/RT against the extent of reaction at temperature T on the
    Matplotlib Axes ax, and mark its minimum.
    """
    xi_grid = np.linspace(0, 1, 201)
    ax.plot(xi_grid, [calc_G_over_RT(xi, T) for xi in xi_grid])
    xi_eq = get_xi_eq(T)
    ax.plot(xi_eq, calc_G_over_RT(xi_eq, T), "o")
    ax.set_title(f"{T} K")


if __name__ == "__main__":
    temperatures = (500, 1000, 1500, 2000)
    print(" T/K  xi/mol    K(min)    K(DrG)  K(JANAF)  K(Callaghan)")
    for T in temperatures:
        print(f"{T:4d}  {get_xi_eq(T):.4f}  {get_K(T):8.4g}  "
              f"{get_K_from_DrGmo(T):8.4g}  {get_K_JANAF(T):8.4g}  "
              f"{get_K_Callaghan(T):12.4g}")

    fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, layout="constrained")
    for T, ax in zip(temperatures, axes.flat):
        plot_G_over_RT(T, ax)
    fig.supxlabel(r"$\xi$ / mol")
    fig.supylabel(r"$G/RT$ / mol")
    plt.show()
