"""Axisymmetric R-z Euler diagnostic for an imposed B1 fluid handoff."""
import argparse
import json
from pathlib import Path

import numpy as np

R_GAS = 8.314462618e3 * 12/17
A_RAD = 7.5657e-16
DISTANCE = 1.1e9
SEED_FRACTION = 0.0008
AMBIENT = 0.001


def eos(q):
    rho = q[0]
    assert rho.min() > 0
    vr, vz = q[1:3]/rho
    energy = q[3] - .5*rho*(vr*vr + vz*vz)
    assert energy.min() > 0
    gas = rho*R_GAS
    temperature = np.minimum(energy/(1.5*gas), (energy/A_RAD)**.25)
    for _ in range(6):
        rad = A_RAD*temperature**4
        temperature -= temperature*(1.5*gas*temperature + rad - energy)/(1.5*gas*temperature + 4*rad)
    pg = gas*temperature
    pr = A_RAD*temperature**4/3
    sound = np.sqrt((pg + (pg+4*pr)**2/(1.5*pg+12*pr))/rho)
    return vr, vz, pg+pr, sound, temperature


def flux(q, v, p, direction):
    result = q*v
    result[direction+1] += p
    result[3] += p*v
    return result


def faces(q, v, p, c, direction):
    axis = direction+1
    a = np.moveaxis(q, axis, -1)
    vv, pp, cc = (np.moveaxis(x, direction, -1) for x in (v, p, c))
    f = flux(a, vv, pp, direction)
    wave = np.maximum(np.abs(vv[..., 1:])+cc[..., 1:], np.abs(vv[..., :-1])+cc[..., :-1])
    interior = .5*(f[..., 1:]+f[..., :-1]-wave*(a[..., 1:]-a[..., :-1]))
    return np.moveaxis(np.concatenate((f[..., :1], interior, f[..., -1:]), axis=-1), -1, axis)


def deposit(trace, grid, pointing, timing_us, speed_ppb, loading_percent):
    t = trace['time_s']
    duration = np.interp(300., trace['radius_m'][:, -1], t)
    r, speed, temperature = (
        np.array([np.interp(duration, t, line) for line in trace[k].T])
        for k in ('radius_m', 'reverse_velocity_m_s', 'temperature_K')
    )
    mass = trace['mass_kg']
    x = (np.arange(128)+.5)/128
    mu = (np.arange(1024)+.5)/512-1
    sine = np.sqrt(1-mu*mu)
    hemisphere = np.sign(mu)
    volume = grid['volume']
    dr, extent = grid['dr'], grid['extent']
    shape = volume.shape
    q = np.zeros((6,)+shape)
    seed_radius = np.interp(SEED_FRACTION,np.r_[0.,np.cumsum(mass)/mass.sum()],r**3)**(1/3)
    launch_ke = 0.
    for k, shell_mass in enumerate(mass):
        # Each shell uses equal-volume quadrature in radius and solid angle.
        radius = (r[k]**3+x*(r[k+1]**3-r[k]**3))[:,None]**(1/3)
        v = np.interp(radius, r, speed)
        seed = radius < seed_radius
        parcel = shell_mass/(len(x)*len(mu)) * (1+loading_percent*.01*hemisphere*(~seed))
        # Smooth polar aiming vanishes on the symmetry axis. The seed is fixed at release.
        miss = DISTANCE*pointing*1e-9*(~seed)*sine
        advance = (v*timing_us*1e-6+DISTANCE*speed_ppb*1e-9)*(~seed)*hemisphere
        cylindrical_r = (radius-advance)*sine - miss*mu
        z = (radius-advance)*mu + miss*sine
        vr = -v*sine*np.sign(cylindrical_r)
        vz = -v*mu
        ri = np.abs(cylindrical_r)/dr-.5
        zi = (z+extent)/dr-.5
        ir, iz = np.floor(ri).astype(int), np.floor(zi).astype(int)
        frac_r, frac_z = ri-ir, zi-iz
        rho_shell = shell_mass/(4*np.pi/3*(r[k+1]**3-r[k]**3))
        temp = temperature[k]
        specific_e = 1.5*R_GAS*temp + A_RAD*temp**4/rho_shell + .5*v*v
        launch_ke += np.sum(.5*parcel*v*v)
        values = (1., vr, vz, specific_e, seed, 1.-seed)
        for i in (0,1):
            for j in (0,1):
                rid, zid = ir+i, iz+j
                assert rid.max()<shape[0] and zid.min()>=0 and zid.max()<shape[1]
                index = (np.where(rid<0,-rid-1,rid)*shape[1]+zid).ravel()
                weight = parcel*(frac_r if i else 1-frac_r)*(frac_z if j else 1-frac_z)
                for field,value in enumerate(values):
                    parity = np.where(rid<0,-1,1) if field==1 else 1
                    q[field] += np.bincount(index,weights=(weight*value*parity).ravel(),minlength=volume.size).reshape(shape)
    q /= volume
    q[0] += AMBIENT
    q[3] += 1.5*AMBIENT*R_GAS*1e4 + A_RAD*1e16
    grid_ke = np.sum(.5*np.sum(q[1:3]**2,axis=0)/q[0]*volume)
    return q, duration, mass.sum(), float(1-grid_ke/launch_ke)


def evolve(q, radius, dr, duration):
    """Advance conserved state and integrate the open-boundary fluxes."""
    extent = len(radius)*dr
    r_edge = np.arange(len(radius)+1)*dr
    elapsed = 0.
    steps = 0
    boundary_energy = 0.
    boundary_axial_momentum = 0.
    while elapsed < duration:
        vr,vz,p,c,_ = eos(q)
        dt = min(.3*dr/np.max(np.abs(vr)+np.abs(vz)+2*c),duration-elapsed)
        fr = faces(q,vr,p,c,0)
        fz = faces(q,vz,p,c,1)
        radial = np.diff(fr*r_edge[None,:,None],axis=1)
        radial[1] -= p*dr
        q -= dt*(radial/radius[None,:,None]+np.diff(fz,axis=2))/dr
        for k in (2,3):
            outward = np.sum(fr[k,-1])*2*np.pi*extent*dr + np.sum((fz[k,:,-1]-fz[k,:,0])*2*np.pi*radius*dr)
            if k==3:
                boundary_energy += dt*outward
            else:
                boundary_axial_momentum += dt*outward
        steps += 1
        elapsed += dt
    return steps, boundary_energy, boundary_axial_momentum


def run(trace, dr, pointing, timing_us=0., speed_ppb=0., loading_percent=0., field_out=None):
    extent = 352. if abs(timing_us) <= 6 else 416.
    n = round(extent/dr)
    assert n*dr == extent
    radius = (np.arange(n)+.5)*dr
    z = (np.arange(2*n)+.5)*dr-extent
    volume = np.broadcast_to((2*np.pi*radius*dr*dr)[:,None],(n,2*n))
    grid = dict(volume=volume, dr=dr, extent=extent)
    q, duration, mass, mixed_fraction = deposit(trace,grid,pointing,timing_us,speed_ppb,loading_percent)

    def diagnostics(state,temperature):
        seed, fuel = state[4:6]*volume
        return dict(fuel_kg=float(fuel.sum()),seed_kg=float(seed.sum()),
                    fuel_z_m=float(np.sum(fuel*z)/fuel.sum()),seed_z_m=float(np.sum(seed*z)/seed.sum()),
                    seed_mass_weighted_T_K=float(np.sum(seed*temperature)/seed.sum()),
                    seed_mass_weighted_density_kg_m3=float(np.sum(seed*state[0])/seed.sum()),
                    fuel_density_ge_1000_kg_fraction=float(np.sum(fuel[state[0]>=1000])/fuel.sum()),
                    total_energy_J=float(np.sum(state[3]*volume)),
                    total_z_momentum_kg_m_s=float(np.sum(state[2]*volume)))

    initial = diagnostics(q,eos(q)[-1])
    assert abs((initial['fuel_kg']+initial['seed_kg'])/mass-1)<1e-12
    steps, boundary_energy, boundary_axial_momentum = evolve(q,radius,dr,duration)
    temperature = eos(q)[-1]
    final = diagnostics(q,temperature)
    for tracer in ('fuel_kg','seed_kg'):
        assert abs(final[tracer]/initial[tracer]-1)<1e-6, 'Tracer reached the domain boundary'
    if field_out:
        region = np.ix_(radius<=60, np.abs(z)<=60)
        np.savez_compressed(field_out, R=radius[radius<=60], z=z[np.abs(z)<=60],
                            density=q[0][region], temperature=temperature[region],
                            seed_fraction=(q[4]/q[0])[region])
    assert abs((final['total_energy_J']+boundary_energy)/initial['total_energy_J']-1)<1e-12
    assert abs(final['total_z_momentum_kg_m_s']+boundary_axial_momentum-initial['total_z_momentum_kg_m_s'])/(mass*1e6)<1e-12
    return dict(pointing_nrad=pointing,timing_us=timing_us,speed_ppb=speed_ppb,loading_percent=loading_percent,
                initial_kinetic_fraction_thermalized_in_projection=mixed_fraction,cell_m=dr,steps=steps,elapsed_s=float(duration),initial=initial,final=final,
                escaped_energy_J=boundary_energy,escaped_z_momentum_kg_m_s=boundary_axial_momentum)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('trace',type=Path)
    parser.add_argument('--cell-m',type=float,required=True)
    parser.add_argument('--pointing-nrad',type=float,required=True)
    parser.add_argument('--timing-us',type=float,default=0.)
    parser.add_argument('--speed-ppb',type=float,default=0.)
    parser.add_argument('--loading-percent',type=float,default=0.)
    parser.add_argument('--field-out',type=Path)
    parser.add_argument('--out',type=Path,required=True)
    args = parser.parse_args()
    with np.load(args.trace) as trace:
        result = run(trace,args.cell_m,args.pointing_nrad,args.timing_us,args.speed_ppb,args.loading_percent,args.field_out)
    args.out.write_text(json.dumps(result,indent=2,allow_nan=False)+'\n')
    print(args.out,result['final'])
