
"""PKTron Chemistry — Reaction kinetics, equilibrium, thermochemistry."""
import numpy as np
_R = np.float32

R_GAS = _R(8.314)

def arrhenius_rate(A, Ea, T):
    """k = A * exp(-Ea / R*T)   Ea in J/mol, T in K"""
    return float(_R(A)*np.exp(-_R(Ea)/(R_GAS*_R(T))))

def half_life_first_order(k):
    """t_1/2 = ln2 / k"""
    return float(np.log(2)/_R(k))

def concentration_first_order(C0, k, t):
    """[A](t) = C0 * exp(-k*t)"""
    return float(_R(C0)*np.exp(-_R(k)*np.asarray(t,dtype=_R)))

def reaction_quotient(products, reactants):
    """Q = product(conc_products) / product(conc_reactants)"""
    Q = 1.0
    for c in products: Q *= float(c)
    for c in reactants: Q /= float(c)
    return Q

def equilibrium_constant_from_dG(dG_rxn, T=298.15):
    """Keq = exp(-dG / R*T)   dG in J/mol"""
    return float(np.exp(-_R(dG_rxn)/(R_GAS*_R(T))))

def gibbs_free_energy(dH, dS, T):
    """dG = dH - T*dS"""
    return float(_R(dH) - _R(T)*_R(dS))

def henderson_hasselbalch(pKa, C_acid, C_base):
    """pH = pKa + log10([A-]/[HA])"""
    return float(_R(pKa)+np.log10(_R(C_base)/_R(C_acid)))

def dilution_law(C1, V1, V2):
    """C2 = C1*V1/V2"""
    return float(_R(C1)*_R(V1)/_R(V2))

def simulate_first_order_kinetics(C0, k, t_max, n_points=200):
    """Simulate first-order decay. Returns (t_arr, C_arr)."""
    t = np.linspace(_R(0),_R(t_max),n_points,dtype=_R)
    C = _R(C0)*np.exp(-_R(k)*t)
    return t, C
