"""Independent polarized Rayleigh/LTE layered reference; never imported by LESS.

NumPy/SciPy only. Electrostatic depolarization comes from its defining integral;
particle orientation moments use independent Gaussian quadrature. Thin-layer
matrix exponentials and adding/doubling solve the two-polarization, azimuthally
symmetric transfer equation. Layers are ordered bottom to top.
"""
import numpy as np
from scipy.integrate import quad
from scipy.linalg import expm, solve


def permittivity(frequency, moisture, temperature, dry_density=0.):
    f, t = frequency/1e9, temperature-273.15
    relaxation = 1.1109e-10-3.824e-12*t+6.938e-14*t*t-5.096e-16*t**3
    static = 88.045-.4147*t+6.295e-4*t*t+1.075e-5*t**3
    free = 4.9+(static-4.9)/(1+1j*frequency*relaxation)-1j*22.74/f
    bound = 2.9+55/(1+(1+1j)*np.sqrt(f/.36))
    if dry_density:
        m = moisture*dry_density/(1-moisture*(1-dry_density))
        a, b, c = 1.7+3.2*m+6.5*m*m, m*(.82*m+.166), 31.4*m*m/(59.5*m*m+1)
    else:
        m = moisture
        a, b, c = 1.7-.74*m+6.16*m*m, m*(.55*m-.076), 4.64*m*m/(7.36*m*m+1)
    value = a+b*free+c*bound
    return complex(value.real, -abs(value.imag))


def polarizability(population, frequency, temperature):
    ratio = population["length_m"]/(2*population["radius_m"])
    axial = ratio/2*quad(lambda u: 1/((u+1)*(u+ratio*ratio)**1.5),
                         0, np.inf, epsabs=2e-13, epsrel=2e-13)[0]
    factors = np.array([(1-axial)/2, axial])
    volume = np.pi*population["radius_m"]**2*population["length_m"]
    eps = permittivity(frequency, population["moisture"], temperature,
                       population.get("dry_density", 0.))
    alpha = volume*(eps-1)/(1+factors*(eps-1))
    return alpha, eps, factors


def basis(mu, phi=0.):
    mu, phi = np.broadcast_arrays(np.asarray(mu), np.asarray(phi))
    vertical = np.stack((mu*np.cos(phi), mu*np.sin(phi), -np.sqrt(1-mu*mu)), axis=-1)
    horizontal = np.stack((-np.sin(phi), np.cos(phi), np.zeros_like(phi)), axis=-1)
    return np.stack((vertical, horizontal), axis=-2)


class Population:
    def __init__(self, settings, frequency, temperature):
        self.settings = settings
        electrostatic, self.eps, self.depolarization = polarizability(settings, frequency, temperature)
        self.k = 2*np.pi*frequency/299792458
        # SI volume polarizability with negative loss, matching this offline
        # reference's convention. Intrinsic dissipation excludes radiated power.
        denominator = 1+1j*self.k**3*electrostatic/(6*np.pi)
        self.alpha = electrostatic/denominator
        self.absorbed_axis = -self.k*electrostatic.imag/abs(denominator)**2
        self.density = settings["density_m3"]
        orientation = settings["orientation"]
        if orientation == "spherical":
            z, w = np.polynomial.legendre.leggauss(4)
            z, w = (z+1)/2, w/2
        else:
            z, w = np.array([np.cos(np.deg2rad(float(orientation)))]), np.ones(1)
        phi = np.arange(8)*2*np.pi/8
        sine = np.sqrt(1-z*z)
        self.axes = np.stack(np.broadcast_arrays(sine[:, None]*np.cos(phi),
            sine[:, None]*np.sin(phi), z[:, None]), axis=-1).reshape(-1, 3)
        self.weights = np.repeat(w/8, 8)

    def rates(self, mu):
        projection = basis(mu) @ self.axes.T
        moment = np.einsum("...pn,n->...p", projection**2, self.weights)
        transverse, axial = self.alpha
        absorption = self.density*(self.absorbed_axis[0]
            +(self.absorbed_axis[1]-self.absorbed_axis[0])*moment)
        scattering = self.density*self.k**4/(6*np.pi)*(abs(transverse)**2+
            (abs(axial)**2-abs(transverse)**2)*moment)
        return absorption, scattering

    def phase(self, outgoing, incoming):
        outgoing, incoming = np.atleast_1d(outgoing), np.atleast_1d(incoming)
        result = np.zeros((len(outgoing), len(incoming), 2, 2))
        out = basis(outgoing)
        po = out @ self.axes.T
        a, b = self.alpha[0], self.alpha[1]-self.alpha[0]
        for phi in np.arange(8)*2*np.pi/8:
            inc = basis(incoming, phi)
            pi = inc @ self.axes.T
            cross = np.einsum("oac,ibc->oiab", out, inc)
            second = np.einsum("oan,ibn,n->oiab", po, pi, self.weights)
            fourth = np.einsum("oan,ibn,n->oiab", po**2, pi**2, self.weights)
            result += abs(a)**2*cross**2+2*(a*b.conjugate()).real*cross*second+abs(b)**2*fourth
        return result*(2*np.pi/8)*self.density*self.k**4/(4*np.pi)**2


def join(lower, upper):
    """Compose two layer response operators; retain arbitrary source columns."""
    lu, lr, lb, ld, leu, led = lower
    uu, ur, ub, ud, ueu, ued = upper
    n = len(lu)
    internal = solve(np.eye(n)-lr@ub,
        np.concatenate((lu, lr@ud, lr@ued+leu), axis=1), check_finite=False)
    x, y, v = internal[:, :n], internal[:, n:2*n], internal[:, 2*n:]
    return (uu@x, ur+uu@y, lb+ld@ub@x, ld@(ud+ub@y),
            ueu+uu@v, led+ld@(ued+ub@v))


def layer_operator(layer, frequency, mu, weights, multiplier=1., thin_limit=.1):
    populations = [Population(p, frequency, layer["temperature_K"]) for p in layer["populations"]]
    directions = np.r_[mu, -mu]
    absorption = sum(p.rates(directions)[0] for p in populations)
    scattering = sum(p.rates(directions)[1] for p in populations)
    extinction = absorption+scattering
    phase = sum(p.phase(directions, directions) for p in populations)
    angular = phase*np.tile(weights, 2)[None, :, None, None]
    matrix = angular.transpose(0, 2, 1, 3).reshape(extinction.size, extinction.size)*multiplier
    matrix -= np.diag(extinction.ravel())
    derivative = np.repeat(directions, 2)
    matrix = matrix/derivative[:, None]
    sources = np.zeros((extinction.size, 3), dtype=matrix.dtype)
    sources[:, 1] = (absorption*layer["temperature_K"]).ravel()/derivative
    height = layer["top_m"]-layer["bottom_m"]
    halvings = max(0, int(np.ceil(np.log2(max(1., height*np.max(
        extinction/np.abs(directions)[:, None])/thin_limit)))))
    augmented = np.zeros((len(matrix)+3, len(matrix)+3), dtype=matrix.dtype)
    augmented[:-3, :-3], augmented[:-3, -3:] = matrix, sources
    transfer = expm(augmented*(height/2**halvings))
    n = len(mu)*2
    a, b = transfer[:n, :n], transfer[:n, n:2*n]
    c, d = transfer[n:2*n, :n], transfer[n:2*n, n:2*n]
    e, f = transfer[:n, -3:], transfer[n:2*n, -3:]
    inverse = solve(d, np.concatenate((c, np.eye(n), f), axis=1), check_finite=False)
    dc, di, df = inverse[:, :n], inverse[:, n:2*n], inverse[:, 2*n:]
    operator = (a-b@dc, b@di, -dc, di, e-b@df, -df)
    for _ in range(halvings):
        operator = join(operator, operator)
    return operator


def solve_layers(layers, frequency, soil_eps, soil_K, sky_K, angles=(0., 40., 60.),
                 n_mu=16, multiplier=1., thin_limit=.1):
    nodes, weights = np.polynomial.legendre.leggauss(n_mu)
    mu = np.r_[(nodes+1)/2, np.cos(np.deg2rad(angles))]
    weights = np.r_[weights/2, np.zeros(len(angles))]
    operator = None
    for layer in layers:
        current = layer_operator(layer, frequency, mu, weights, multiplier, thin_limit)
        operator = current if operator is None else join(operator, current)
    tu, rt, rb, td, eu, ed = operator
    root = np.sqrt(soil_eps-(1-mu*mu))
    rh = abs((mu-root)/(mu+root))**2
    rv = abs((soil_eps*mu-root)/(soil_eps*mu+root))**2
    reflect = np.diag(np.stack((rv, rh), axis=-1).ravel())
    top = np.zeros((len(reflect), 3), dtype=tu.dtype)
    top[:, 2] = sky_K
    bottom = np.zeros_like(top)
    bottom[:, 0] = (1-np.diag(reflect))*soil_K
    up = solve(np.eye(len(reflect))-reflect@rb,
               reflect@(td@top+ed)+bottom, check_finite=False)
    result = (tu@up+rt@top+eu).reshape(len(mu), 2, 3)[-len(angles):]
    return result


def scattering_orders(layers, frequency, soil_eps, soil_K, sky_K, angles, n_mu=32):
    full = solve_layers(layers, frequency, soil_eps, soil_K, sky_K, angles, n_mu)
    zero = solve_layers(layers, frequency, soil_eps, soil_K, sky_K, angles, n_mu, 0.)
    first = solve_layers(layers, frequency, soil_eps, soil_K, sky_K, angles, n_mu, 1j*1e-20).imag/1e-20
    return dict(full=full, zero=zero, first=first, higher=full-zero-first)
