# granular.py - Hertz-Mindlin contact model, soft-sand and stiff-sand models.
#
# Free to use, copy and modify (MIT-style): no warranty of any kind.
# From Rock Physics Templates (RPTs), https://www.rockphysicstemplates.com/learn/granular
# Equations as published in: Mavko, G., Mukerji, T., & Dvorkin, J.
#   The Rock Physics Handbook (Cambridge University Press).
# Not an official Stanford product. Requires only numpy.
"""Granular-media rock physics models.

Units: moduli in GPa, density in g/cm3, effective pressure in MPa,
velocity in km/s. Porosity is a fraction.

Hertz-Mindlin pack at critical porosity phic, coordination number n,
effective pressure P, mineral K, mu and Poisson ratio nu:

    K_HM  = [ n^2 (1-phic)^2 mu^2 P / (18 pi^2 (1-nu)^2) ]^(1/3)
    mu_HM = (2 + 3f - nu(1 + 3f)) / (5(2 - nu))
            * [ 3 n^2 (1-phic)^2 mu^2 P / (2 pi^2 (1-nu)^2) ]^(1/3)

f is the shear-reduction factor (fraction of grain contacts with no slip):
f = 1 is classic no-slip Hertz-Mindlin, prefactor (5 - 4nu)/(5(2 - nu));
f = 0 is frictionless (Walton smooth), where mu_HM = 3/5 K_HM exactly
(the bracket for mu is 27x the bracket for K, so its cube root is 3 K_HM).

Soft sand (Dvorkin-Nur; modified Hashin-Shtrikman lower bound) connects the
HM pack at phic with the mineral at phi = 0, using the HM shear modulus as
the stiffening term. Stiff sand (modified HS upper bound) uses the mineral
shear modulus instead.
"""
import numpy as np


def poisson(k, mu):
    """Poisson ratio from K and mu."""
    return (3.0 * k - 2.0 * mu) / (2.0 * (3.0 * k + mu))


def hertz_mindlin(k, mu, phic=0.36, n=9.0, p_mpa=20.0, f=1.0):
    """(K_HM, mu_HM) in GPa for a random pack of identical spheres."""
    nu = poisson(k, mu)
    p = p_mpa / 1000.0  # MPa -> GPa
    c = n ** 2 * (1.0 - phic) ** 2 * mu ** 2 * p / (np.pi ** 2 * (1.0 - nu) ** 2)
    k_hm = (c / 18.0) ** (1.0 / 3.0)
    mu_hm = (2.0 + 3.0 * f - nu * (1.0 + 3.0 * f)) / (5.0 * (2.0 - nu)) * (1.5 * c) ** (1.0 / 3.0)
    return k_hm, mu_hm


def _zeta(k, mu):
    return mu / 6.0 * (9.0 * k + 8.0 * mu) / (k + 2.0 * mu)


def _mhs(phi, phic, k_hm, mu_hm, k, mu, k_z, mu_z):
    """Modified HS mix of the HM end-member (at phic) and the mineral (at phi = 0).

    (k_z, mu_z) is the stiffening end-member: the HM pack for soft sand (lower
    bound) or the mineral for stiff sand (upper bound).
    """
    phi = np.asarray(phi, dtype=float)
    a = phi / phic
    zk = 4.0 / 3.0 * mu_z
    k_dry = 1.0 / (a / (k_hm + zk) + (1.0 - a) / (k + zk)) - zk
    y = _zeta(k_z, mu_z)
    mu_dry = 1.0 / (a / (mu_hm + y) + (1.0 - a) / (mu + y)) - y
    return k_dry, mu_dry


def soft_sand(k, mu, phi, phic=0.36, n=9.0, p_mpa=20.0, f=1.0):
    """Dry (K, mu) in GPa of the soft-sand (unconsolidated) model, 0 <= phi <= phic."""
    k_hm, mu_hm = hertz_mindlin(k, mu, phic, n, p_mpa, f)
    return _mhs(phi, phic, k_hm, mu_hm, k, mu, k_hm, mu_hm)


def stiff_sand(k, mu, phi, phic=0.36, n=9.0, p_mpa=20.0, f=1.0):
    """Dry (K, mu) in GPa of the stiff-sand model, 0 <= phi <= phic."""
    k_hm, mu_hm = hertz_mindlin(k, mu, phic, n, p_mpa, f)
    return _mhs(phi, phic, k_hm, mu_hm, k, mu, k, mu)


def gassmann_ksat(k_dry, k_min, k_fl, phi):
    """Gassmann saturated bulk modulus (GPa)."""
    phi = np.asarray(phi, dtype=float)
    b = 1.0 - np.asarray(k_dry, dtype=float) / k_min
    with np.errstate(divide='ignore', invalid='ignore'):
        dk = b ** 2 / (phi / k_fl + (1.0 - phi) / k_min - k_dry / k_min ** 2)
    return k_dry + np.where(np.abs(b) < 1e-12, 0.0, dk)  # frame == mineral: no change


def velocities(k_dry, mu_dry, phi, k_min, rho_min, k_fl=None, rho_fl=0.0):
    """(Vp, Vs) in km/s. If k_fl is given the frame is saturated with Gassmann."""
    phi = np.asarray(phi, dtype=float)
    rho = (1.0 - phi) * rho_min + phi * rho_fl
    k = k_dry if k_fl is None else gassmann_ksat(k_dry, k_min, k_fl, phi)
    return np.sqrt((k + 4.0 / 3.0 * mu_dry) / rho), np.sqrt(mu_dry / rho)


if __name__ == '__main__':
    k, mu, rho_min = 36.6, 45.0, 2.65  # quartz
    k_hm, mu_hm = hertz_mindlin(k, mu, phic=0.36, n=9, p_mpa=20, f=1.0)
    print(f'Hertz-Mindlin at 20 MPa: K = {k_hm:.4f} GPa, mu = {mu_hm:.4f} GPa')
    phi = np.array([0.0, 0.05, 0.1, 0.2, 0.3, 0.36])
    print(f"{'phi':>5} {'soft dry':>9} {'soft brine':>10} {'stiff dry':>9} {'stiff brine':>11}  (Vp, km/s)")
    sk, smu = soft_sand(k, mu, phi)
    tk, tmu = stiff_sand(k, mu, phi)
    s_dry, _ = velocities(sk, smu, phi, k, rho_min)
    s_wet, _ = velocities(sk, smu, phi, k, rho_min, 2.8, 1.05)
    t_dry, _ = velocities(tk, tmu, phi, k, rho_min)
    t_wet, _ = velocities(tk, tmu, phi, k, rho_min, 2.8, 1.05)
    for i, p in enumerate(phi):
        print(f'{p:5.2f} {s_dry[i]:9.3f} {s_wet[i]:10.3f} {t_dry[i]:9.3f} {t_wet[i]:11.3f}')
