# gassmann.py - Gassmann fluid substitution with Wood (Reuss) fluid mixing.
#
# Free to use, copy and modify (MIT-style): no warranty of any kind.
# From Rock Physics Templates (RPTs), https://www.rockphysicstemplates.com/learn/gassmann
# 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.
"""Gassmann fluid substitution.

Units: moduli in GPa, density in g/cm3, velocity in km/s
(sqrt(GPa / (g/cm3)) = km/s). Porosity and saturation are fractions.

    K_sat  = K_dry + (1 - K_dry/K_min)^2 / (phi/K_fl + (1 - phi)/K_min - K_dry/K_min^2)
    mu_sat = mu_dry
    rho    = (1 - phi) rho_min + phi rho_fl

Fluid mix (uniform saturation, Wood/Reuss):
    1/K_fl = Sw/K_brine + (1 - Sw)/K_hc,   rho_fl = Sw rho_brine + (1 - Sw) rho_hc
"""
import numpy as np


def moduli_from_velocities(vp, vs, rho):
    """(K, mu) in GPa from Vp, Vs (km/s) and density (g/cm3)."""
    vp, vs, rho = (np.asarray(a, dtype=float) for a in (vp, vs, rho))
    return rho * (vp ** 2 - 4.0 / 3.0 * vs ** 2), rho * vs ** 2


def velocities(k, mu, rho):
    """(Vp, Vs) in km/s from K, mu (GPa) and density (g/cm3)."""
    k, mu, rho = (np.asarray(a, dtype=float) for a in (k, mu, rho))
    return np.sqrt((k + 4.0 / 3.0 * mu) / rho), np.sqrt(mu / rho)


def wood(sw, k_brine, k_hc):
    """Wood (Reuss) bulk modulus of a brine/hydrocarbon mix at water saturation sw."""
    sw = np.asarray(sw, dtype=float)
    return 1.0 / (sw / k_brine + (1.0 - sw) / k_hc)


def fluid_density(sw, rho_brine, rho_hc):
    """Linear (volume-weighted) fluid density."""
    sw = np.asarray(sw, dtype=float)
    return sw * rho_brine + (1.0 - sw) * rho_hc


def gassmann_ksat(k_dry, k_min, k_fl, phi):
    """Saturated bulk modulus from Gassmann's equation. K_fl = 0 returns K_dry."""
    k_dry, k_fl, phi = (np.asarray(a, dtype=float) for a in (k_dry, k_fl, phi))
    b = 1.0 - k_dry / k_min
    with np.errstate(divide='ignore', invalid='ignore'):
        phi_kfl = np.where(k_fl > 0, phi / k_fl, np.where(phi > 0, np.inf, 0.0))
        denom = phi_kfl + (1.0 - phi) / k_min - k_dry / k_min ** 2
        dk = np.where(np.isinf(denom), 0.0, b ** 2 / denom)
    return k_dry + np.where(np.abs(b) < 1e-12, 0.0, dk)  # frame == mineral: no change


def gassmann_kdry(k_sat, k_min, k_fl, phi):
    """Invert Gassmann: dry-frame bulk modulus from a saturated one (K_fl > 0)."""
    k_sat, k_fl, phi = (np.asarray(a, dtype=float) for a in (k_sat, k_fl, phi))
    a = phi * k_min / k_fl
    return (k_sat * (a + 1.0 - phi) - k_min) / (a + k_sat / k_min - 1.0 - phi)


def substitute(k_dry, mu_dry, k_min, rho_min, phi, sw, k_brine, rho_brine, k_hc, rho_hc):
    """Forward model versus water saturation. Returns dict of arrays (GPa, g/cm3, km/s)."""
    sw = np.asarray(sw, dtype=float)
    k_fl = wood(sw, k_brine, k_hc)
    rho = (1.0 - phi) * rho_min + phi * fluid_density(sw, rho_brine, rho_hc)
    k_sat = gassmann_ksat(k_dry, k_min, k_fl, phi)
    mu = np.full_like(sw, float(mu_dry))
    vp, vs = velocities(k_sat, mu, rho)
    return {'sw': sw, 'k_fl': k_fl, 'k_sat': k_sat, 'mu': mu, 'rho': rho,
            'vp': vp, 'vs': vs, 'vp_vs': vp / vs}


def dry_from_log(vp, vs, rho, k_min, phi, sw0, k_brine, rho_brine, k_hc, rho_hc):
    """Dry frame (K_dry, mu_dry) and implied mineral density from measured Vp, Vs, rho at Sw0."""
    k_sat, mu = moduli_from_velocities(vp, vs, rho)
    k_dry = gassmann_kdry(k_sat, k_min, wood(sw0, k_brine, k_hc), phi)
    rho_min = (rho - phi * fluid_density(sw0, rho_brine, rho_hc)) / (1.0 - phi)
    return float(k_dry), float(mu), float(rho_min)


if __name__ == '__main__':
    # Demo: brine sand logged at Sw = 1, substituted to gas.
    k_min, phi = 36.6, 0.25
    brine, gas = (2.8, 1.05), (0.06, 0.2)
    k_dry, mu_dry, rho_min = dry_from_log(3.0, 1.6, 2.2, k_min, phi, 1.0, *brine, *gas)
    print(f'K_dry = {k_dry:.3f} GPa, mu_dry = {mu_dry:.3f} GPa, rho_min = {rho_min:.3f} g/cm3')
    sw = np.array([0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
    r = substitute(k_dry, mu_dry, k_min, rho_min, phi, sw, *brine, *gas)
    print(f"{'Sw':>4} {'Vp':>6} {'Vs':>6} {'rho':>6} {'Vp/Vs':>6}")
    for i, s in enumerate(sw):
        print(f"{s:4.1f} {r['vp'][i]:6.3f} {r['vs'][i]:6.3f} {r['rho'][i]:6.3f} {r['vp_vs'][i]:6.3f}")
