# avo.py - P-wave reflectivity versus angle (Aki-Richards, Shuey) and AVO classes.
#
# Free to use, copy and modify (MIT-style): no warranty of any kind.
# From Rock Physics Templates (RPTs), https://www.rockphysicstemplates.com/learn/avo
# Equations as published in: Mavko, G., Mukerji, T., & Dvorkin, J.
#   The Rock Physics Handbook (Cambridge University Press), AVO section;
#   Aki, K., & Richards, P. G. (1980) Quantitative Seismology (W. H. Freeman);
#   Shuey, R. T. (1985) Geophysics 50, 609-614;
#   Rutherford, S. R., & Williams, R. H. (1989) Geophysics 54, 680-688;
#   Ross, C. P., & Kinman, D. L. (1995) Geophysics 60, 1398-1408 (class IIp);
#   Castagna, J. P., Swan, H. W., & Foster, D. J. (1998) Geophysics 63, 948-956.
# Not an official Stanford product. Requires only numpy.
"""PP reflectivity of a planar interface between two isotropic elastic layers.

Units: velocity in km/s, density in g/cm3 (any consistent units work: only
ratios enter). Layer 1 is the upper (incidence) medium, layer 2 the lower one.
Angles are P-wave incidence angles in degrees.

Contrasts use layer averages:
    a = (Vp1 + Vp2)/2, b = (Vs1 + Vs2)/2, r = (rho1 + rho2)/2
    da = Vp2 - Vp1,    db = Vs2 - Vs1,    dr = rho2 - rho1

Aki & Richards (1980) linearized PP reflection coefficient:
    Rpp(t) = 1/2 (1 - 4 b^2/a^2 sin^2 t) dr/r + 1/(2 cos^2 t) da/a - 4 b^2/a^2 sin^2 t db/b

Angle choice: t is the average of the incidence angle t1 and the transmitted
P angle t2, with sin t2 = Vp2/Vp1 sin t1 (Snell's law), as in Aki & Richards.
Past the critical angle (sin t2 > 1) there is no transmitted P wave and the
linearized formula does not apply, so NaN is returned.

Shuey (1985), written as in the Rock Physics Handbook:
    Rpp(t) = A + B sin^2 t + C (tan^2 t - sin^2 t)
    A = 1/2 (da/a + dr/r)                      intercept (normal incidence)
    B = 1/2 da/a - 2 b^2/a^2 (dr/r + 2 db/b)   gradient
    C = 1/2 da/a                               curvature
The three-term form is an exact rearrangement of Aki-Richards (same average
angle t), so the two agree to rounding error. The two-term form drops C and is
accurate to about 30 degrees.

A is the linearized normal-incidence coefficient. The exact value is
R0 = (Z2 - Z1)/(Z2 + Z1), Z = rho Vp; they differ only at second order
(by a factor r a / mean(Z), exact when either rho or Vp has no contrast).
"""
import numpy as np

# Intercept band for class II (near-zero impedance contrast), after Rutherford & Williams.
CLASS_II_BAND = 0.02


def impedance(vp, rho):
    """Acoustic impedance Z = rho * Vp."""
    return np.asarray(rho, dtype=float) * np.asarray(vp, dtype=float)


def normal_incidence(vp1, rho1, vp2, rho2):
    """Exact normal-incidence PP reflection coefficient R0 = (Z2 - Z1)/(Z2 + Z1)."""
    z1, z2 = impedance(vp1, rho1), impedance(vp2, rho2)
    return (z2 - z1) / (z2 + z1)


def _contrasts(vp1, vs1, rho1, vp2, vs2, rho2):
    vp1, vs1, rho1, vp2, vs2, rho2 = (np.asarray(x, dtype=float) for x in (vp1, vs1, rho1, vp2, vs2, rho2))
    a, b, r = (vp1 + vp2) / 2, (vs1 + vs2) / 2, (rho1 + rho2) / 2
    return (vp2 - vp1) / a, (vs2 - vs1) / b, (rho2 - rho1) / r, (b / a) ** 2


def average_angle(vp1, vp2, theta_deg):
    """Average of incidence and transmitted P angles (radians); NaN past the critical angle."""
    t1 = np.radians(np.asarray(theta_deg, dtype=float))
    s2 = np.asarray(vp2, dtype=float) / np.asarray(vp1, dtype=float) * np.sin(t1)
    with np.errstate(invalid='ignore'):
        t2 = np.where(np.abs(s2) <= 1.0, np.arcsin(np.clip(s2, -1.0, 1.0)), np.nan)
    return (t1 + t2) / 2


def critical_angle(vp1, vp2):
    """P-wave critical angle in degrees (NaN when Vp2 <= Vp1: no critical angle)."""
    vp1, vp2 = np.asarray(vp1, dtype=float), np.asarray(vp2, dtype=float)
    with np.errstate(invalid='ignore', divide='ignore'):
        return np.where(vp2 > vp1, np.degrees(np.arcsin(np.minimum(vp1 / vp2, 1.0))), np.nan)


def aki_richards(vp1, vs1, rho1, vp2, vs2, rho2, theta_deg):
    """Aki-Richards linearized Rpp at incidence angle(s) theta_deg (average angle used inside)."""
    dvp, dvs, drho, k = _contrasts(vp1, vs1, rho1, vp2, vs2, rho2)
    t = average_angle(vp1, vp2, theta_deg)
    s2 = np.sin(t) ** 2
    return 0.5 * (1 - 4 * k * s2) * drho + 0.5 / np.cos(t) ** 2 * dvp - 4 * k * s2 * dvs


def shuey(vp1, vs1, rho1, vp2, vs2, rho2):
    """Shuey intercept A, gradient B and curvature C."""
    dvp, dvs, drho, k = _contrasts(vp1, vs1, rho1, vp2, vs2, rho2)
    a = 0.5 * (dvp + drho)
    b = 0.5 * dvp - 2 * k * (drho + 2 * dvs)
    c = 0.5 * dvp
    return a, b, c


def shuey_rpp(vp1, vs1, rho1, vp2, vs2, rho2, theta_deg, terms=3):
    """Shuey Rpp at incidence angle(s) theta_deg: terms=3 (A, B, C) or terms=2 (A, B)."""
    if terms not in (2, 3):
        raise ValueError('terms must be 2 or 3')
    a, b, c = shuey(vp1, vs1, rho1, vp2, vs2, rho2)
    t = average_angle(vp1, vp2, theta_deg)
    s2 = np.sin(t) ** 2
    r = a + b * s2
    return r + c * (np.tan(t) ** 2 - s2) if terms == 3 else r


def background_slope(vp_vs=2.0, gardner_exp=0.25, mudrock_slope=1.16):
    """Slope B/A of the brine-sand/shale background trend through the origin.

    Follows the approach of Castagna et al. (1998): linearized contrasts with
    Gardner density (rho ~ Vp^g, so drho/rho = g dVp/Vp) and the mudrock line
    Vp = m Vs + c (so dVs/Vs = Vp/(m Vs) dVp/Vp), giving
        B = A/(1 + g) [1 - 4 (Vs/Vp)^2 (g + 2 Vp/(m Vs))].
    """
    k = 1.0 / vp_vs ** 2
    return (1 - 4 * k * (gardner_exp + 2 * vp_vs / mudrock_slope)) / (1 + gardner_exp)


def avo_class(a, b, band=CLASS_II_BAND):
    """AVO class of a top-of-sand reflection from intercept A and gradient B.

    'I'   A >  band                 hard sand: amplitude dims with angle
    'IIp' 0 < A <= band and B < 0   near-zero intercept, polarity reverses with angle
    'II'  |A| <= band otherwise     near-zero intercept, amplitude grows with angle
    'III' A < -band and B <= 0      soft sand, bright spot growing with angle
    'IV'  A < -band and B >  0      soft sand, bright at zero offset but dimming with angle
    Classes I-III after Rutherford & Williams (1989), IIp after Ross & Kinman
    (1995), IV after Castagna et al. (1998). Works element-wise on arrays.
    """
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    out = np.where(a > band, 'I',
          np.where(a >= -band, np.where((a > 0) & (b < 0), 'IIp', 'II'),
          np.where(b > 0, 'IV', 'III')))
    return out.item() if out.ndim == 0 else out


if __name__ == '__main__':
    # Demo: shale over three sands, reflectivity versus angle and AVO class.
    shale = (2.40, 1.00, 2.25)
    sands = {'gas sand': (2.00, 1.25, 1.95), 'brine sand': (2.60, 1.25, 2.15),
             'hard sand': (3.40, 1.95, 2.40)}
    angles = np.array([0, 10, 20, 30, 40])
    print(f"{'':10} {'A':>7} {'B':>7} {'C':>7} class  " + ' '.join(f'{t:>6d}°' for t in angles))
    for name, sand in sands.items():
        a, b, c = shuey(*shale, *sand)
        r = aki_richards(*shale, *sand, angles)
        print(f'{name:10} {a:7.3f} {b:7.3f} {c:7.3f} {avo_class(a, b):5}  ' +
              ' '.join(f'{x:7.3f}' for x in r))
    print(f'R0 exact (gas sand): {float(normal_incidence(shale[0], shale[2], 2.00, 1.95)):.4f}')
