using Sockets
using Base.Threads: @spawn
using Dates
using MAT
using JLD2

const R = u"Ω"
const V = u"V"
const A = u"A"
const Hz = u"Hz"

using Unitful: Current, Voltage, Frequency, Time

raw(a::Current)   = Float64(ustrip(uconvert(A, a)))
raw(a::Voltage)   = Float64(ustrip(uconvert(V, a)))
raw(a::Frequency) = Float64(ustrip(uconvert(Hz, a)))
raw(a::Time)      = Float64(ustrip(uconvert(u"s", a)))

function elapsed_time(start_time)
    seconds = floor(time() - start_time)
    return Time(0) + Second(seconds)
end

function elapsed_time(func, start_time)
    seconds = floor(time() - start_time)
    return Time(0) + Second(func(seconds))
end

"""
    save(data)
    save(data; format=:matlab)
    save(data; filename="custom_file_name.ext")

Save data to a file

By default saves to julia format (.jld2) but can also export
data to matlab by using the format=:matlab keyword argument
"""
function save(data; filename = "", format = :julia)
    if isempty(filename)
        t = Dates.format(Dates.now(), "yy-mm-dd_HH:MM:SS")
        filename = "scan_" * t
    end
    if format == :julia
        @save (filename * ".jld2") data
    elseif format == :matlab
        if isa(data, ScopeData)
            data = ScopeData(data.info, ustrip(data.volt), data.time)
        end
        file = matopen(filename * ".mat", "w")
        write(file, "data", data)
        close(file)
    end
end

"""
    data = load("file.jld2")

Loads saved data from a file
"""
function load(filename)
    ext = split(filename, '.')[end]
    if ext == "jld2"
        jldopen(filename)["data"]
    else
        error("unsupported file type: $ext")
    end
end

"""
    scan_prologix(ip::AbstractString)

Given an IP Address to a prologix adapter return a
Dict of GPIB bus numbers that map to the connected device names
"""
function scan_prologix(ip::AbstractString)
    instr = initialize(Instrument, ip)
    return scan_prologix(instr)
end

"""
    scan_prologix(instr)

Given any instrument with a connection to a prologix adapter that
supports query and write. Return a Dict of GPIB bus numbers
that map to the connected device names
"""
function scan_prologix(obj)
    devices = Dict()
    for i in 0:15
        write(obj, "++addr $i")
        try
            devices[i] = query(obj, "*IDN?"; timeout = 0.5)
        catch

        end
    end
    return devices
end

"""
    scan_network(; network_id="10.1.30.0", host_range=1:255, v=false)
Will scan your network and report all found devices.

By searches for devices connected on port:
    - 5025 (scpi)
    - 1234 (prologix)
"""
function scan_network(; network="10.1.30.", host_range=1:255)
    network = ensure_ending_dot(network)
    @info "Scanning $network$(host_range[1])-$(host_range[end])"

    # Scan for SCPI devices
    ips_scpi = asyncmap(x-> _get_info_from_ip(x), [network*"$ip" for ip in host_range])
    # Scan for Prologix device
    ips_prlx = asyncmap(x-> _get_info_from_ip(x; port=1234), [network*"$ip" for ip in host_range])

    ips_all = vcat(ips_scpi, ips_prlx)
    print("\n")
    return [ip for ip in ips_all if !isempty(ip)]
end
ensure_ending_dot(network) = network[end] != '.' ? network*'.' : network

function _get_info_from_ip(ip_str; port = 5025)
    temp_ip = ip_str * ":$port"
    print(".")
    proc = @spawn temp_ip => _get_instr_info_and_close(temp_ip)
    sleep(2)
    if proc.state == :runnable
        print("t") # for time out
        kill_task(proc)
        return ""
    elseif proc.state == :done
        printstyled("s"; color = :green) # for success
        return fetch(proc)
    elseif proc.state == :failed
        print("f") # for failed
        return ""
    else
        error("Uncaught state: $(proc.state)")
    end
end

kill_task(proc) = schedule(proc, ErrorException("Timed out"), error=true)

function _get_instr_info_and_close(ip)

    obj = initialize(Instrument, ip)
    info_str = info(obj)
    close(obj)
    return info_str
end

"""
    scan_prologix(ip::AbstractString)
    Scans all GPIB addresses on a prologix device having the ip-address `ip`.
"""
function scan_prologix(ip::AbstractString)
    devices = Dict()
    prologix_port = ":1234"
    full_ip = ip * prologix_port
    obj = initialize(Instrument, ip)

    for i in 0:15
        write(obj, "++addr $i")
        try
            devices[i] = query(obj, "*IDN?"; timeout=0.5)
        catch

        end
    end
    return devices
end

udef(func) =  error("$(func) not implemented")

macro codeLocation()
    return quote
        st = stacktrace(backtrace())
        myf = ""
        for frm in st
            funcname = frm.func
            if frm.func != :backtrace && frm.func != Symbol("macro expansion")
                myf = frm.func
                break
            end
        end
        println(
            "Running function ",
            $("$(__module__)"),
            ".$(myf) at ",
            $("$(__source__.file)"),
            ":",
            $("$(__source__.line)"),
        )

        myf
    end
end

function alias_print(msg)
    printstyled("[ Aliasing: ", color = :blue, bold = true)
    println(msg)
end

"""
	split_str_into_host_and_port(str)
Splits a string like "192.168.1.1:5056" into ("192.168.1.1", 5056)
"""
function split_str_into_host_and_port(str::AbstractString)
	spl_str = split(str, ":")
    isempty(spl_str) && error("IP address string is empty!")
    host = spl_str[1]
    if length(spl_str) == 1
        port = 0
    else
        port = parse(Int, spl_str[2])
    end
    return (host, port)
end


module TestInterface

using Functors
using Random
using Test

function test_interface(rng::AbstractRNG, lik, out_dist, D_in=1; functor_args=())
    N = 10
    T = Float64 # TODO test Float32 as well
    f, fs = if D_in == 1
        f = randn(rng, T)
        fs = randn(rng, T, 10)
        f, fs
    else
        f = randn(rng, T, D_in)
        fs = [randn(rng, T, D_in) for _ in 1:N]
        f, fs
    end
    # Check if likelihood produces the correct distribution
    # and is sampleable
    @test lik(f) isa out_dist
    @test_nowarn rand(rng, lik(f))

    # Check if the likelihood samples are of correct length
    @test length(rand(rng, lik(fs))) == N

    # Check if functor works properly
    xs, re = Functors.functor(lik)
    @test lik == re(xs)
    if isempty(functor_args)
        @test xs === ()
    else
        @test keys(xs) == functor_args
    end

    return nothing
end

@doc raw"""
    test_interface([rng::AbstractRNG,] lik, out_dist; functor_args=())

This function provides unified method to check the interface of the various likelihoods
defined. It checks if the likelihood produces the correct distribution, length of likelihood
samples is correct and if the functor works as intended.

...
## Arguments
- `lik`: the likelihood to test the interface of
- `out_dist::Type{<:Distribution}`: the type of distribution the likelihood should return
- `D_in::Int=1` : The input dimension of the likelihood

## Keyword arguments
- `functor_args=()`: a collection of symbols of arguments to match functor parameters with.
...
"""
function test_interface(lik, out_dist, D_in=1; kwargs...)
    return test_interface(Random.GLOBAL_RNG, lik, out_dist, D_in; kwargs...)
end

end


include("common.jl")

function symbol_to_inttype(::Type{Normed}, s::Symbol)
    d = Dict(:i8 => UInt8, :i16 => UInt16, :i32 => UInt32, :i64 => UInt64, :i128 => UInt128)
    d[s]
end

@testset "domain of f" begin
    @test_throws DomainError zero(Normed{UInt8,-1})
    @test_throws DomainError zero(Normed{UInt8,0})
    @test_throws DomainError zero(Normed{UInt8,9})
    @test_throws DomainError zero(Normed{UInt16,17})
end

@testset "construction using type suffix" begin
    @test 0.635N0f8  ===  N0f8(0.635)
    @test 0.635N6f10 === N6f10(0.635)
    @test 0.635N4f12 === N4f12(0.635)
    @test 0.635N2f14 === N2f14(0.635)
    @test 0.635N0f16 === N0f16(0.635)

    @test_throws ArgumentError 1.1N0f8

    @test wrapping_mul(0.635, N0f8) === N0f8(0.635)
    @test wrapping_mul(1.635, N0f8) === N0f8((1.635 * 255 - 256) / 255)
    @test saturating_mul(0.635, N0f8) === N0f8(0.635)
    @test saturating_mul(1.635, N0f8) === N0f8(1.0)
    @test checked_mul(0.635, N0f8) === N0f8(0.635)
    @test_throws ArgumentError checked_mul(1.635, N0f8)
end

@testset "reinterpret/bitstring" begin
    @test reinterpret(N0f8, 0xa2).i  === 0xa2
    @test reinterpret(N6f10, 0x1fa2).i === 0x1fa2
    @test reinterpret(N4f12, 0x1fa2).i === 0x1fa2
    @test reinterpret(N2f14, 0x1fa2).i === 0x1fa2
    @test reinterpret(N0f16, 0x1fa2).i === 0x1fa2

    @test reinterpret(reinterpret(N0f8, 0xa2))    === 0xa2
    @test reinterpret(reinterpret(N6f10, 0x00a2)) === 0x00a2
    @test reinterpret(reinterpret(N4f12, 0x00a2)) === 0x00a2
    @test reinterpret(reinterpret(N2f14, 0x00a2)) === 0x00a2
    @test reinterpret(reinterpret(N0f16, 0x00a2)) === 0x00a2

    @test reinterpret(UInt8, 1N0f8) === 0xff

    @test bitstring(reinterpret(N0f8, 0xa2))    === "10100010"
    @test bitstring(reinterpret(N6f10, 0x00a2)) === "0000000010100010"

    @test N0f8(1.0) == reinterpret(N0f8, 0xff)
    @test N0f8(0.5) == reinterpret(N0f8, 0x80)
    @test N2f14(1.0) == reinterpret(N2f14, 0x3fff)
    v = N4f12.([2])
    @test v == N4f12[reinterpret(N4f12, 0x1ffe)]
    @test isa(v, Vector{N4f12})
end

@testset "limits and identities" begin
    @testset "$N" for N in target(Normed)
        T, f = rawtype(N), nbitsfrac(N)
        @test zero(N) == 0
        @test one(N) == 1
        @test one(N) * oneunit(N) == oneunit(N)
        @test typemin(N) == 0
        @test typemax(N) == typemax(T)//(big"2"^f - 1)
        @test floatmin(N) === eps(N) == 1//(big"2"^f - 1)
        @test floatmax(N) === typemax(N)
        @test eps(zero(N)) === eps(typemax(N))
        @test sizeof(N) == sizeof(T)
    end
end

@testset "inexactness" begin
    # TODO: change back to InexactError when it allows message strings
    @test_throws ArgumentError N0f8(2)
    @test_throws ArgumentError N0f8(0xff)
    @test_throws ArgumentError N0f16(2)
    @test_throws ArgumentError N0f16(0xff)
    @test_throws ArgumentError N0f16(0xffff)
    @test_throws ArgumentError convert(N0f8,  typemax(N6f10))
    @test_throws ArgumentError convert(N0f16, typemax(N6f10))
    @test_throws ArgumentError convert(Normed{UInt128,100}, 10^9)

    ret = @test_throws ArgumentError N0f8(255)
    msg = ret.value.msg
    @test occursin("N0f8 is an 8-bit type representing 256 values from 0.0 to 1.0;", msg)
    ret = @test_throws ArgumentError convert(Normed{UInt128,100}, 10.0^9)
    msg = ret.value.msg
    @test occursin("Normed{UInt128,$(SP)100} is a 128-bit type representing 2^128 values", msg)
end

@testset "disambiguation constructors" begin
    @test_throws ArgumentError Normed{UInt32,16}('a')
    @test_throws InexactError  Normed{UInt32,16}(complex(1.0, 1.0))
    @test Normed{UInt32,16}(complex(1.0, 0.0)) == 1
    @test Normed{UInt32,16}(Base.TwicePrecision(1.0, 0.0)) == 1
end

@testset "conversion" begin
    x = N0f8(0.5)
    @test convert(N0f8, x) === x

    @test convert(N0f8,  1.1/typemax(UInt8)) === eps(N0f8)
    @test convert(N0f8,  1.1f0/typemax(UInt8)) === eps(N0f8)
    @test convert(N6f10, 1.1/typemax(UInt16)*64) === eps(N6f10)
    @test convert(N4f12, 1.1/typemax(UInt16)*16) === eps(N4f12)
    @test convert(N2f14, 1.1/typemax(UInt16)*4)  === eps(N2f14)
    @test convert(N0f16, 1.1/typemax(UInt16))    === eps(N0f16)
    @test convert(N16f16, 1.1/typemax(UInt32)*2^16) === eps(N16f16)
    @test convert(N61f3,  1.1/typemax(UInt64)*UInt64(2)^61) === eps(N61f3)
    @test convert(Normed{UInt128,7}, 1.1/typemax(UInt128)*UInt128(2)^121) === eps(Normed{UInt128,7})

    @test convert(N0f8, Base.TwicePrecision(1.0)) === 1N0f8

    @test convert(N0f16, one(N0f8)) === one(N0f16)
    @test convert(N0f16, N0f8(0.5)) === reinterpret(N0f16, 0x8080)
    @test convert(N9f7, N1f7(0.504)) === N9f7(0.504)

    # avoiding overflow with Float16
    @test N0f16(Float16(1.0)) === N0f16(1.0)
    @test Float16(1.0) % N0f16 === N0f16(1.0)
end

@testset "bool conversions" begin
    @testset "$N to/from Bool" for N in target(Normed)
        @test convert(Bool, zero(N)) === false
        @test convert(Bool, oneunit(N))  === true
        eps(N) < 1 && @test_throws InexactError convert(Bool, convert(N, 0.2))
        @test convert(N, true) === oneunit(N)
        @test convert(N, false) === zero(N)
    end
    @test Bool(1N0f8) === true
end

@testset "integer conversions" begin
    @testset "$N to/from integer" for N in target(Normed)
        @test convert(Int, oneunit(N)) === 1
        @test convert(Integer, oneunit(N)) === oneunit(rawtype(N))
        @test convert(N, 1) === oneunit(N)
        @test convert(N, 0x0) === zero(N)
    end
    @test convert(UInt, 1N1f7) === UInt(1)
    @test_throws InexactError convert(Integer, 0.5N1f7)
    @test_throws InexactError convert(Int8, 256N8f8)
end

@testset "rational conversions" begin
    @testset "$N to/from rational" for N in target(Normed)
        @test convert(Rational, oneunit(N)) == 1//1
        @test convert(Rational{Int}, zero(N)) === 0//1
        @test convert(N, 1//1) === oneunit(N)
    end
    @test convert(N0f8, 1//255) === eps(N0f8)
    @test convert(N0f8, Rational{Int8}(3//5)) === N0f8(3/5)
    @test convert(N0f8, Rational{UInt8}(3//5)) === N0f8(3/5)
    @test_throws ArgumentError convert(N0f8, typemax(Rational{UInt8}))

    @test convert(Rational, 0.5N0f8) === Rational{UInt8}(0x80//0xff)
    @test convert(Rational, 0.5N4f12) === Rational{UInt16}(0x800//0xfff)
    @test convert(Rational{Int}, 0.5N0f8) === Rational{Int}(0x80//0xff)

    @test rationalize(0.8N0f8) === Rational{Int}(4//5)
    @test rationalize(Int16, 0.804N0f8) === Rational{Int16}(41//51)
    @test rationalize(0.804N0f8, tol=0.002) === Rational{Int}(41//51)
    @test rationalize(Int8, 0.804N0f8, tol=0.005) === Rational{Int8}(4//5)
end

@testset "BigFloat conversions" begin
    @test convert(BigFloat, 0.5N0f8)::BigFloat == 128 / big"255"
    @test convert(BigFloat, eps(N0f8))::BigFloat == 1 / big"255"

    @test big(N7f1) === BigFloat # !== BigInt
    @test big(0.5N4f4)::BigFloat == 8 / big"15"
end

@testset "float/floattype" begin
    @test float(0.8N4f4) === 0.8f0
    @test float(0.8N20f12) === 0.8
    @test float(0.8N8f24) === 0.8
    @test float(1N11f53)::BigFloat == big"1.0"

    test_floattype(Normed)
end

@testset "conversions from float" begin
    # issue 102
    for Tf in (Float16, Float32, Float64)
        @testset "$N(::$Tf)" for N in target(Normed)
            T, f = rawtype(N), nbitsfrac(N)
            r = FixedPointNumbers.rawone(N)

            @test reinterpret(N(zero(Tf))) == 0x0

            input_typemax = Tf(typemax(N))
            if isinf(input_typemax)
                @test reinterpret(N(floatmax(Tf))) >= round(T, floatmax(Tf))
            else
                @test reinterpret(N(input_typemax)) > (typemax(T)>>1) # overflow check
                @test N(input_typemax) >= N(prevfloat(input_typemax))
             end

            input_upper = Tf(BigFloat(typemax(T)) / r, RoundDown)
            isinf(input_upper) && continue # for Julia v0.7
            @test reinterpret(N(input_upper)) == T(min(round(BigFloat(input_upper) * r), typemax(T)))

            input_exp2 = Tf(exp2(bitwidth(T) - f))
            isinf(input_exp2) && continue
            @test reinterpret(N(input_exp2)) == T(input_exp2) * r
        end
    end
    @test N0f32(Float32(0x0.7FFFFFp-32)) == zero(N0f32)
    @test N0f32(Float32(0x0.800000p-32)) <= eps(N0f32) # should be zero in RoundNearest mode
    @test N0f32(Float32(0x0.800001p-32)) == eps(N0f32)

    test_convert_from_nan(Normed)
end

@testset "conversions to float" begin
    x = N0f8(0.3)
    for T in (Float16, Float32, Float64)
        y = convert(T, x)
        @test isa(y, T)
    end

    for Tf in (Float16, Float32, Float64)
        @testset "$Tf(::$N)" for N in target(Normed, :i8, :i16)
            T = rawtype(N)
            float_err = zero(Tf)
            for i = typemin(T):typemax(T)
                b_expected = i / BigFloat(FixedPointNumbers.rawone(N))
                f_expected = Tf(promote_type(Tf, Float32)(b_expected)) # workaround for issue #246
                isinf(f_expected) && break # for Float16(::Normed{UInt16,1})
                f_actual = Tf(reinterpret(N, i))
                float_err += abs(f_actual - f_expected)
            end
            @test float_err == 0
        end
        @testset "$Tf(::$N)" for N in target(Normed, :i32, :i64, :i128)
            T = rawtype(N)
            error_count = 0
            for i in vcat(T(0x00):T(0xFF), (typemax(T)-0xFF):typemax(T))
                b_expected = i / BigFloat(FixedPointNumbers.rawone(N))
                f_expected = Tf(promote_type(Tf, Float32)(b_expected)) # workaround for issue #246
                isinf(f_expected) && break # for Float16() and Float32()
                f_actual = Tf(reinterpret(N, i))
                f_actual == f_expected && continue
                f_actual == prevfloat(f_expected) && continue
                f_actual == nextfloat(f_expected) && continue
                error_count += 1
            end
            @test error_count == 0
        end
    end
end

@testset "type modulus" begin
    test_rem_type(Normed)
    test_rem_nan(Normed)

    @test  N0f8(0.2) % N0f8  === N0f8(0.2)
    @test N2f14(1.2) % N0f16 === N0f16(0.20002)
    @test N2f14(1.2) % N0f8  === N0f8(0.196)

    @test ( 1.5 % N0f8).i == round(Int,  1.5*255) % UInt8
    @test (-0.3 % N0f8).i == round(Int, -0.3*255) % UInt8

    @test (65.2 % N6f10).i == round(Int, 65.2*1023) % UInt16
    @test (-0.3 % N6f10).i == round(Int, -0.3*1023) % UInt16

    @test 1 % N0f8 === N0f8(1)
    @test 2 % N0f8 === N0f8(0.996)

    # issue #150
    @test all(f -> 1.0f0 % Normed{UInt32,f} == oneunit(Normed{UInt32,f}), 1:32)
    @test all(f -> 1.0e0 % Normed{UInt64,f} == oneunit(Normed{UInt64,f}), 1:64)

    # issue #211
    @test big"1.2" % N0f8 === 0.196N0f8
    @test reinterpret(BigFloat(0x0_01234567_89abcdef) % N63f1) === 0x01234567_89abcdef
end

@testset "arithmetic" begin
    @testset "$N arithmetic" for N in target(Normed; ex = :light)
        x = N(0x10,0)
        y = N(0x25,0)
        fx = float(x)
        fy = float(y)
        @test y > x
        @test y != x
        @test x+y === N(0x35,0)
        @test ((x+y)-y) === x
        @test ((x-y)+y) === x # wraparound
        fx*fy <= typemax(N) && @test (x*y)::N ≈ convert(N, fx*fy)
        @test (x/y)::N ≈ convert(N, fx/fy)
        fx^2 <= typemax(N) && @test (x^2)::N ≈ convert(N, fx^2)
        @test (x^2.1f0) ≈ fx^2.1f0
        @test (x^2.1) ≈ convert(Float64, x)^2.1
    end
end

@testset "neg" begin
    for N in target(Normed; ex = :thin)
        @test   wrapping_neg(typemin(N)) === zero(N)
        @test saturating_neg(typemin(N)) === zero(N)
        @test    checked_neg(typemin(N)) === zero(N)

        @test   wrapping_neg(typemax(N)) === eps(N)
        @test saturating_neg(typemax(N)) === zero(N)
        @test_throws OverflowError checked_neg(typemax(N))

        @test   wrapping_neg(eps(N)) === typemax(N)
        @test saturating_neg(eps(N)) === zero(N)
        @test_throws OverflowError checked_neg(eps(N))
    end
    test_neg(Normed)
end

@testset "abs" begin
    for N in target(Normed; ex = :thin)
        @test   wrapping_abs(typemax(N)) === typemax(N)
        @test saturating_abs(typemax(N)) === typemax(N)
        @test    checked_abs(typemax(N)) === typemax(N)

        @test   wrapping_abs(typemin(N)) === typemin(N)
        @test saturating_abs(typemin(N)) === typemin(N)
        @test    checked_abs(typemin(N)) === typemin(N)
    end
    test_abs(Normed)
end

@testset "add" begin
    for N in target(Normed; ex = :thin)
        @test   wrapping_add(typemin(N), typemin(N)) === zero(N)
        @test saturating_add(typemin(N), typemin(N)) === zero(N)
        @test    checked_add(typemin(N), typemin(N)) === zero(N)

        @test   wrapping_add(typemax(N), eps(N)) ===   wrapping_add(eps(N), typemax(N)) === zero(N)
        @test saturating_add(typemax(N), eps(N)) === saturating_add(eps(N), typemax(N)) === typemax(N)
        @test_throws OverflowError checked_add(typemax(N), eps(N))
        @test_throws OverflowError checked_add(eps(N), typemax(N))

        @test   wrapping_add(zero(N), eps(N)) ===   wrapping_add(eps(N), zero(N)) === eps(N)
        @test saturating_add(zero(N), eps(N)) === saturating_add(eps(N), zero(N)) === eps(N)
        @test    checked_add(zero(N), eps(N)) ===    checked_add(eps(N), zero(N)) === eps(N)
    end
    test_add(Normed)
end

@testset "sub" begin
    for N in target(Normed; ex = :thin)
        @test   wrapping_sub(typemin(N), typemin(N)) === zero(N)
        @test saturating_sub(typemin(N), typemin(N)) === zero(N)
        @test    checked_sub(typemin(N), typemin(N)) === zero(N)

        @test   wrapping_sub(typemin(N), eps(N)) === typemax(N)
        @test saturating_sub(typemin(N), eps(N)) === typemin(N)
        @test_throws OverflowError checked_sub(typemin(N), eps(N))

        @test   wrapping_sub(eps(N), zero(N)) === eps(N)
        @test saturating_sub(eps(N), zero(N)) === eps(N)
        @test    checked_sub(eps(N), zero(N)) === eps(N)
    end
    test_sub(Normed)
end

@testset "mul" begin
    for N in target(Normed; ex = :thin)
        @test   wrapping_mul(typemax(N), zero(N)) === zero(N)
        @test saturating_mul(typemax(N), zero(N)) === zero(N)
        @test    checked_mul(typemax(N), zero(N)) === zero(N)

        @test   wrapping_mul(one(N), typemax(N)) === typemax(N)
        @test saturating_mul(one(N), typemax(N)) === typemax(N)
        @test    checked_mul(one(N), typemax(N)) === typemax(N)

        @test   wrapping_mul(typemax(N), typemax(N)) === big(typemax(N))^2 % N
        @test saturating_mul(typemax(N), typemax(N)) === typemax(N)
        if typemax(N) != 1
            @test_throws OverflowError checked_mul(typemax(N), typemax(N))
        end
    end
    test_mul(Normed)
end

@testset "fdiv" begin
    for N in target(Normed; ex = :thin)
        @test   wrapping_fdiv(typemax(N), typemax(N)) === one(N)
        @test saturating_fdiv(typemax(N), typemax(N)) === one(N)
        @test    checked_fdiv(typemax(N), typemax(N)) === one(N)

        @test   wrapping_fdiv(zero(N), eps(N)) === zero(N)
        @test saturating_fdiv(zero(N), eps(N)) === zero(N)
        @test    checked_fdiv(zero(N), eps(N)) === zero(N)

        @test   wrapping_fdiv(typemax(N), eps(N)) === (floattype(N))(typemax(rawtype(N))) % N
        @test saturating_fdiv(typemax(N), eps(N)) === typemax(N)
        @test_throws OverflowError checked_fdiv(typemax(N), eps(N))

        @test   wrapping_fdiv(zero(N), zero(N)) === zero(N)
        @test saturating_fdiv(zero(N), zero(N)) === zero(N)
        @test_throws DivideError checked_fdiv(zero(N), zero(N))

        @test   wrapping_fdiv(eps(N), zero(N)) === zero(N)
        @test saturating_fdiv(eps(N), zero(N)) === typemax(N)
        @test_throws DivideError checked_fdiv(eps(N), zero(N))
    end
    test_fdiv(Normed)
end

@testset "div/cld/fld" begin
    for N in target(Normed; ex = :thin)
        nm, nz, ne = typemax(N), zero(N), eps(N)
        T = rawtype(N)
        @test   wrapping_div(nm, nm) ===   wrapping_fld(nm, nm) ===   wrapping_cld(nm, nm) === one(T)
        @test saturating_div(nm, nm) === saturating_fld(nm, nm) === saturating_cld(nm, nm) === one(T)
        @test    checked_div(nm, nm) ===    checked_fld(nm, nm) ===    checked_cld(nm, nm) === one(T)

        @test   wrapping_div(nz, ne) ===   wrapping_fld(nz, ne) ===   wrapping_cld(nz, ne) === zero(T)
        @test saturating_div(nz, ne) === saturating_fld(nz, ne) === saturating_cld(nz, ne) === zero(T)
        @test    checked_div(nz, ne) ===    checked_fld(nz, ne) ===    checked_cld(nz, ne) === zero(T)

        @test   wrapping_div(nm, ne) ===   wrapping_fld(nm, ne) ===   wrapping_cld(nm, ne) === typemax(T)
        @test saturating_div(nm, ne) === saturating_fld(nm, ne) === saturating_cld(nm, ne) === typemax(T)
        @test    checked_div(nm, ne) ===    checked_fld(nm, ne) ===    checked_cld(nm, ne) === typemax(T)

        @test   wrapping_div(nz, nz) ===   wrapping_fld(nz, nz) ===   wrapping_cld(nz, nz) === zero(T)
        @test saturating_div(nz, nz) === saturating_fld(nz, nz) === saturating_cld(nz, nz) === zero(T)
        @test_throws DivideError checked_div(nz, nz)
        @test_throws DivideError checked_fld(nz, nz)
        @test_throws DivideError checked_cld(nz, nz)

        @test   wrapping_div(ne, nz) ===   wrapping_fld(ne, nz) ===   wrapping_cld(ne, nz) === zero(T)
        @test saturating_div(ne, nz) === saturating_fld(ne, nz) === saturating_cld(ne, nz) === typemax(T)
        @test_throws DivideError checked_div(ne, nz)
        @test_throws DivideError checked_fld(ne, nz)
        @test_throws DivideError checked_cld(ne, nz)

        @test wrapping_div(ne, nm) === saturating_div(ne, nm) === checked_div(ne, nm) === zero(T)
        @test wrapping_fld(ne, nm) === saturating_fld(ne, nm) === checked_fld(ne, nm) === zero(T)
        @test wrapping_cld(ne, nm) === saturating_cld(ne, nm) === checked_cld(ne, nm) === one(T)
    end
    test_div(Normed)
    test_div_3arg(Normed)
end

@testset "rem/mod" begin
    for N in target(Normed; ex = :thin)
        nm, nz, ne = typemax(N), zero(N), eps(N)
        T = rawtype(N)
        @test   wrapping_rem(nm, nm) ===   wrapping_mod(nm, nm) === nz
        @test saturating_rem(nm, nm) === saturating_mod(nm, nm) === nz
        @test    checked_rem(nm, nm) ===    checked_mod(nm, nm) === nz

        @test   wrapping_rem(nz, ne) ===   wrapping_mod(nz, ne) === nz
        @test saturating_rem(nz, ne) === saturating_mod(nz, ne) === nz
        @test    checked_rem(nz, ne) ===    checked_mod(nz, ne) === nz

        @test   wrapping_rem(nm, ne) ===   wrapping_mod(nm, ne) === nz
        @test saturating_rem(nm, ne) === saturating_mod(nm, ne) === nz
        @test    checked_rem(nm, ne) ===    checked_mod(nm, ne) === nz

        @test   wrapping_rem(nz, nz) ===   wrapping_mod(nz, nz) === nz
        @test saturating_rem(nz, nz) === saturating_mod(nz, nz) === nz
        @test_throws DivideError checked_rem(nz, nz)
        @test_throws DivideError checked_mod(nz, nz)

        @test   wrapping_rem(ne, nz) ===   wrapping_mod(ne, nz) === ne
        @test saturating_rem(ne, nz) === saturating_mod(ne, nz) === ne
        @test_throws DivideError checked_rem(ne, nz)
        @test_throws DivideError checked_mod(ne, nz)

        @test wrapping_rem(ne, nm) === saturating_rem(ne, nm) === checked_rem(ne, nm) === ne
        @test wrapping_mod(ne, nm) === saturating_mod(ne, nm) === checked_mod(ne, nm) === ne
    end
    test_rem(Normed)
    test_rem_3arg(Normed)

    @test_throws OverflowError rem(0.5N0f8, 1N0f8, RoundUp)
    @test saturating_rem(0.5N0f8, 1N0f8, RoundUp) === zero(N0f8)
end

@testset "fld1/mod1" begin
    test_fld1_mod1(Normed)
end

@testset "rounding" begin
    for sym in (:i8, :i16, :i32, :i64)
        T = symbol_to_inttype(Normed, sym)
        rs = vcat([ oneunit(T) << b - oneunit(T) << 1 for b = 1:bitwidth(T)],
                  [ oneunit(T) << b - oneunit(T)      for b = 1:bitwidth(T)],
                  [ oneunit(T) << b                   for b = 2:bitwidth(T)-1])
        @testset "rounding $N" for N in target(Normed, sym)
            xs = (reinterpret(N, r) for r in rs)
            @test all(x -> trunc(x) == trunc(float(x)), xs)
            @test all(x -> floor(x) == floor(float(x)), xs)
            # force `Normed` comparison avoiding rounding errors
            @test all(x -> ceil(float(x)) > typemax(N) || ceil(x) == N(ceil(float(x))), xs)
            @test all(x -> round(x) == round(float(x)), xs)
            @test all(x -> trunc(UInt64, x) === trunc(UInt64, float(x)), xs)
            @test all(x -> floor(UInt64, x) === floor(UInt64, float(x)), xs)
            @test all(x ->  ceil(UInt64, x) ===  ceil(UInt64, float(x)), xs)
            @test all(x -> round(UInt64, x) === round(UInt64, float(x)), xs)
        end
    end
    @testset "rounding Normed{Int16,$f} with overflow" for f in filter(x->!ispow2(x), 1:16)
        N = Normed{UInt16,f}
        @test_throws ArgumentError ceil(typemax(N))
        @test_throws ArgumentError ceil(floor(typemax(N)) + eps(N))
    end
    @testset "rounding mode" begin
        @test round(1.504N1f7, RoundNearest) === 2N1f7
        @test round(1.504N1f7, RoundToZero) === 1N1f7
        @test round(1.504N1f7, RoundUp) === 2N1f7
        @test round(1.504N1f7, RoundDown) === 1N1f7
        @test round(Int, 1.504N1f7, RoundNearest) === 2
        @test round(Int, 1.504N1f7, RoundToZero) === 1
        @test round(Int, 1.504N1f7, RoundUp) === 2
        @test round(Int, 1.504N1f7, RoundDown) === 1
    end
    @testset "rounding with digits" begin
        test_round_digits(Normed)
    end
end

@testset "approx" begin
    test_isapprox(Normed)

    @test isapprox(typemin(N0f8), typemax(N0f8), rtol=1.0)
    @test !isapprox(zero(N0f8), typemax(N0f8), rtol=0.9)
    @test isapprox(zero(N0f8), eps(N0f8), rtol=1e-6) # atol = eps(N0f8)
    @test !isapprox(eps(N0f8), zero(N0f8), rtol=1e-6, atol=1e-6)
    @test !isapprox(0.66N6f2, 1.0N6f2, rtol=0.3, atol=0) # 1.0 * 0.3 < eps(N6f2)

    @test isapprox(eps(N8f8), eps(N0f8), rtol=1e-6)
end

@testset "comparison" begin
    @test !(N0f8(0.5) < N0f8(0.5))
    @test N0f8(0.5) <= N0f8(0.5)

    @test minmax(N0f8(0.8), N0f8(0.2)) === (N0f8(0.2), N0f8(0.8))
end

@testset "clamp" begin
    @test clamp(0.5N0f8, 0.2N0f8, 0.8N0f8) === 0.5N0f8
    @test clamp(0.5N0f8, 0.6N0f8, 0.8N0f8) === 0.6N0f8
    @test clamp(0.5N0f8, 0.2N0f8, 0.4N0f8) === 0.4N0f8
    @test clamp(0.5,      0.2N0f8, 0.8N0f8) === 0.5
    @test clamp(0.5f0,    0.6N0f8, 0.8N0f8) === 0.6f0
    @test clamp(0.5N0f16, 0.2N0f8, 0.4N0f8) === 0.4N0f16
    @test clamp(0.6N0f8, -Inf, Inf) === 0.6
    @test clamp(0.5,     N0f8) === 0.5N0f8
    @test clamp(-1.0f0,  N0f8) === 0.0N0f8
    @test clamp(2.0N1f7, N0f8) === 1.0N0f8

    test_clamp_nan(Normed)
end

@testset "sign-related functions" begin
    @test_throws Exception signed(N0f8)
    @test_throws Exception signed(1N0f8)
    @test_throws Exception unsigned(N0f8)
    @test_throws Exception unsigned(1N0f8)
    @test_throws ArgumentError copysign(1N0f8, 0x1)
    @test_throws ArgumentError copysign(1N0f8, -1)
    @test_throws ArgumentError flipsign(1N0f8, 0x1)
    @test_throws ArgumentError flipsign(1N0f8, -1)
    @test_throws ArgumentError sign(0N0f8)
    @test signbit(1N0f8) === false
end

@testset "bitwise" begin
    x = N0f8(0b01010001, 0)
    @test ~x == N0f8(0b10101110, 0)
    @test -x == reinterpret(N0f8, 0xaf)

    @test bswap(N0f8(0.5)) === N0f8(0.5)
    @test bswap(N0f16(0.5)) === reinterpret(N0f16, 0x0080)
end

@testset "predicates" begin
    @test isfinite(1N8f8)
    @test !isnan(1N8f8)
    @test !isinf(1N8f8)

    @testset "isinteger" begin
        test_isinteger(Normed)
        @testset "isinteger(::$N)" for N in target(Normed, :i32, :i64, :i128)
            if nbitsfrac(N) == 1
                @test isinteger(zero(N)) & isinteger(oneunit(N))
            else
                @test !isinteger(oneunit(N) - eps(N)) & isinteger(oneunit(N))
            end
        end
    end
end

@testset "unit range" begin
    @test length(N0f8(0):N0f8(1)) == 2
    @test length(N0f8(1):N0f8(0)) == 0
    @test isempty(N0f8(1):N0f8(0))
    @test collect(N0f8(0):N0f8(1)) == N0f8[0, 1]
    @test length(0.5N1f7:1.504N1f7) == 2
    @test length(N7f1(0):N7f1(255)) == 256
    NIntW = Normed{UInt,bitwidth(UInt)}
    @test length(NIntW(0):NIntW(1)) == 2
    NInt1 = Normed{UInt,1}
    @test length(NInt1(0):typemax(NInt1)-oneunit(NInt1)) == typemax(UInt)
    @test_throws OverflowError length(NInt1(0):typemax(NInt1))
    N64f64 = Normed{UInt128,64}
    @test_broken length(N64f64(0):typemax(N64f64)) == UInt128(typemax(UInt64)) + 1
    @test length(N1f63(2):N1f63(0)) == 0
end

@testset "step range" begin
    counter = 0
    for x in N0f8(0):eps(N0f8):N0f8(1)
        counter += 1
    end
    @test counter == 256
    @test length(N0f8(0):eps(N0f8):N0f8(1)) == 256
    r = reinterpret(N0f8, 0x01):reinterpret(N0f8, 0x01):reinterpret(N0f8, UInt8(48))
    @test length(r) == 48
    NInt1 = Normed{UInt,1}
    @test length(NInt1(0):NInt1(1):typemax(NInt1)-oneunit(NInt1)) == typemax(UInt)
    @test_throws OverflowError length(NInt1(0):NInt1(1):typemax(NInt1))
end

@testset "reductions" begin
    a = N0f8[reinterpret(N0f8, 0xff), reinterpret(N0f8, 0xff)]
    @test sum(a) == 2.0
    @test sum(a, dims=1) == [2.0]

    a = N2f14[3.2, 2.4]
    acmp = Float64(a[1])*Float64(a[2])
    @test prod(a) == acmp
    @test prod(a, dims=1) == [acmp]
end

@testset "reductions, Statistics" begin
    a = N0f8[reinterpret(N0f8, 0x80), reinterpret(N0f8, 0x40)]
    af = FixedPointNumbers.Treduce.(a)
    @test mean(a) === mean(af)
    @test std(a)  === std(af)
    @test var(a)  === var(af)
    m = mean(a)
    @test stdm(a, m) === stdm(af, m)
    @test varm(a, m) === varm(af, m)
end

@testset "rand" begin
    test_rand(Normed)
    @test rand(MersenneTwister(1234), N0f8) === 0.925N0f8
end

@testset "Promotion within Normed" begin
    @test @inferred(promote(N0f8(0.2), N0f8(0.8))) ===
        (N0f8(0.2), N0f8(0.8))
    @test @inferred(promote(Normed{UInt16,3}(0.2), Normed{UInt8,3}(0.86))) ===
        (Normed{UInt16,3}(0.2), Normed{UInt16,3}(0.86))
    @test @inferred(promote(Normed{UInt8,7}(0.197), Normed{UInt8,4}(0.8))) ===
        (Normed{UInt16,7}(0.197), Normed{UInt16,7}(0.8))

    @test Normed{UInt16,16}(1)   == Normed{UInt8,8}(1)
    @test Normed{UInt16,16}(0.2) == Normed{UInt8,8}(0.2)
    @test Normed{UInt16,8}(1)   == Normed{UInt8,8}(1)
    @test Normed{UInt16,8}(0.2) == Normed{UInt8,8}(0.2)
    @test Normed{UInt16,16}(1)   == Normed{UInt8,6}(1)
    @test Normed{UInt16,16}(0.20635) == Normed{UInt8,6}(0.20635)
    @test Normed{UInt16,4}(1)   == Normed{UInt8,6}(1)
    @test Normed{UInt16,4}(0.2) == Normed{UInt8,6}(0.2)

    @test @inferred(promote_type(N0f8, Float64)) === Float64
    @test @inferred(promote_type(Float32, N8f24)) === Float64

    @test @inferred(promote_type(N0f8, Int8)) === Float32
    @test @inferred(promote_type(Int128, N8f24)) === Float64

    @test @inferred(promote_type(N0f16, Rational{Int8})) === Rational{Int8}

    @test @inferred(promote_type(N0f8, Float32, Int)) === Float32
    @test @inferred(promote_type(N0f8, Int, Float32)) === Float32
    @test @inferred(promote_type(Int, N0f8, Float32)) === Float32
    @test @inferred(promote_type(Int, Float32, N0f8)) === Float32
    @test @inferred(promote_type(Float32, Int, N0f8)) === Float32
    @test @inferred(promote_type(Float32, N0f8, Int)) === Float32

    @test @inferred(promote_type(N0f8,N1f7,N2f6,N3f5,N4f4,N5f3)) === Normed{UInt128,8}

    @test @inferred(promote_type(N0f8, Q0f31)) === Float64
end

@testset "show" begin
    @test (@test_deprecated FixedPointNumbers.typechar(N0f8)) === 'N'

    iob = IOBuffer()
    n0f8 = reinterpret(N0f8, 0xaa)
    show(iob, n0f8)
    str = String(take!(iob))
    @test str == "0.667N0f8"
    @test eval(Meta.parse(str)) === n0f8

    print(iob, n0f8)
    str = String(take!(iob))
    @test str == "0.667" # w/o type suffix

    n16f16 = reinterpret(N16f16, 0xaaaaaaaa)
    show(iob, n16f16)
    str = String(take!(iob))
    @test str == "43691.33333N16f16"
    @test eval(Meta.parse(str)) === n16f16

    show(IOContext(iob, :compact=>true), n16f16)
    @test String(take!(iob)) == "43691.3"

    show(IOContext(iob, :compact=>true, :typeinfo=>N16f16), n16f16)
    @test String(take!(iob)) == "43691.3"

    show(IOContext(iob, :compact=>true, :typeinfo=>Normed), n16f16)
    @test String(take!(iob)) == "43691.3"

    show(IOContext(iob, :typeinfo=>N16f16), n16f16)
    @test String(take!(iob)) == "43691.33333"

    show(IOContext(iob, :typeinfo=>Normed), n16f16)
    @test String(take!(iob)) == "43691.33333N16f16"

    show(iob, Normed{UInt128,64}(1.2345e6))
    @test String(take!(iob)) == "Normed{UInt128,$(SP)64}(1.2345e6)"
end

@testset "summary" begin
    a = N0f8[0.2, 0.4]
    aa = Normed[0.2N0f8 0.4N0f16]

    if VERSION >= v"1.6.0-DEV.356"
        @test summary(a) == "2-element Vector{N0f8}"
        @test summary(view(a, 1:2)) == "2-element view(::Vector{N0f8}, 1:2) with eltype N0f8"
        @test summary(aa) == "1×2 Matrix{Normed}"
    else
        @test summary(a) == "2-element Array{N0f8,1} with eltype Normed{UInt8,8}"
        @test summary(view(a, 1:2)) == "2-element view(::Array{N0f8,1}, 1:2) with eltype Normed{UInt8,8}"
        @test summary(aa) == "1×2 Array{Normed,2}"
    end
end

@testset "scaledual" begin
    a = rand(UInt8, 10)
    af8 = reinterpret(N0f8, a)
    b = 0.5

    # LHSs of the following `@test`s with `af8` can be slightly more accurate
    bd, eld = scaledual(b, af8[1])
    @test b*af8[1] ≈ bd*eld rtol=1e-15
    bd, ad = scaledual(b, af8)
    @test b*af8 ≈ bd*ad rtol=1e-15

    bd, eld = scaledual(b, a[1])
    @test b*a[1] == bd*eld
    bd, ad = scaledual(b, a)
    @test b*a == bd*ad

    bd, eld = scaledual(Float64, af8[1])
    @test 1.0*af8[1] ≈ bd*eld rtol=1e-15
    bd, ad = scaledual(Float64, af8)
    @test 1.0*af8 ≈ bd*ad rtol=1e-15

    bd, eld = scaledual(Float64, a[1])
    @test 1.0*a[1] == bd*eld
    bd, ad = scaledual(Float64, a)
    @test 1.0*a == bd*ad
end


"""
Calculate the contributions of a single source for a single pixel to
the sensitive floats E_G_s and var_G_s, which are cleared and updated in place.

Args:
    - ea: Model parameters
    - vp: the variational parameters
    - elbo_vars: Elbo intermediate values, with updated fs1m and fs0m.
    - sb: Source brightnesse
    - s: The source, in 1:ea.S
    - b: The band

Returns:
    Updates E_G_s, E_G2_s, and var_G_s in place with the brightness
    for this source at this pixel.
"""
function calculate_G_s!(vp::VariationalParams{T},
                        elbo_vars::ElboIntermediateVariables{T},
                        sb::SourceBrightness{T},
                        b::Int,
                        s::Int,
                        is_active_source::Bool) where {T<:Number}
    E_G_s = elbo_vars.E_G_s
    E_G2_s = elbo_vars.E_G2_s
    var_G_s = elbo_vars.var_G_s

    @assert E_G_s.local_P == var_G_s.local_P == length(CanonicalParams)
    @assert E_G_s.local_S == var_G_s.local_S == 1
    @assert elbo_vars.fs0m.local_P == length(StarPosParams)
    @assert elbo_vars.fs1m.local_P == length(GalaxyPosParams)

    # we'd like to get rid of these calls to `fill!`
    if is_active_source
        SensitiveFloats.zero!(E_G_s)
        SensitiveFloats.zero!(E_G2_s)
        SensitiveFloats.zero!(var_G_s)
    else
        E_G_s.v[] = 0.0
        E_G2_s.v[] = 0.0
        var_G_s.v[] = 0.0
    end

    @inbounds for i in 1:NUM_SOURCE_TYPES # Celestial object types (e.g. stars and galaxies)
        fsm_i = (i == 1) ? elbo_vars.fs0m : elbo_vars.fs1m
        a_i = vp[s][ids.is_star[i]]
        sb_E_l_a_b_i = sb.E_l_a[b, i]
        sb_E_ll_a_b_i = sb.E_ll_a[b, i]

        fsm_i_v = fsm_i.v[]
        sb_E_l_a_b_i_v = sb_E_l_a_b_i.v[]
        sb_E_ll_a_b_i_v = sb_E_ll_a_b_i.v[]

        fsm_i_d = fsm_i.d
        sb_E_l_a_b_i_d = sb_E_l_a_b_i.d
        sb_E_ll_a_b_i_d = sb_E_ll_a_b_i.d
        E_G_s_d = E_G_s.d
        E_G2_s_d = E_G2_s.d

        E_G_s_h = E_G_s.h
        E_G2_s_h = E_G2_s.h

        lf = sb_E_l_a_b_i_v * fsm_i_v
        llff = sb_E_ll_a_b_i_v * fsm_i_v^2

        E_G_s.v[] += a_i * lf
        E_G2_s.v[] += a_i * llff

        ############ Only gradient and hessian code below ##############
        (is_active_source && elbo_vars.elbo.has_gradient) || continue

        E_G_s_d[ids.is_star[i], 1] += lf
        E_G2_s_d[ids.is_star[i], 1] += llff

        p0_shape = shape_standard_alignment[i]
        p0_bright = brightness_standard_alignment[i]
        u_ind = i == 1 ? star_ids.pos : gal_ids.pos

        # Derivatives with respect to the spatial parameters
        tmp1 = sb_E_l_a_b_i_v * a_i
        tmp2 = sb_E_ll_a_b_i_v * 2 * fsm_i_v * a_i
        for p0_shape_ind in 1:length(p0_shape)
            E_G_s_d[p0_shape[p0_shape_ind], 1] += tmp1 * fsm_i_d[p0_shape_ind, 1]
            E_G2_s_d[p0_shape[p0_shape_ind], 1] += tmp2 * fsm_i_d[p0_shape_ind, 1]
        end

        # Derivatives with respect to the brightness parameters.
        for p0_bright_ind in 1:length(p0_bright)
            E_G_s_d[p0_bright[p0_bright_ind], 1] =
                a_i * fsm_i_v * sb_E_l_a_b_i_d[p0_bright_ind, 1]
            E_G2_s_d[p0_bright[p0_bright_ind], 1] =
                a_i * (fsm_i_v^2) * sb_E_ll_a_b_i_d[p0_bright_ind, 1]
        end

        ############ only hessian code below ##############
        elbo_vars.elbo.has_hessian || continue

        E_G_s_hsub = elbo_vars.E_G_s_hsub_vec[i]
        E_G2_s_hsub = elbo_vars.E_G2_s_hsub_vec[i]

        # The (a, a) block of the hessian is zero.

        # The (bright, bright) block:
        for p0_ind1 in 1:length(p0_bright), p0_ind2 in 1:length(p0_bright)
            E_G_s_h[p0_bright[p0_ind1], p0_bright[p0_ind2]] =
                a_i * sb_E_l_a_b_i.h[p0_ind1, p0_ind2] * fsm_i_v
            E_G2_s_h[p0_bright[p0_ind1], p0_bright[p0_ind2]] =
                (fsm_i_v^2) * a_i * sb_E_ll_a_b_i.h[p0_ind1, p0_ind2]
        end

        # The (shape, shape) block:
        p1, p2 = size(E_G_s_hsub.shape_shape)
        for ind1 = 1:p1, ind2 = 1:p2
            E_G_s_hsub.shape_shape[ind1, ind2] =
                a_i * sb_E_l_a_b_i_v * fsm_i.h[ind1, ind2]
            E_G2_s_hsub.shape_shape[ind1, ind2] =
                2 * a_i * sb_E_ll_a_b_i_v * (
                    fsm_i_v * fsm_i.h[ind1, ind2] +
                    fsm_i_d[ind1, 1] * fsm_i_d[ind2, 1])
        end

        # The u_u submatrix of this assignment will be overwritten after
        # the loop.
        for p0_ind1 in 1:length(p0_shape), p0_ind2 in 1:length(p0_shape)
            E_G_s_h[p0_shape[p0_ind1], p0_shape[p0_ind2]] =
                a_i * sb_E_l_a_b_i_v * fsm_i.h[p0_ind1, p0_ind2]
            E_G2_s_h[p0_shape[p0_ind1], p0_shape[p0_ind2]] =
                E_G2_s_hsub.shape_shape[p0_ind1, p0_ind2]
        end

        # Since the u_u submatrix is not disjoint between different i, accumulate
        # it separate and add it at the end.
        for u_ind1 = 1:2, u_ind2 = 1:2
            E_G_s_hsub.u_u[u_ind1, u_ind2] =
                E_G_s_hsub.shape_shape[u_ind[u_ind1], u_ind[u_ind2]]
            E_G2_s_hsub.u_u[u_ind1, u_ind2] =
                E_G2_s_hsub.shape_shape[u_ind[u_ind1], u_ind[u_ind2]]
        end

        # All other terms are disjoint between different i and don't involve
        # addition, so we can just assign their values (which is efficient in
        # native julia).

        # The (a, bright) blocks:
        for p0_ind in 1:length(p0_bright)
            E_G_s_h[p0_bright[p0_ind], ids.is_star[i]] =
                fsm_i_v * sb_E_l_a_b_i_d[p0_ind, 1]
            E_G2_s_h[p0_bright[p0_ind], ids.is_star[i]] =
                (fsm_i_v ^ 2) * sb_E_ll_a_b_i_d[p0_ind, 1]
            E_G_s_h[ids.is_star[i], p0_bright[p0_ind]] =
                E_G_s_h[p0_bright[p0_ind], ids.is_star[i]]
            E_G2_s_h[ids.is_star[i], p0_bright[p0_ind]] =
                E_G2_s_h[p0_bright[p0_ind], ids.is_star[i]]
        end

        # The (a, shape) blocks.
        for p0_ind in 1:length(p0_shape)
            E_G_s_h[p0_shape[p0_ind], ids.is_star[i]] =
                sb_E_l_a_b_i_v * fsm_i_d[p0_ind, 1]
            E_G2_s_h[p0_shape[p0_ind], ids.is_star[i]] =
                sb_E_ll_a_b_i_v * 2 * fsm_i_v * fsm_i_d[p0_ind, 1]
            E_G_s_h[ids.is_star[i], p0_shape[p0_ind]] =
                E_G_s_h[p0_shape[p0_ind], ids.is_star[i]]
            E_G2_s_h[ids.is_star[i], p0_shape[p0_ind]] =
                E_G2_s_h[p0_shape[p0_ind], ids.is_star[i]]
        end

        for ind_b in 1:length(p0_bright), ind_s in 1:length(p0_shape)
            E_G_s_h[p0_bright[ind_b], p0_shape[ind_s]] =
                a_i * sb_E_l_a_b_i_d[ind_b, 1] * fsm_i_d[ind_s, 1]
            E_G2_s_h[p0_bright[ind_b], p0_shape[ind_s]] =
                2 * a_i * sb_E_ll_a_b_i_d[ind_b, 1] * fsm_i_v * fsm_i_d[ind_s]

            E_G_s_h[p0_shape[ind_s], p0_bright[ind_b]] =
                E_G_s_h[p0_bright[ind_b], p0_shape[ind_s]]
            E_G2_s_h[p0_shape[ind_s], p0_bright[ind_b]] =
                E_G2_s_h[p0_bright[ind_b], p0_shape[ind_s]]
        end
    end # i loop

    if elbo_vars.elbo.has_hessian
        # Accumulate the pos Hessian. pos is the only parameter that is shared between
        # different values of i.

        # This is
        # for i = 1:NUM_SOURCE_TYPES
        #     E_G_u_u_hess += elbo_vars.E_G_s_hsub_vec[i].u_u
        #     E_G2_u_u_hess += elbo_vars.E_G2_s_hsub_vec[i].u_u
        # end
        # For each value in 1:NUM_SOURCE_TYPES, written this way for speed.
        for u_ind1 = 1:2, u_ind2 = 1:2
            elbo_vars.E_G_s.h[ids.pos[u_ind1], ids.pos[u_ind2]] =
                elbo_vars.E_G_s_hsub_vec[1].u_u[u_ind1, u_ind2] +
                elbo_vars.E_G_s_hsub_vec[2].u_u[u_ind1, u_ind2]

            elbo_vars.E_G2_s.h[ids.pos[u_ind1], ids.pos[u_ind2]] =
                elbo_vars.E_G2_s_hsub_vec[1].u_u[u_ind1, u_ind2] +
                elbo_vars.E_G2_s_hsub_vec[2].u_u[u_ind1, u_ind2]
        end
    end

    ####################################################
    #### the code below loads var_G_s ##################

    var_G_s.v[] = E_G2_s.v[] - (E_G_s.v[] ^ 2)

    ############### only gradient and hessian code below
    (is_active_source && elbo_vars.elbo.has_gradient) || return

    var_G_s_d = elbo_vars.var_G_s.d
    E_G2_s_d = elbo_vars.E_G2_s.d
    E_G_s_d = elbo_vars.E_G_s.d

    @assert length(var_G_s_d) == length(E_G2_s_d) == length(E_G_s_d)

    @inbounds for ind1 = 1:length(var_G_s_d)
        var_G_s_d[ind1] = E_G2_s_d[ind1] - 2 * E_G_s.v[] * E_G_s_d[ind1]
    end

    ########## only hessian code below
    elbo_vars.elbo.has_hessian || return

    var_G_s_h = elbo_vars.var_G_s.h
    E_G2_s_h = elbo_vars.E_G2_s.h
    E_G_s_h = elbo_vars.E_G_s.h
    p1, p2 = size(var_G_s_h)
    @inbounds for ind2 = 1:p2, ind1 = 1:ind2
        var_G_s_h[ind1, ind2] =
            E_G2_s_h[ind1, ind2] - 2 * (
                E_G_s.v[] * E_G_s_h[ind1, ind2] +
                E_G_s_d[ind1, 1] * E_G_s_d[ind2, 1])
        var_G_s_h[ind2, ind1] = var_G_s_h[ind1, ind2]
    end
end

"""
Add the contributions from a single source at a single pixel to the
sensitive floast E_G and var_G, which are updated in place.
"""
function accumulate_source_pixel_brightness!(
        ea::ElboArgs,
        vp::VariationalParams{T},
        elbo_vars::ElboIntermediateVariables{T},
        sb::SourceBrightness{T},
        b::Int, s::Int,
        is_active_source::Bool) where {T<:Number}

    calculate_G_s!(vp, elbo_vars, sb, b, s, is_active_source)

    if is_active_source
        sa = findfirst(ea.active_sources, s)
        add_sources_sf!(elbo_vars.E_G, elbo_vars.E_G_s, sa)
        add_sources_sf!(elbo_vars.var_G, elbo_vars.var_G_s, sa)
    else
        # If the sources is inactive, simply accumulate the values.
        elbo_vars.E_G.v[] += elbo_vars.E_G_s.v[]
        elbo_vars.var_G.v[] += elbo_vars.var_G_s.v[]
    end
end

"""
Add the lower bound to the log term to the elbo for a single pixel.

Args:
     - elbo_vars: Intermediate variables
     - x_nbm: The photon count at this pixel
     - iota: The optical sensitivity

 Returns:
    Updates elbo_vars.elbo in place by adding the lower bound to the log
    term.
"""
function add_elbo_log_term!(elbo_vars::ElboIntermediateVariables{T},
                            E_G::SensitiveFloat{T},
                            var_G::SensitiveFloat{T},
                            elbo::SensitiveFloat{T},
                            x_nbm::AbstractFloat,
                            iota::AbstractFloat) where {T<:Number}
    # See notes for a derivation. The log term is
    # log E[G] - Var(G) / (2 * E[G] ^2 )

    @inbounds begin
        E_G_v = E_G.v[]
        var_G_v = var_G.v[]

        # The gradients and Hessians are written as a f(x, y) = f(E_G2, E_G)
        log_term_value = log(E_G_v) - var_G_v / (2.0 * E_G_v ^ 2)

        # Add x_nbm * (log term * log(iota)) to the elbo.
        # If not calculating derivatives, add the values directly.
        elbo.v[] += x_nbm * (log(iota) + log_term_value)

        if elbo_vars.elbo.has_gradient
            elbo_vars.combine_grad[1] = -0.5 / (E_G_v ^ 2)
            elbo_vars.combine_grad[2] = 1 / E_G_v + var_G_v / (E_G_v ^ 3)

            if elbo_vars.elbo.has_hessian
                elbo_vars.combine_hess[1, 1] = 0.0
                elbo_vars.combine_hess[1, 2] = elbo_vars.combine_hess[2, 1] = 1 / E_G_v^3
                elbo_vars.combine_hess[2, 2] =
                    -(1 / E_G_v ^ 2 + 3 * var_G_v / (E_G_v ^ 4))
            end

            # Calculate the log term.
            combine_sfs!(
                var_G, E_G, elbo_vars.elbo_log_term,
                log_term_value, elbo_vars.combine_grad, elbo_vars.combine_hess)

            # Add to the ELBO.
            elbo_d = elbo.d
            elbo_vars_elbo_log_term_d = elbo_vars.elbo_log_term.d

            for ind in 1:length(elbo_d)
                elbo_d[ind] += x_nbm * elbo_vars_elbo_log_term_d[ind]
            end

            if elbo_vars.elbo.has_hessian
                elbo_h = elbo.h
                elbo_vars_elbo_log_term_h = elbo_vars.elbo_log_term.h
                for ind in 1:length(elbo_h)
                    elbo_h[ind] += x_nbm * elbo_vars_elbo_log_term_h[ind]
                end
            end
        end
    end
end

function add_pixel_term!(
        ea::ElboArgs,
        vp::VariationalParams{T},
        n::Int, h::Int, w::Int,
        bvn_bundle::BvnBundle{T},
        sbs::Vector{SourceBrightness{T}},
        elbo_vars::ElboIntermediateVariables = ElboIntermediateVariables(T, ea.Sa)) where {T<:Number}
    img = ea.images[n]

    SensitiveFloats.zero!(elbo_vars.E_G)
    SensitiveFloats.zero!(elbo_vars.var_G)

    for s in 1:ea.S
        p = ea.patches[s,n]

        h2 = h - p.bitmap_offset[1]
        w2 = w - p.bitmap_offset[2]

        H2, W2 = size(p.active_pixel_bitmap)
        if 1 <= h2 <= H2 && 1 <= w2 < W2 && p.active_pixel_bitmap[h2, w2]
            is_active_source = s in ea.active_sources

            # this if/else block is for reporting purposes only
            if is_active_source
                elbo_vars.active_pixel_counter[] += 1
            else
                elbo_vars.inactive_pixel_counter[] += 1
            end

            Model.star_light_density!(elbo_vars.fs0m, p, h, w, vp[s][ids.pos], is_active_source)
            Model.populate_gal_fsm!(elbo_vars.fs1m,
                                    bvn_bundle.bvn_derivs,
                                    s, h, w,
                                    is_active_source,
                                    p.wcs_jacobian,
                                    bvn_bundle.gal_mcs)

            accumulate_source_pixel_brightness!(ea, vp, elbo_vars,
                sbs[s], ea.images[n].b, s, is_active_source)
        end
    end

    # There are no derivatives with respect to epsilon, so can safely add
    # to the value.
    elbo_vars.E_G.v[] += img.sky[h, w]

    # Add the terms to the elbo given the brightness.
    add_elbo_log_term!(elbo_vars,
                       elbo_vars.E_G,
                       elbo_vars.var_G,
                       elbo_vars.elbo,
                       img.pixels[h,w],
                       img.nelec_per_nmgy[h])
    add_scaled_sfs!(elbo_vars.elbo,
                    elbo_vars.E_G,
                    -img.nelec_per_nmgy[h])

    # Subtract the log factorial term. This is not a function of the
    # parameters so the derivatives don't need to be updated. Note that
    # even though this does not affect the ELBO's maximum, it affects
    # the optimization convergence criterion, so I will leave it in for now.
    elbo_vars.elbo.v[] -= lgamma(img.pixels[h,w] + 1.0)
end

"""
Return the expected log likelihood for all bands in a section
of the sky.
Returns: A sensitive float with the log likelihood.
"""
function elbo_likelihood(ea::ElboArgs,
                         vp::VariationalParams{T},
                         elbo_vars::ElboIntermediateVariables = ElboIntermediateVariables(T, ea.Sa),
                         bvn_bundle::BvnBundle{T} = BvnBundle{T}(ea.psf_K, ea.S)) where {T}
    zero!(elbo_vars)
    Model.zero!(bvn_bundle)

    # this call loops over light sources (but not images)
    sbs = load_source_brightnesses(ea, vp)

    for n in 1:ea.N
        img = ea.images[n]

        # could preallocate these---outside of elbo_likehood even to use for
        # all ~50 evalulations of the likelihood
        # This convolves the PSF with the star/galaxy model, returning a
        # mixture of bivariate normals.
        star_mcs, gal_mcs = Model.load_bvn_mixtures!(
                                    bvn_bundle.star_mcs,
                                    bvn_bundle.gal_mcs,
                                    ea.S, ea.patches,
                                    vp, ea.active_sources,
                                    ea.psf_K, n,
                                    elbo_vars.elbo.has_gradient,
                                    elbo_vars.elbo.has_hessian)

        # if there's only one active source, we know each pixel we visit
        # hasn't been visited before, so no need to allocate memory.
        # currently length(ea.active_sources) > 1 only in unit tests, never
        # when invoked from `bin`.
        already_visited = length(ea.active_sources) == 1 ?
                              falses(0, 0) :
                              falses(size(img.pixels))

        # iterate over the pixels by iterating over the patches, and visiting
        # all the pixels in the patch that are active and haven't already been
        # visited
        for s in ea.active_sources
            p = ea.patches[s, n]
            H2, W2 = size(p.active_pixel_bitmap)
            for w2 in 1:W2, h2 in 1:H2
                # (h2, w2) index the local patch, while (h, w) index the image
                h = p.bitmap_offset[1] + h2
                w = p.bitmap_offset[2] + w2

                if !p.active_pixel_bitmap[h2, w2]
                    continue
                end

                # if there's only one source to visit, we know this pixel is new
                if length(ea.active_sources) != 1
                    if already_visited[h,w]
                        continue
                    end
                    already_visited[h,w] = true
                end

                # Some pixels that are NaN in the original image may be active
                # for the convolution code.
                if isnan(img.pixels[h, w])
                    continue
                end

                # if we're here it's a unique active pixel.
                # Note that although we are iterating over pixels within a
                # single patch, add_pixel_term /also/ iterates over patches to
                # find all patches that overlap with this pixel.
                add_pixel_term!(ea, vp, n, h, w, bvn_bundle, sbs, elbo_vars)
            end
        end
    end

    assert_all_finite(elbo_vars.elbo)
    elbo_vars.elbo
end

"""
Calculates and returns the ELBO and its derivatives for all the bands
of an image.
Returns: A sensitive float containing the ELBO for the image.
"""
function elbo(ea::ElboArgs,
              vp::VariationalParams{T},
              elbo_vars::ElboIntermediateVariables =
                  ElboIntermediateVariables(T, ea.Sa, true,  T<:AbstractFloat),
              bvn_bundle::BvnBundle = BvnBundle{T}(ea.psf_K, ea.S)) where {T}
    @assert(all(all(isfinite, vs) for vs in vp), "vp contains NaNs or Infs")
    result = elbo_likelihood(ea, vp, elbo_vars, bvn_bundle)
    ea.include_kl && KLDivergence.subtract_kl_all_sources!(ea, vp, result)
    assert_all_finite(elbo_vars.elbo)
    return result
end


module ComradeBase

using DocStringExtensions
using ChainRulesCore
using FLoops
using StaticArrays
using StructArrays

export  visibility, intensitymap, intensitymap!,
        StokesVector, CoherencyMatrix, evpa, m̆, SingleStokes,
        flux, fov, imagepixels, pixelsizes, IntensityMap

include("interface.jl")
include("images/images.jl")
#include("threaded.jl")

#include("polarized.jl")

end


mutable struct hydro_vars
    U1D::Array{Float64,2}
    U1D_p::Array{Float64,2}
    U1D_c::Array{Float64,2}
    F1D::Array{Float64,2}
    G1D::Array{Float64,2}
    R1D::Array{Float64,2}
    C1D::Array{Float64,2}
    rho::Array{Float64,2}
    u::Array{Float64,2}
    T::Array{Float64,2}
    p::Array{Float64,2}
    Efield::Array{Float64,1}
    ni::Array{Float64,2}
    ne::Array{Float64,1}

    function hydro_vars(nz::Int64, nspec::Int64, neqi::Int64)
        U1D = zeros(Float64, nz, neqi+1)
        U1D_p = zeros(Float64, nz, neqi+1)
        U1D_c = zeros(Float64, nz, neqi+1)
        F1D = zeros(Float64, nz, neqi+1)
        G1D = zeros(Float64, nz, neqi+1)
        R1D = zeros(Float64, nz, neqi + 1)
        C1D = zeros(Float64, nz, neqi)
        p = zeros(Float64, nz, nspec+1)
        u = zeros(Float64, nz, nspec+1)
        rho = zeros(Float64, nz, nspec+1)
        T = zeros(Float64, nz, nspec+1)
        Efield = zeros(Float64, nz)
        ni = zeros(Float64, nz, nspec)
        ne = zeros(Float64, nz)

        new(
            U1D,
            U1D_p,
            U1D_c,
            F1D,
            G1D,
            R1D,
            C1D,
            p,
            u,
            rho,
            T,
            Efield,
            ni,
            ne
        )
    end
end


module Topologies
import ..BrickMesh
import MPI
using DocStringExtensions

export AbstractTopology,
    BrickTopology,
    StackedBrickTopology,
    CubedShellTopology,
    StackedCubedSphereTopology,
    isstacked,
    cubedshellwarp,
    cubedshellunwarp

export grid1d, SingleExponentialStretching, InteriorStretching

"""
    AbstractTopology{dim}

Represents the connectivity of individual elements, with local dimension `dim`.
"""
abstract type AbstractTopology{dim} end

"""
    BoxElementTopology{dim, T} <: AbstractTopology{dim}

The local topology of a larger MPI-distributed topology, represented by
`dim`-dimensional box elements.

This contains the necessary information for the connectivity elements of the
elements on the local process, along with "ghost" elements from neighbouring
processes.

# Fields

$(DocStringExtensions.FIELDS)
"""
struct BoxElementTopology{dim, T} <: AbstractTopology{dim}

    """
    MPI communicator for communicating with neighbouring processes.
    """
    mpicomm::MPI.Comm

    """
    Range of element indices
    """
    elems::UnitRange{Int64}

    """
    Range of real (aka nonghost) element indices
    """
    realelems::UnitRange{Int64}

    """
    Range of ghost element indices
    """
    ghostelems::UnitRange{Int64}

    """
    Ghost element to face is received; `ghostfaces[f,ge] == true` if face `f` of
    ghost element `ge` is received.
    """
    ghostfaces::BitArray{2}

    """
    Array of send element indices
    """
    sendelems::Array{Int64, 1}

    """
    Send element to face is sent; `sendfaces[f,se] == true` if face `f` of send
    element `se` is sent.
    """
    sendfaces::BitArray{2}

    """
    Array of real elements that do not have a ghost element as a neighbor.
    """
    interiorelems::Array{Int64, 1}

    """
    Array of real elements that have at least on ghost element as a neighbor.

    Note that this is different from `sendelems` because `sendelems` duplicates
    elements that need to be sent to multiple neighboring processes.
    """
    exteriorelems::Array{Int64, 1}

    """
    Element to vertex coordinates; `elemtocoord[d,i,e]` is the `d`th coordinate
    of corner `i` of element `e`

    !!! note
        currently coordinates always are of size 3 for `(x1, x2, x3)`
    """
    elemtocoord::Array{T, 3}

    """
    Element to neighboring element; `elemtoelem[f,e]` is the number of the
    element neighboring element `e` across face `f`.  If there is no neighboring
    element then `elemtoelem[f,e] == e`.
    """
    elemtoelem::Array{Int64, 2}

    """
    Element to neighboring element face; `elemtoface[f,e]` is the face number of
    the element neighboring element `e` across face `f`.  If there is no
    neighboring element then `elemtoface[f,e] == f`."
    """
    elemtoface::Array{Int64, 2}

    """
    element to neighboring element order; `elemtoordr[f,e]` is the ordering
    number of the element neighboring element `e` across face `f`.  If there is
    no neighboring element then `elemtoordr[f,e] == 1`.
    """
    elemtoordr::Array{Int64, 2}

    """
    Element to boundary number; `elemtobndy[f,e]` is the boundary number of face
    `f` of element `e`.  If there is a neighboring element then `elemtobndy[f,e]
    == 0`.
    """
    elemtobndy::Array{Int64, 2}

    """
    List of the MPI ranks for the neighboring processes
    """
    nabrtorank::Array{Int64, 1}

    """
    Range in ghost elements to receive for each neighbor
    """
    nabrtorecv::Array{UnitRange{Int64}, 1}

    """
    Range in `sendelems` to send for each neighbor
    """
    nabrtosend::Array{UnitRange{Int64}, 1}

    """
    original order in partitioning
    """
    origsendorder::Array{Int64, 1}

    """
    boolean for whether or not this topology has a boundary
    """
    hasboundary::Bool

    function BoxElementTopology{dim, T}(
        mpicomm,
        elems,
        realelems,
        ghostelems,
        ghostfaces,
        sendelems,
        sendfaces,
        elemtocoord,
        elemtoelem,
        elemtoface,
        elemtoordr,
        elemtobndy,
        nabrtorank,
        nabrtorecv,
        nabrtosend,
        origsendorder,
        hasboundary,
    ) where {dim, T}

        exteriorelems = sort(unique(sendelems))
        interiorelems = sort(setdiff(realelems, exteriorelems))

        return new{dim, T}(
            mpicomm,
            elems,
            realelems,
            ghostelems,
            ghostfaces,
            sendelems,
            sendfaces,
            interiorelems,
            exteriorelems,
            elemtocoord,
            elemtoelem,
            elemtoface,
            elemtoordr,
            elemtobndy,
            nabrtorank,
            nabrtorecv,
            nabrtosend,
            origsendorder,
            hasboundary,
        )
    end
end

"""
    hasboundary(topology::AbstractTopology)

query function to check whether a topology has a boundary (i.e., not fully
periodic)
"""
hasboundary(topology::AbstractTopology) = topology.hasboundary

if VERSION >= v"1.2-"
    isstacked(::T) where {T <: AbstractTopology} = hasfield(T, :stacksize)
else
    isstacked(::T) where {T <: AbstractTopology} =
        Base.fieldindex(T, :stacksize, false) > 0
end

"""
    BrickTopology{dim, T} <: AbstractTopology{dim}

A simple grid-based topology. This is a convenience wrapper around
[`BoxElementTopology`](@ref).
"""
struct BrickTopology{dim, T} <: AbstractTopology{dim}
    topology::BoxElementTopology{dim, T}
end
Base.getproperty(a::BrickTopology, p::Symbol) =
    getproperty(getfield(a, :topology), p)

"""
    CubedShellTopology{T} <: AbstractTopology{2}

A cube-shell topology. This is a convenience wrapper around
[`BoxElementTopology`](@ref).
"""
struct CubedShellTopology{T} <: AbstractTopology{2}
    topology::BoxElementTopology{2, T}
end
Base.getproperty(a::CubedShellTopology, p::Symbol) =
    getproperty(getfield(a, :topology), p)

"""
    StackedBrickTopology{dim, T} <: AbstractTopology{dim}

A simple grid-based topology, where all elements on the trailing dimension are
stacked to be contiguous. This is a convenience wrapper around
[`BoxElementTopology`](@ref).
"""
struct StackedBrickTopology{dim, T} <: AbstractTopology{dim}
    topology::BoxElementTopology{dim, T}
    stacksize::Int64
end
function Base.getproperty(a::StackedBrickTopology, p::Symbol)
    return p == :stacksize ? getfield(a, p) :
           getproperty(getfield(a, :topology), p)
end

"""
    StackedCubedSphereTopology{3, T} <: AbstractTopology{3}

A cube-sphere topology. All elements on the same "vertical" dimension are
stacked to be contiguous. This is a convenience wrapper around
[`BoxElementTopology`](@ref).
"""
struct StackedCubedSphereTopology{T} <: AbstractTopology{3}
    topology::BoxElementTopology{3, T}
    stacksize::Int64
end
function Base.getproperty(a::StackedCubedSphereTopology, p::Symbol)
    return p == :stacksize ? getfield(a, p) :
           getproperty(getfield(a, :topology), p)
end

""" A wrapper for the BrickTopology """
BrickTopology(mpicomm, Nelems::NTuple{N, Integer}; kw...) where {N} =
    BrickTopology(mpicomm, map(Ne -> 0:Ne, Nelems); kw...)

"""
    BrickTopology{dim, T}(mpicomm, elemrange; boundary, periodicity)

Generate a brick mesh topology with coordinates given by the tuple `elemrange`
and the periodic dimensions given by the `periodicity` tuple.

The elements of the brick are partitioned equally across the MPI ranks based
on a space-filling curve.

By default boundary faces will be marked with a one and other faces with a
zero.  Specific boundary numbers can also be passed for each face of the brick
in `boundary`.  This will mark the nonperiodic brick faces with the given
boundary number.

# Examples

We can build a 3 by 2 element two-dimensional mesh that is periodic in the
\$x2\$-direction with
```jldoctest brickmesh

using CLIMA.Topologies
using MPI
MPI.Init()
topology = BrickTopology(MPI.COMM_SELF, (2:5,4:6);
                         periodicity=(false,true),
                         boundary=((1,2),(3,4)))
```
This returns the mesh structure for

             x2

              ^
              |
             6-  +-----+-----+-----+
              |  |     |     |     |
              |  |  3  |  4  |  5  |
              |  |     |     |     |
             5-  +-----+-----+-----+
              |  |     |     |     |
              |  |  1  |  2  |  6  |
              |  |     |     |     |
             4-  +-----+-----+-----+
              |
              +--|-----|-----|-----|--> x1
                 2     3     4     5

For example, the (dimension by number of corners by number of elements) array
`elemtocoord` gives the coordinates of the corners of each element.
```jldoctest brickmesh
julia> topology.elemtocoord
2×4×6 Array{Int64,3}:
[:, :, 1] =
 2  3  2  3
 4  4  5  5

[:, :, 2] =
 3  4  3  4
 4  4  5  5

[:, :, 3] =
 2  3  2  3
 5  5  6  6

[:, :, 4] =
 3  4  3  4
 5  5  6  6

[:, :, 5] =
 4  5  4  5
 5  5  6  6

[:, :, 6] =
 4  5  4  5
 4  4  5  5
```
Note that the corners are listed in Cartesian order.

The (number of faces by number of elements) array `elemtobndy` gives the
boundary number for each face of each element.  A zero will be given for
connected faces.
```jldoctest brickmesh
julia> topology.elemtobndy
4×6 Array{Int64,2}:
 1  0  1  0  0  0
 0  0  0  0  2  2
 0  0  0  0  0  0
 0  0  0  0  0  0
```
Note that the faces are listed in Cartesian order.

"""
function BrickTopology(
    mpicomm,
    elemrange;
    boundary = ntuple(j -> (1, 1), length(elemrange)),
    periodicity = ntuple(j -> false, length(elemrange)),
    connectivity = :face,
    ghostsize = 1,
)

    if boundary isa Matrix
        boundary = tuple(mapslices(x -> tuple(x...), boundary, dims = 1)...)
    end

    # We cannot handle anything else right now...
    @assert connectivity == :face
    @assert ghostsize == 1

    mpirank = MPI.Comm_rank(mpicomm)
    mpisize = MPI.Comm_size(mpicomm)
    topology = BrickMesh.brickmesh(
        elemrange,
        periodicity,
        part = mpirank + 1,
        numparts = mpisize,
        boundary = boundary,
    )
    topology = BrickMesh.partition(mpicomm, topology...)
    origsendorder = topology[5]
    topology = BrickMesh.connectmesh(mpicomm, topology[1:4]...)

    dim = length(elemrange)
    T = eltype(topology.elemtocoord)
    return BrickTopology{dim, T}(BoxElementTopology{dim, T}(
        mpicomm,
        topology.elems,
        topology.realelems,
        topology.ghostelems,
        topology.ghostfaces,
        topology.sendelems,
        topology.sendfaces,
        topology.elemtocoord,
        topology.elemtoelem,
        topology.elemtoface,
        topology.elemtoordr,
        topology.elemtobndy,
        topology.nabrtorank,
        topology.nabrtorecv,
        topology.nabrtosend,
        origsendorder,
        !minimum(periodicity),
    ))
end

""" A wrapper for the StackedBrickTopology """
StackedBrickTopology(mpicomm, Nelems::NTuple{N, Integer}; kw...) where {N} =
    StackedBrickTopology(mpicomm, map(Ne -> 0:Ne, Nelems); kw...)

"""
    StackedBrickTopology{dim, T}(mpicomm, elemrange; boundary, periodicity)

Generate a stacked brick mesh topology with coordinates given by the tuple
`elemrange` and the periodic dimensions given by the `periodicity` tuple.

The elements are stacked such that the elements associated with range
`elemrange[dim]` are contiguous in the element ordering.

The elements of the brick are partitioned equally across the MPI ranks based
on a space-filling curve.  Further, stacks are not split at MPI boundaries.

By default boundary faces will be marked with a one and other faces with a
zero.  Specific boundary numbers can also be passed for each face of the brick
in `boundary`.  This will mark the nonperiodic brick faces with the given
boundary number.

# Examples

We can build a 3 by 2 element two-dimensional mesh that is periodic in the
\$x2\$-direction with
```jldoctest brickmesh

using CLIMA.Topologies
using MPI
MPI.Init()
topology = StackedBrickTopology(MPI.COMM_SELF, (2:5,4:6);
                                periodicity=(false,true),
                                boundary=((1,2),(3,4)))
```
This returns the mesh structure stacked in the \$x2\$-direction for

             x2

              ^
              |
             6-  +-----+-----+-----+
              |  |     |     |     |
              |  |  2  |  4  |  6  |
              |  |     |     |     |
             5-  +-----+-----+-----+
              |  |     |     |     |
              |  |  1  |  3  |  5  |
              |  |     |     |     |
             4-  +-----+-----+-----+
              |
              +--|-----|-----|-----|--> x1
                 2     3     4     5

For example, the (dimension by number of corners by number of elements) array
`elemtocoord` gives the coordinates of the corners of each element.
```jldoctest brickmesh
julia> topology.elemtocoord
2×4×6 Array{Int64,3}:
[:, :, 1] =
 2  3  2  3
 4  4  5  5

[:, :, 2] =
 2  3  2  3
 5  5  6  6

[:, :, 3] =
 3  4  3  4
 4  4  5  5

[:, :, 4] =
 3  4  3  4
 5  5  6  6

[:, :, 5] =
 4  5  4  5
 4  4  5  5

[:, :, 6] =
 4  5  4  5
 5  5  6  6
```
Note that the corners are listed in Cartesian order.

The (number of faces by number of elements) array `elemtobndy` gives the
boundary number for each face of each element.  A zero will be given for
connected faces.
```jldoctest brickmesh
julia> topology.elemtobndy
4×6 Array{Int64,2}:
 1  0  1  0  0  0
 0  0  0  0  2  2
 0  0  0  0  0  0
 0  0  0  0  0  0
```
Note that the faces are listed in Cartesian order.
"""
function StackedBrickTopology(
    mpicomm,
    elemrange;
    boundary = ntuple(j -> (1, 1), length(elemrange)),
    periodicity = ntuple(j -> false, length(elemrange)),
    connectivity = :face,
    ghostsize = 1,
)

    if boundary isa Matrix
        boundary = tuple(mapslices(x -> tuple(x...), boundary, dims = 1)...)
    end

    dim = length(elemrange)

    dim <= 1 && error("Stacked brick topology works for 2D and 3D")

    # Build the base topology
    basetopo = BrickTopology(
        mpicomm,
        elemrange[1:(dim - 1)];
        boundary = boundary[1:(dim - 1)],
        periodicity = periodicity[1:(dim - 1)],
        connectivity = connectivity,
        ghostsize = ghostsize,
    )

    # Use the base topology to build the stacked topology
    stack = elemrange[dim]
    stacksize = length(stack) - 1

    nvert = 2^dim
    nface = 2dim

    nreal = length(basetopo.realelems) * stacksize
    nghost = length(basetopo.ghostelems) * stacksize

    elems = 1:(nreal + nghost)
    realelems = 1:nreal
    ghostelems = nreal .+ (1:nghost)

    sendelems =
        similar(basetopo.sendelems, length(basetopo.sendelems) * stacksize)
    for i in 1:length(basetopo.sendelems), j in 1:stacksize
        sendelems[stacksize * (i - 1) + j] =
            stacksize * (basetopo.sendelems[i] - 1) + j
    end

    ghostfaces = similar(basetopo.ghostfaces, nface, length(ghostelems))
    ghostfaces .= false

    for i in 1:length(basetopo.ghostelems), j in 1:stacksize
        e = stacksize * (i - 1) + j
        for f in 1:(2 * (dim - 1))
            ghostfaces[f, e] = basetopo.ghostfaces[f, i]
        end
    end

    sendfaces = similar(basetopo.sendfaces, nface, length(sendelems))
    sendfaces .= false

    for i in 1:length(basetopo.sendelems), j in 1:stacksize
        e = stacksize * (i - 1) + j
        for f in 1:(2 * (dim - 1))
            sendfaces[f, e] = basetopo.sendfaces[f, i]
        end
    end

    elemtocoord = similar(basetopo.elemtocoord, dim, nvert, length(elems))

    for i in 1:length(basetopo.elems), j in 1:stacksize
        e = stacksize * (i - 1) + j

        for v in 1:(2^(dim - 1))
            for d in 1:(dim - 1)
                elemtocoord[d, v, e] = basetopo.elemtocoord[d, v, i]
                elemtocoord[d, 2^(dim - 1) + v, e] =
                    basetopo.elemtocoord[d, v, i]
            end

            elemtocoord[dim, v, e] = stack[j]
            elemtocoord[dim, 2^(dim - 1) + v, e] = stack[j + 1]
        end
    end

    elemtoelem = similar(basetopo.elemtoelem, nface, length(elems))
    elemtoface = similar(basetopo.elemtoface, nface, length(elems))
    elemtoordr = similar(basetopo.elemtoordr, nface, length(elems))
    elemtobndy = similar(basetopo.elemtobndy, nface, length(elems))

    for e in 1:(length(basetopo.elems) * stacksize), f in 1:nface
        elemtoelem[f, e] = e
        elemtoface[f, e] = f
        elemtoordr[f, e] = 1
        elemtobndy[f, e] = 0
    end

    for i in 1:length(basetopo.realelems), j in 1:stacksize
        e1 = stacksize * (i - 1) + j

        for f in 1:(2 * (dim - 1))
            e2 = stacksize * (basetopo.elemtoelem[f, i] - 1) + j

            elemtoelem[f, e1] = e2
            elemtoface[f, e1] = basetopo.elemtoface[f, i]

            # We assume a simple orientation right now
            @assert basetopo.elemtoordr[f, i] == 1
            elemtoordr[f, e1] = basetopo.elemtoordr[f, i]
        end

        et = stacksize * (i - 1) + j + 1
        eb = stacksize * (i - 1) + j - 1
        ft = 2 * (dim - 1) + 1
        fb = 2 * (dim - 1) + 2
        ot = 1
        ob = 1

        if j == stacksize
            et = periodicity[dim] ? stacksize * (i - 1) + 1 : e1
            ft = periodicity[dim] ? ft : 2 * (dim - 1) + 2
        end
        if j == 1
            eb = periodicity[dim] ? stacksize * (i - 1) + stacksize : e1
            fb = periodicity[dim] ? fb : 2 * (dim - 1) + 1
        end

        elemtoelem[2 * (dim - 1) + 1, e1] = eb
        elemtoelem[2 * (dim - 1) + 2, e1] = et
        elemtoface[2 * (dim - 1) + 1, e1] = fb
        elemtoface[2 * (dim - 1) + 2, e1] = ft
        elemtoordr[2 * (dim - 1) + 1, e1] = ob
        elemtoordr[2 * (dim - 1) + 2, e1] = ot
    end

    for i in 1:length(basetopo.elems), j in 1:stacksize
        e1 = stacksize * (i - 1) + j

        for f in 1:(2 * (dim - 1))
            elemtobndy[f, e1] = basetopo.elemtobndy[f, i]
        end

        bt = bb = 0

        if j == stacksize
            bt = periodicity[dim] ? bt : boundary[dim][2]
        end
        if j == 1
            bb = periodicity[dim] ? bb : boundary[dim][1]
        end

        elemtobndy[2 * (dim - 1) + 1, e1] = bb
        elemtobndy[2 * (dim - 1) + 2, e1] = bt
    end

    nabrtorank = basetopo.nabrtorank
    nabrtorecv = UnitRange{Int}[
        UnitRange(
            stacksize * (first(basetopo.nabrtorecv[n]) - 1) + 1,
            stacksize * last(basetopo.nabrtorecv[n]),
        ) for n in 1:length(nabrtorank)
    ]
    nabrtosend = UnitRange{Int}[
        UnitRange(
            stacksize * (first(basetopo.nabrtosend[n]) - 1) + 1,
            stacksize * last(basetopo.nabrtosend[n]),
        ) for n in 1:length(nabrtorank)
    ]

    T = eltype(basetopo.elemtocoord)

    StackedBrickTopology{dim, T}(
        BoxElementTopology{dim, T}(
            mpicomm,
            elems,
            realelems,
            ghostelems,
            ghostfaces,
            sendelems,
            sendfaces,
            elemtocoord,
            elemtoelem,
            elemtoface,
            elemtoordr,
            elemtobndy,
            nabrtorank,
            nabrtorecv,
            nabrtosend,
            basetopo.origsendorder,
            !minimum(periodicity),
        ),
        stacksize,
    )
end

"""
    CubedShellTopology(mpicomm, Nelem, T) <: AbstractTopology{dim}

Generate a cubed shell mesh with the number of elements along each dimension of
the cubes being `Nelem`. This topology actual creates a cube mesh, and the
warping should be done after the grid is created using the `cubedshellwarp`
function. The coordinates of the points will be of type `T`.

The elements of the shell are partitioned equally across the MPI ranks based
on a space-filling curve.

Note that this topology is logically 2-D but embedded in a 3-D space

# Examples

We can build a cubed shell mesh with 10 elements on each cube, total elements is
`10 * 10 * 6 = 600`, with
```jldoctest brickmesh
using CLIMA.Topologies
using MPI
MPI.Init()
topology = CubedShellTopology(MPI.COMM_SELF, 10, Float64)

# Typically the warping would be done after the grid is created, but the cell
# corners could be warped with...

# Shell radius = 1
x1, x2, x3 = ntuple(j->topology.elemtocoord[j, :, :], 3)
for n = 1:length(x1)
   x1[n], x2[n], x3[n] = Topologies.cubedshellwarp(x1[n], x2[n], x3[n])
end

# Shell radius = 10
x1, x2, x3 = ntuple(j->topology.elemtocoord[j, :, :], 3)
for n = 1:length(x1)
  x1[n], x2[n], x3[n] = Topologies.cubedshellwarp(x1[n], x2[n], x3[n], 10)
end
```
"""
function CubedShellTopology(
    mpicomm,
    Neside,
    T;
    connectivity = :face,
    ghostsize = 1,
)

    # We cannot handle anything else right now...
    @assert connectivity == :face
    @assert ghostsize == 1

    mpirank = MPI.Comm_rank(mpicomm)
    mpisize = MPI.Comm_size(mpicomm)

    topology = cubedshellmesh(Neside, part = mpirank + 1, numparts = mpisize)

    topology = BrickMesh.partition(mpicomm, topology...)
    origsendorder = topology[5]
    dim, nvert = 3, 4
    elemtovert = topology[1]
    nelem = size(elemtovert, 2)
    elemtocoord = Array{T}(undef, dim, nvert, nelem)
    ind2vert = CartesianIndices((Neside + 1, Neside + 1, Neside + 1))
    for e in 1:nelem
        for n in 1:nvert
            v = elemtovert[n, e]
            i, j, k = Tuple(ind2vert[v])
            elemtocoord[:, n, e] =
                (2 * [i - 1, j - 1, k - 1] .- Neside) / Neside
        end
    end

    topology = BrickMesh.connectmesh(
        mpicomm,
        topology[1],
        elemtocoord,
        topology[3],
        topology[4];
        dim = 2,
    )

    CubedShellTopology{T}(BoxElementTopology{2, T}(
        mpicomm,
        topology.elems,
        topology.realelems,
        topology.ghostelems,
        topology.ghostfaces,
        topology.sendelems,
        topology.sendfaces,
        topology.elemtocoord,
        topology.elemtoelem,
        topology.elemtoface,
        topology.elemtoordr,
        topology.elemtobndy,
        topology.nabrtorank,
        topology.nabrtorecv,
        topology.nabrtosend,
        origsendorder,
        false,
    ))
end

"""
    cubedshellmesh(T, Ne; part=1, numparts=1)

Generate a cubed mesh with each of the "cubes" has an `Ne X Ne` grid of
elements.

The mesh can optionally be partitioned into `numparts` and this returns
partition `part`.  This is a simple Cartesian partition and further partitioning
(e.g, based on a space-filling curve) should be done before the mesh is used for
computation.

This mesh returns the cubed spehere in a flatten fashion for the vertex values,
and a remapping is needed to embed the mesh in a 3-D space.

The mesh structures for the cubes is as follows:

```
x2
   ^
   |
4Ne-           +-------+
   |           |       |
   |           |   6   |
   |           |       |
3Ne-           +-------+
   |           |       |
   |           |   5   |
   |           |       |
2Ne-           +-------+
   |           |       |
   |           |   4   |
   |           |       |
 Ne-   +-------+-------+-------+
   |   |       |       |       |
   |   |   1   |   2   |   3   |
   |   |       |       |       |
  0-   +-------+-------+-------+
   |
   +---|-------|-------|------|-> x1
       0      Ne      2Ne    3Ne
```

"""
function cubedshellmesh(Ne; part = 1, numparts = 1)
    dim = 2
    @assert 1 <= part <= numparts

    globalnelems = 6 * Ne^2

    # How many vertices and faces per element
    nvert = 2^dim # 4
    nface = 2dim  # 4

    # linearly partition to figure out which elements we own
    elemlocal = BrickMesh.linearpartition(prod(globalnelems), part, numparts)

    # elemen to vertex maps which we own
    elemtovert = Array{Int}(undef, nvert, length(elemlocal))
    elemtocoord = Array{Int}(undef, dim, nvert, length(elemlocal))

    nelemcube = Ne^dim # Ne^2

    etoijb = CartesianIndices((Ne, Ne, 6))
    bx = [0 Ne 2Ne Ne Ne Ne]
    by = [0 0 0 Ne 2Ne 3Ne]

    vertmap = LinearIndices((Ne + 1, Ne + 1, Ne + 1))
    for (le, e) in enumerate(elemlocal)
        i, j, blck = Tuple(etoijb[e])
        elemtocoord[1, :, le] = bx[blck] .+ [i - 1 i i - 1 i]
        elemtocoord[2, :, le] = by[blck] .+ [j - 1 j - 1 j j]

        for n in 1:4
            ix = i + mod(n - 1, 2)
            jx = j + div(n - 1, 2)
            # set the vertices like they are the face vertices of a cube
            if blck == 1
                elemtovert[n, le] = vertmap[1, Ne + 2 - ix, jx]
            elseif blck == 2
                elemtovert[n, le] = vertmap[ix, 1, jx]
            elseif blck == 3
                elemtovert[n, le] = vertmap[Ne + 1, ix, jx]
            elseif blck == 4
                elemtovert[n, le] = vertmap[ix, jx, Ne + 1]
            elseif blck == 5
                elemtovert[n, le] = vertmap[ix, Ne + 1, Ne + 2 - jx]
            elseif blck == 6
                elemtovert[n, le] = vertmap[ix, Ne + 2 - jx, 1]
            end
        end
    end

    # no boundaries for a shell
    elemtobndy = zeros(Int, nface, length(elemlocal))

    # no faceconnections for a shell
    faceconnections = Array{Array{Int, 1}}(undef, 0)

    (elemtovert, elemtocoord, elemtobndy, faceconnections, collect(elemlocal))
end

"""
    cubedshellwarp(a, b, c, R = max(abs(a), abs(b), abs(c)))

Given points `(a, b, c)` on the surface of a cube, warp the points out to a
spherical shell of radius `R` based on the equiangular gnomonic grid proposed by
Ronchi, Iacono, Paolucci (1996) <https://doi.org/10.1006/jcph.1996.0047>

```
@article{RonchiIaconoPaolucci1996,
  title={The ``cubed sphere'': a new method for the solution of partial
         differential equations in spherical geometry},
  author={Ronchi, C. and Iacono, R. and Paolucci, P. S.},
  journal={Journal of Computational Physics},
  volume={124},
  number={1},
  pages={93--114},
  year={1996},
  doi={10.1006/jcph.1996.0047}
}
```

"""
function cubedshellwarp(a, b, c, R = max(abs(a), abs(b), abs(c)))

    function f(sR, ξ, η)
        X, Y = tan(π * ξ / 4), tan(π * η / 4)
        x1 = sR / sqrt(X^2 + Y^2 + 1)
        x2, x3 = X * x1, Y * x1
        x1, x2, x3
    end

    fdim = argmax(abs.((a, b, c)))
    if fdim == 1 && a < 0
        # (-R, *, *) : Face I from Ronchi, Iacono, Paolucci (1996)
        x1, x2, x3 = f(-R, b / a, c / a)
    elseif fdim == 2 && b < 0
        # ( *,-R, *) : Face II from Ronchi, Iacono, Paolucci (1996)
        x2, x1, x3 = f(-R, a / b, c / b)
    elseif fdim == 1 && a > 0
        # ( R, *, *) : Face III from Ronchi, Iacono, Paolucci (1996)
        x1, x2, x3 = f(R, b / a, c / a)
    elseif fdim == 2 && b > 0
        # ( *, R, *) : Face IV from Ronchi, Iacono, Paolucci (1996)
        x2, x1, x3 = f(R, a / b, c / b)
    elseif fdim == 3 && c > 0
        # ( *, *, R) : Face V from Ronchi, Iacono, Paolucci (1996)
        x3, x2, x1 = f(R, b / c, a / c)
    elseif fdim == 3 && c < 0
        # ( *, *,-R) : Face VI from Ronchi, Iacono, Paolucci (1996)
        x3, x2, x1 = f(-R, b / c, a / c)
    else
        error("invalid case for cubedshellwarp: $a, $b, $c")
    end

    return x1, x2, x3
end

"""
    cubedshellunwarp(x1, x2, x3)

The inverse of [`cubedshellwarp`](@ref).
"""
function cubedshellunwarp(x1, x2, x3)

    function g(R, X, Y)
        ξ = atan(X) * 4 / pi
        η = atan(Y) * 4 / pi
        R, R * ξ, R * η
    end

    R = hypot(x1, x2, x3)
    fdim = argmax(abs.((x1, x2, x3)))

    if fdim == 1 && x1 < 0
        # (-R, *, *) : Face I from Ronchi, Iacono, Paolucci (1996)
        a, b, c = g(-R, x2 / x1, x3 / x1)
    elseif fdim == 2 && x2 < 0
        # ( *,-R, *) : Face II from Ronchi, Iacono, Paolucci (1996)
        b, a, c = g(-R, x1 / x2, x3 / x2)
    elseif fdim == 1 && x1 > 0
        # ( R, *, *) : Face III from Ronchi, Iacono, Paolucci (1996)
        a, b, c = g(R, x2 / x1, x3 / x1)
    elseif fdim == 2 && x2 > 0
        # ( *, R, *) : Face IV from Ronchi, Iacono, Paolucci (1996)
        b, a, c = g(R, x1 / x2, x3 / x2)
    elseif fdim == 3 && x3 > 0
        # ( *, *, R) : Face V from Ronchi, Iacono, Paolucci (1996)
        c, b, a = g(R, x2 / x3, x1 / x3)
    elseif fdim == 3 && x3 < 0
        # ( *, *,-R) : Face VI from Ronchi, Iacono, Paolucci (1996)
        c, b, a = g(-R, x2 / x3, x1 / x3)
    else
        error("invalid case for cubedshellunwarp: $a, $b, $c")
    end

    return a, b, c
end

"""
   StackedCubedSphereTopology(mpicomm, Nhorz, Rrange;
                              boundary=(1,1)) <: AbstractTopology{3}

Generate a stacked cubed sphere topology with `Nhorz` by `Nhorz` cells for each
horizontal face and `Rrange` is the radius edges of the stacked elements.  This
topology actual creates a cube mesh, and the warping should be done after the
grid is created using the `cubedshellwarp` function. The coordinates of the
points will be of type `eltype(Rrange)`. The inner boundary condition type is
`boundary[1]` and the outer boundary condition type is `boundary[2]`.

The elements are stacked such that the vertical elements are contiguous in the
element ordering.

The elements of the brick are partitioned equally across the MPI ranks based
on a space-filling curve. Further, stacks are not split at MPI boundaries.

# Examples

We can build a cubed sphere mesh with 10 x 10 x 5 elements on each cube, total
elements is `10 * 10 * 5 * 6 = 3000`, with
```jldoctest brickmesh
using CLIMA.Topologies
using MPI
MPI.Init()
Nhorz = 10
Nstack = 5
Rrange = Float64.(accumulate(+,1:Nstack+1))
topology = StackedCubedSphereTopology(MPI.COMM_SELF, Nhorz, Rrange)

x1, x2, x3 = ntuple(j->reshape(topology.elemtocoord[j, :, :],
                            2, 2, 2, length(topology.elems)), 3)
for n = 1:length(x1)
   x1[n], x2[n], x3[n] = Topologies.cubedshellwarp(x1[n], x2[n], x3[n])
end
```
Note that the faces are listed in Cartesian order.
"""
function StackedCubedSphereTopology(
    mpicomm,
    Nhorz,
    Rrange;
    boundary = (1, 1),
    connectivity = :face,
    ghostsize = 1,
)
    T = eltype(Rrange)

    basetopo = CubedShellTopology(
        mpicomm,
        Nhorz,
        T;
        connectivity = connectivity,
        ghostsize = ghostsize,
    )

    dim = 3
    nvert = 2^dim
    nface = 2dim
    stacksize = length(Rrange) - 1

    nreal = length(basetopo.realelems) * stacksize
    nghost = length(basetopo.ghostelems) * stacksize

    elems = 1:(nreal + nghost)
    realelems = 1:nreal
    ghostelems = nreal .+ (1:nghost)

    sendelems =
        similar(basetopo.sendelems, length(basetopo.sendelems) * stacksize)

    for i in 1:length(basetopo.sendelems), j in 1:stacksize
        sendelems[stacksize * (i - 1) + j] =
            stacksize * (basetopo.sendelems[i] - 1) + j
    end

    ghostfaces = similar(basetopo.ghostfaces, nface, length(ghostelems))
    ghostfaces .= false

    for i in 1:length(basetopo.ghostelems), j in 1:stacksize
        e = stacksize * (i - 1) + j
        for f in 1:(2 * (dim - 1))
            ghostfaces[f, e] = basetopo.ghostfaces[f, i]
        end
    end

    sendfaces = similar(basetopo.sendfaces, nface, length(sendelems))
    sendfaces .= false

    for i in 1:length(basetopo.sendelems), j in 1:stacksize
        e = stacksize * (i - 1) + j
        for f in 1:(2 * (dim - 1))
            sendfaces[f, e] = basetopo.sendfaces[f, i]
        end
    end

    elemtocoord = similar(basetopo.elemtocoord, dim, nvert, length(elems))

    for i in 1:length(basetopo.elems), j in 1:stacksize
        # i is base element
        # e is stacked element
        e = stacksize * (i - 1) + j

        # v is base vertex
        for v in 1:(2^(dim - 1))
            for d in 1:dim # dim here since shell is embedded in 3-D
                # v is lower stacked vertex
                elemtocoord[d, v, e] = basetopo.elemtocoord[d, v, i] * Rrange[j]
                # 2^(dim-1) + v is higher stacked vertex
                elemtocoord[d, 2^(dim - 1) + v, e] =
                    basetopo.elemtocoord[d, v, i] * Rrange[j + 1]
            end
        end
    end

    elemtoelem = similar(basetopo.elemtoelem, nface, length(elems))
    elemtoface = similar(basetopo.elemtoface, nface, length(elems))
    elemtoordr = similar(basetopo.elemtoordr, nface, length(elems))
    elemtobndy = similar(basetopo.elemtobndy, nface, length(elems))

    for e in 1:(length(basetopo.elems) * stacksize), f in 1:nface
        elemtoelem[f, e] = e
        elemtoface[f, e] = f
        elemtoordr[f, e] = 1
        elemtobndy[f, e] = 0
    end

    for i in 1:length(basetopo.realelems), j in 1:stacksize
        e1 = stacksize * (i - 1) + j

        for f in 1:(2 * (dim - 1))
            e2 = stacksize * (basetopo.elemtoelem[f, i] - 1) + j

            elemtoelem[f, e1] = e2
            elemtoface[f, e1] = basetopo.elemtoface[f, i]

            # since the basetopo is 2-D we only need to worry about two
            # orientations
            @assert basetopo.elemtoordr[f, i] ∈ (1, 2)
            #=
            orientation 1:
            2---3     2---3
            |   | --> |   |
            0---1     0---1
            same:
            (a,b) --> (a,b)

            orientation 3:
            2---3     3---2
            |   | --> |   |
            0---1     1---0
            reverse first index:
            (a,b) --> (N+1-a,b)
            =#
            elemtoordr[f, e1] = basetopo.elemtoordr[f, i] == 1 ? 1 : 3
        end

        # If top or bottom of stack set neighbor to self on respective face
        elemtoelem[2 * (dim - 1) + 1, e1] =
            j == 1 ? e1 : stacksize * (i - 1) + j - 1
        elemtoelem[2 * (dim - 1) + 2, e1] =
            j == stacksize ? e1 : stacksize * (i - 1) + j + 1

        elemtoface[2 * (dim - 1) + 1, e1] =
            j == 1 ? 2 * (dim - 1) + 1 : 2 * (dim - 1) + 2
        elemtoface[2 * (dim - 1) + 2, e1] =
            j == stacksize ? 2 * (dim - 1) + 2 : 2 * (dim - 1) + 1

        elemtoordr[2 * (dim - 1) + 1, e1] = 1
        elemtoordr[2 * (dim - 1) + 2, e1] = 1
    end

    # Set the top and bottom boundary condition
    for i in 1:length(basetopo.elems)
        eb = stacksize * (i - 1) + 1
        et = stacksize * (i - 1) + stacksize

        elemtobndy[2 * (dim - 1) + 1, eb] = boundary[1]
        elemtobndy[2 * (dim - 1) + 2, et] = boundary[2]
    end

    nabrtorank = basetopo.nabrtorank
    nabrtorecv = UnitRange{Int}[
        UnitRange(
            stacksize * (first(basetopo.nabrtorecv[n]) - 1) + 1,
            stacksize * last(basetopo.nabrtorecv[n]),
        ) for n in 1:length(nabrtorank)
    ]
    nabrtosend = UnitRange{Int}[
        UnitRange(
            stacksize * (first(basetopo.nabrtosend[n]) - 1) + 1,
            stacksize * last(basetopo.nabrtosend[n]),
        ) for n in 1:length(nabrtorank)
    ]

    StackedCubedSphereTopology{T}(
        BoxElementTopology{3, T}(
            mpicomm,
            elems,
            realelems,
            ghostelems,
            ghostfaces,
            sendelems,
            sendfaces,
            elemtocoord,
            elemtoelem,
            elemtoface,
            elemtoordr,
            elemtobndy,
            nabrtorank,
            nabrtorecv,
            nabrtosend,
            basetopo.origsendorder,
            true,
        ),
        stacksize,
    )
end

"""
    grid1d(a, b[, stretch::AbstractGridStretching]; elemsize, nelem)

Discretize the 1D interval [`a`,`b`] into elements.
Exactly one of the following keyword arguments must be provided:
- `elemsize`: the average element size, or
- `nelem`: the number of elements.

The optional `stretch` argument allows stretching, otherwise the element sizes
will be uniform.

Returns either a range object or a vector containing the element boundaries.
"""
function grid1d(a, b, stretch = nothing; elemsize = nothing, nelem = nothing)
    xor(nelem === nothing, elemsize === nothing) ||
    error("Either `elemsize` or `nelem` arguments must be provided")
    if elemsize !== nothing
        nelem = round(Int, abs(b - a) / elemsize)
    end
    grid1d(a, b, stretch, nelem)
end
function grid1d(a, b, ::Nothing, nelem)
    range(a, stop = b, length = nelem + 1)
end

# TODO: document these
abstract type AbstractGridStretching end

"""
    SingleExponentialStretching(A)

Apply single-exponential stretching: `A > 0` will increase the density of points
at the lower boundary, `A < 0` will increase the density at the upper boundary.

# Reference
* "Handbook of Grid Generation" J. F. Thompson, B. K. Soni, N. P. Weatherill
  (Editors) RCR Press 1999, §3.6.1 Single-Exponential Function
"""
struct SingleExponentialStretching{T} <: AbstractGridStretching
    A::T
end
function grid1d(
    a::A,
    b::B,
    stretch::SingleExponentialStretching,
    nelem,
) where {A, B}
    F = float(promote_type(A, B))
    s = range(zero(F), stop = one(F), length = nelem + 1)
    a .+ (b - a) .* expm1.(stretch.A .* s) ./ expm1(stretch.A)
end

struct InteriorStretching{T} <: AbstractGridStretching
    attractor::T
end
function grid1d(a::A, b::B, stretch::InteriorStretching, nelem) where {A, B}
    F = float(promote_type(A, B))
    coe = F(2.5)
    s = range(zero(F), stop = one(F), length = nelem + 1)
    range(a, stop = b, length = nelem + 1) .+
    coe .* (stretch.attractor .- (b - a) .* s) .* (1 .- s) .* s
end

end


using DelayDiffEq, DiffEqProblemLibrary.DDEProblemLibrary
using Test

DDEProblemLibrary.importddeproblems()

@testset "init" begin
    prob = DDEProblemLibrary.prob_dde_constant_1delay_ip
    prob_scalar = DDEProblemLibrary.prob_dde_constant_1delay_scalar

    inferred = [BS3(), Tsit5(), RK4(), Vern6()]
    for alg in inferred
        ddealg = MethodOfSteps(alg)

        @test_broken @inferred init(prob, ddealg)
        @test_broken @inferred init(prob_scalar, ddealg)
    end

    notinferred = [SDIRK2(), TRBDF2(), KenCarp4(), Rosenbrock23(), Rodas4()]
    for alg in notinferred
        ddealg = MethodOfSteps(alg)

        @test_broken @inferred init(prob, ddealg)
        @test_broken @inferred init(prob_scalar, ddealg)
    end
end

@testset "discontinuity_time" begin
    prob_inplace = DDEProblemLibrary.prob_dde_constant_1delay_ip
    prob_scalar = DDEProblemLibrary.prob_dde_constant_1delay_scalar

    for prob in (prob_inplace, prob_scalar)
        int = init(prob, MethodOfSteps(Tsit5()))
        @inferred DelayDiffEq.discontinuity_time(int, (u, p, t) -> 1.0, 0.0, (0.5, 1.5))
    end
end


## Gather data back from RDA files
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_1/kenya_inc_sev_no_vac_w_vac.rda")
"""
kenya_inc_sev_sc_1 = @rget kenya_inc_sev
kenya_inc_sev_sc_1 = sum(kenya_inc_sev_sc_1, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_2/kenya_inc_sev_30_perc_w_vac.rda")
"""
kenya_inc_sev_sc_2 = @rget kenya_inc_sev
kenya_inc_sev_sc_2 = sum(kenya_inc_sev_sc_2, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_3/kenya_inc_sev_50_perc_w_vac.rda")
"""
kenya_inc_sev_sc_3 = @rget kenya_inc_sev
kenya_inc_sev_sc_3 = sum(kenya_inc_sev_sc_3, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_4/kenya_inc_sev_70_perc_w_vac.rda")
"""
kenya_inc_sev_sc_4 = @rget kenya_inc_sev
kenya_inc_sev_sc_4 = sum(kenya_inc_sev_sc_4, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_5/kenya_inc_sev_30_perc_rapid_w_vac.rda")
"""
kenya_inc_sev_sc_5 = @rget kenya_inc_sev
kenya_inc_sev_sc_5 = sum(kenya_inc_sev_sc_5, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_6/kenya_inc_sev_50_perc_rapid_w_vac.rda")
"""
kenya_inc_sev_sc_6 = @rget kenya_inc_sev
kenya_inc_sev_sc_6 = sum(kenya_inc_sev_sc_6, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""
R"""
load(file = "generation_of_data_for_econ_analysis/waning_imm_scenario_7/kenya_inc_sev_70_perc_rapid_w_vac.rda")
"""
kenya_inc_sev_sc_7 = @rget kenya_inc_sev
kenya_inc_sev_sc_7 = sum(kenya_inc_sev_sc_7, dims = 2)[:, 1, :]
kenya_inc_sev = 0
R"""
kenya_inc_sev = 0 #Free memory
"""