text:
"""
    mosaic(f, regions...; missingval, atol)
    mosaic(f, regions; missingval, atol)

Combine `regions`s into a single raster.

# Arguments

- `f`: A reducing function (e.g. `mean`, `sum`, `first` or `last`) for values where `regions` overlap.
- `regions`: Iterable or splatted `Raster` or `RasterStack`.

# Keywords

- `missingval`: Fills empty areas, and defualts to the
    `missingval` of the first layer.
- `atol`: Absolute tolerance for comparison between index values.
    This is often required due to minor differences in range values
    due to floating point error. It is not applied to non-float dimensions.
    A tuple of tolerances may be passed, matching the dimension order.
- `filename`: a file to write to directly.

If your mosaic has has apparent line errors, increase the `atol` value.

# Example

Here we cut out australia and africa from a stack, and join them with `mosaic`.

```jldoctest
using Rasters, Plots
st = RasterStack(WorldClim{Climate}; month=1);

africa = st[X(Between(-20.0, 60.0)), Y(Between(35.0, -40.0))]
a = plot(africa)

aus = st[X(Between(100.0, 160.0)), Y(Between(-10.0, -50.0))]
b = plot(aus)

# Combine with mosaic
mos = mosaic(first, aus, africa)
c = plot(mos)

savefig(a, "build/mosaic_example_africa.png")
savefig(b, "build/mosaic_example_aus.png")
savefig(c, "build/mosaic_example_combined.png")
# output

```

### Individual continents

![arica](mosaic_example_africa.png)

![aus](mosaic_example_aus.png)

### Mosaic of continents

![mosaic](mosaic_example_combined.png)

$EXPERIMENTAL
"""
function mosaic(f::Function, r1::RasterStackOrArray, rs::RasterStackOrArray...; kw...)
    mosaic(f, (r1, rs...); kw...)
end
mosaic(f::Function, regions; kw...) = _mosaic(f, first(regions), regions; kw...)
function _mosaic(f::Function, ::AbstractRaster, regions;
    missingval=missingval(first(regions)), filename=nothing, suffix=nothing, kw...
)
    missingval isa Nothing && throw(ArgumentError("Layers have no missingval, so pass a `missingval` keyword explicitly"))
    T = Base.promote_type(typeof(missingval), Base.promote_eltype(regions...))
    dims = _mosaic(Tuple(map(DD.dims, regions)))
    l1 = first(regions)
    A = create(filename, T, dims; name=name(l1), missingval, metadata=metadata(l1))
    open(A; write=true) do a
        mosaic!(f, a, regions; missingval, kw...)
    end
    return A
end
function _mosaic(f::Function, ::AbstractRasterStack, regions;
    filename=nothing, suffix=keys(first(regions)), kw...
)
    layers = map(suffix, map(values, regions)...) do s, A...
        mosaic(f, A...; filename, suffix=s, kw...)
    end
    return DD.rebuild_from_arrays(first(regions), Tuple(layers))
end

"""
    mosaic!(f, x, regions...; missingval, atol)
    mosaic!(f, x, regions::Tuple; missingval, atol)

Combine `regions`s in `x` using the function `f`.

# Arguments

- `f` a function (e.g. `mean`, `sum`, `first` or `last`) that is applied to
    values where `regions` overlap.
- `x`: A `Raster` or `RasterStack`. May be a an opened disk-based `Raster`,
    the result will be written to disk.
    slow read speed with the current algorithm
- `regions`: source objects to be joined. These should be memory-backed
    (use `read` first), or may experience poor performance. If all objects have
    the same extent, `mosaic` is simply a merge.

# Keywords

- `missingval`: Fills empty areas, and defualts to the `missingval/
    of the first layer.
- `atol`: Absolute tolerance for comparison between index values.
    This is often required due to minor differences in range values
    due to floating point error. It is not applied to non-float dimensions.
    A tuple of tolerances may be passed, matching the dimension order.

# Example

Cut out Australia and Africa stacks, then combined them
into a single stack.

```jldoctest
using Rasters, Statistics, Plots
st = read(RasterStack(WorldClim{Climate}; month=1))
aus = st[X(Between(100.0, 160.0)), Y(Between(-10.0, -50.0))]
africa = st[X(Between(-20.0, 60.0)), Y(Between(35.0, -40.0))]
mosaic!(first, st, aus, africa)
plot(st)
savefig("build/mosaic_bang_example.png")
# output

```

![mosaic](mosaic_bang_example.png)

$EXPERIMENTAL
"""
mosaic!(f::Function, x::RasterStackOrArray, regions::RasterStackOrArray...; kw...) = mosaic!(f, x, regions; kw...)
function mosaic!(f::Function, A::AbstractRaster{T}, regions;
    missingval=missingval(A), atol=_default_atol(T)
) where T
    _without_mapped_crs(A) do A1
        broadcast!(A1, DimKeys(A1; atol)) do ds
            # Get all the regions that have this point
            ls = foldl(regions; init=()) do acc, l
                if DD.hasselection(l, ds)
                    v = l[ds...]
                    (acc..., l)
                else
                    acc
                end
            end
            values = foldl(ls; init=()) do acc, l
                v = l[ds...]
                if isnothing(Rasters.missingval(l))
                    (acc..., v)
                elseif ismissing(Rasters.missingval(l))
                    ismissing(v) ? acc : (acc..., v)
                else
                    v === Rasters.missingval(l) ? acc : (acc..., v)
                end
            end
            if length(values) === 0
                missingval
            else
                f(values)
            end
        end
    end
    return A
end
function mosaic!(f::Function, st::AbstractRasterStack, regions::Tuple; kw...)
    map(st, regions...) do A, r...
        mosaic!(f, A, r; kw...)
    end
end

_mosaic(alldims::Tuple{<:DimTuple,Vararg{<:DimTuple}}) = map(_mosaic, alldims...)
function _mosaic(dims::Dimension...)
    map(dims) do d
        DD.comparedims(first(dims), d; val=false, length=false, lookup=true)
    end
    return rebuild(first(dims), _mosaic(lookup(dims)))
end
_mosaic(lookups::LookupArrayTuple) = _mosaic(first(lookups), lookups)
function _mosaic(lookup::Categorical, lookups::LookupArrayTuple)
    newindex = union(lookups...)
    if order isa ForwardOrdered
        newindex = sort(newindex; order=LA.ordering(order(lookup)))
    end
    return rebuild(lookup; data=newindex)
end
function _mosaic(lookup::AbstractSampled, lookups::LookupArrayTuple)
    order(lookup) isa Unordered && throw(ArgumentError("Cant mozaic an Unordered lookup"))
    return _mosaic(span(lookup), lookup, lookups)
end
function _mosaic(span::Regular, lookup::AbstractSampled, lookups::LookupArrayTuple)
    newindex = if order(lookup) isa ForwardOrdered
        mi = minimum(map(first, lookups))
        ma = maximum(map(last, lookups))
        if mi isa AbstractFloat
            # Handle slight range erorrs to make sure
            # we dont drop one step of the range
            mi:step(span):ma + 2eps(ma)
        else
            mi:step(span):ma
        end
    else
        mi = minimum(map(last, lookups))
        ma = maximum(map(first, lookups))
        if mi isa AbstractFloat
            ma:step(span):mi - 2eps(mi)
        else
            ma:step(span):mi
        end
    end
    return rebuild(lookup; data=newindex)
end

function _mosaic(::Irregular, lookup::AbstractSampled, lookups::LookupArrayTuple)
    newindex = sort(union(map(parent, lookups)...); order=LA.ordering(order(lookup)))
    return rebuild(lookup; data=newindex)
end
function _mosaic(span::Explicit, lookup::AbstractSampled, lookups::LookupArrayTuple)
    # TODO make this less fragile to floating point innaccuracy
    newindex = sort(union(map(parent, lookups)...); order=LA.ordering(order(lookup)))
    bounds = map(val ∘ DD.span, lookups)
    lower = map(b -> view(b, 1, :), bounds)
    upper = map(b -> view(b, 2, :), bounds)
    newlower = sort(union(lower...); order=LA.ordering(order(lookup)))
    newupper = sort(union(upper...); order=LA.ordering(order(lookup)))
    newbounds = vcat(permutedims(newlower), permutedims(newupper))
    return rebuild(lookup; data=newindex, span=Explicit(newbounds))
end

# These are pretty random default, but seem to work
_default_atol(T::Type{<:Float32}) = 100eps(T)
_default_atol(T::Type{<:Float64}) = 1000eps(T)
_default_atol(T::Type{<:Integer}) = T(1)
_default_atol(::Type) = nothing


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "GeographicLib"
version = v"1.52.0"

# Collection of sources required to complete build
sources = [
    ArchiveSource("https://sourceforge.net/projects/geographiclib/files/distrib/GeographicLib-1.52.tar.gz", "5d4145cd16ebf51a2ff97c9244330a340787d131165cfd150e4b2840c0e8ac2b")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir
cd GeographicLib-*
mkdir build
cd build/
cmake -DCMAKE_INSTALL_PREFIX=$prefix -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} -DCMAKE_BUILD_TYPE=Release ..
make -j${nproc}
make install
exit
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms())

# The products that we will ensure are always built
products = [
    ExecutableProduct("GeodesicProj", :GeodesicProj),
    ExecutableProduct("Gravity", :Gravity),
    LibraryProduct("libGeographic", :libGeographic),
    ExecutableProduct("MagneticField", :MagneticField),
    ExecutableProduct("CartConvert", :CartConvert),
    ExecutableProduct("GeodSolve", :GeodSolve),
    ExecutableProduct("GeoidEval", :GeoidEval),
    ExecutableProduct("ConicProj", :ConicProj),
    ExecutableProduct("RhumbSolve", :RhumbSolve),
    ExecutableProduct("TransverseMercatorProj", :TransverseMercatorProj),
    ExecutableProduct("Planimeter", :Planimeter),
    ExecutableProduct("GeoConvert", :GeoConvert)
]

# Dependencies that must be installed before this package can be built
dependencies = Dependency[
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6", preferred_gcc_version=v"9")

ext: jl

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
module Runtests

#=
Currently deactivated, since automatic test will often result in an error
(e.g. no webbrowser available).

import ModiaResult
using  Test

@testset "Test ModiaPlot_WGLMakie/test" begin
    ModiaResult.usePlotPackage("WGLMakie")
    include("$(ModiaResult.path)/test/runtests_withPlot.jl")
    ModiaResult.usePreviousPlotPackage()
end

=#

end


text:
#=
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.

For example, given the following Node class

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

The following test should pass:

node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
=#

using Test
include("Solutions/problem3_serialize_deserialize.jl")

struct Node
    val
    left
    right
end

function Node(val; left = "", right = "")
    Node(val, left, right)
end

node = Node("root", Node("left", left = Node("left.left")), Node("right"))

@test deserialize(serialize(node)).left.left.val == "left.left"

max_stars_repo_name: DominiqueCaron/daily-coding-problem

max_issues_repo_name: DominiqueCaron/daily-coding-problem

max_forks_repo_name: DominiqueCaron/daily-coding-problem


text:
#****************************************************************************
#                     Molecular Dynamics Potentials (MDP)
#                            CESMIX-MIT Project
#
#  Contributing authors: Ngoc-Cuong Nguyen (cuongng@mit.edu, exapde@gmail.com)
#****************************************************************************

function genquadruplet(foldername,filename, u, xij, xik, xil, qi, qj, qk, ql, ti, tj, tk, tl, ai, aj, ak, al, mu, eta, kappa, gen, ifile)

#foldername = "app";
opufile = "opu" * filename;
cpufile = "cpu" * filename;
gpufile = "gpu" * filename;

sp0, sp1, sp2, sp3 = getpotstr(4);

if gen==0
    stropu = "template <typename T> void " * opufile;

    tmp = sp0;

    stropu = stropu * tmp * "{\n";
    stropu = stropu * "}\n";

    tmp = "template void " * opufile;
    tmp = tmp * sp1;
    tmp = tmp * "template void " * opufile;
    tmp = tmp * sp2;

    stropu = stropu * tmp;
    strcpu = replace(stropu, "opu" => "cpu");
    strgpu = replace(stropu, "opu" => "gpu");

    #sp0 = "(T *u, T *xij, T *xik, T *xil, T *qi, T *qj, T *qk, T *ql, int *ti, int *tj, int *tk, int *tl, int *ai, int *aj, int *ak, int *al, T *mu, T *eta, int *kappa, int dim, int ncq, int nmu, int neta, int nkappa, int ng)\n";
    tmp = strgpu;
    tmp = replace(tmp, "(T *u, T *xij, T *xik, T *xil," => "Gradient(T *u, T *du, T *u_xij, T *u_xik, T *u_xil, T *xij, T *xik, T *xil,");
    tmp = replace(tmp, "(double *," => "Gradient(double *, double *, double *, double *, double *,");
    tmp = replace(tmp, "(float *," => "Gradient(float *, float *, float *, float *, float *,");
    strgpu = strgpu * "\n" * tmp;
else
    stropu = "template <typename T> void " * opufile;
    strgpu = "template <typename T>  __global__  void kernel" * gpufile;

    # here
    tmp = sp0;
    st2 = strgpu * sp0 * "{\n";

    stropu = stropu * tmp * "{\n";
    stropu = stropu * "\tfor (int i = 0; i <ng; i++) {\n";

    strgpu = strgpu * tmp * "{\n";
    strgpu = strgpu * "\tint i = threadIdx.x + blockIdx.x * blockDim.x;\n";
    strgpu = strgpu * "\twhile (i<ng) {\n";

    ustr = string(u);
    mystr = "";
    if (contains(ustr, "mu"))
        mystr = varsassign(mystr, "mu", length(mu), ustr, 0);
    end
    if (contains(ustr, "eta"))
        mystr = varsassign(mystr, "eta", length(eta), ustr, 0);
    end
    if (contains(ustr, "kappa"))
        mystr = varsassign(mystr, "kappa", length(kappa), ustr, 1);
    end
    if (contains(ustr, "xij"))
        mystr = varsassign(mystr, "xij", length(xij), ustr, 2);
    end
    if (contains(ustr, "xik"))
        mystr = varsassign(mystr, "xik", length(xik), ustr, 2);
    end
    if (contains(ustr, "xil"))
        mystr = varsassign(mystr, "xil", length(xil), ustr, 2);
    end
    if (contains(ustr, "qi"))
        mystr = varsassign(mystr, "qi", length(qi), ustr, 2);
    end
    if (contains(ustr, "qj"))
        mystr = varsassign(mystr, "qj", length(qj), ustr, 2);
    end
    if (contains(ustr, "qk"))
        mystr = varsassign(mystr, "qk", length(qk), ustr, 2);
    end
    if (contains(ustr, "ql"))
        mystr = varsassign(mystr, "ql", length(ql), ustr, 2);
    end
    if (contains(ustr, "ti"))
        mystr = varsassign(mystr, "ti", length(ti), ustr, 3);
    end
    if (contains(ustr, "tj"))
        mystr = varsassign(mystr, "tj", length(tj), ustr, 3);
    end
    if (contains(ustr, "tk"))
        mystr = varsassign(mystr, "tk", length(tk), ustr, 3);
    end
    if (contains(ustr, "tl"))
        mystr = varsassign(mystr, "tl", length(tl), ustr, 3);
    end
    if (contains(ustr, "ai"))
        mystr = varsassign(mystr, "ai", length(ai), ustr, 3);
    end
    if (contains(ustr, "aj"))
        mystr = varsassign(mystr, "aj", length(aj), ustr, 3);
    end
    if (contains(ustr, "ak"))
        mystr = varsassign(mystr, "ak", length(ak), ustr, 3);
    end
    if (contains(ustr, "al"))
        mystr = varsassign(mystr, "al", length(al), ustr, 3);
    end
    mystr = symsassign(mystr, u);

    stropu = stropu * mystr * "\t}\n" * "}\n\n";

    strgpu = strgpu * mystr * "\t\ti += blockDim.x * gridDim.x;\n";
    strgpu = strgpu * "\t}\n" * "}\n\n";

    # here
    st1 = strgpu;

    tmp = "template <typename T> void " * gpufile;
    tmp = tmp * sp0;
    tmp = tmp * "{\n";
    tmp = tmp * "\tint blockDim = 256;\n";
    tmp = tmp * "\tint gridDim = (ng * blockDim - 1) / blockDim;\n";
    tmp = tmp * "\tgridDim = (gridDim>1024)? 1024 : gridDim;\n";
    tmp = tmp * "\tkernel" * gpufile * "<<<gridDim, blockDim>>>" * sp3;
    tmp = tmp * "}\n\n";
    strgpu = strgpu * tmp;

    # here
    st1 = replace(st1, "__global__  void kernelgpu" => "__device__  void devicegpu");
    st1 = replace(st1, "T *" => "T *__restrict__ ");
    st1 = replace(st1, "int *" => "int *__restrict__ ");
    st2 = replace(st2, "(T *u, T *xij," => "Gradient(T *u, T *du, T *u_xij, T *u_xik, T *u_xil, T *xij,");
    st2 = replace(st2, "*" => "*__restrict__ ");
    st3 = "\t__enzyme_autodiff((void*)devicegpu" * filename *  "<T>, \n";
    st3 = st3 *  "\t\tenzyme_dup, u, du, \n";
    st3 = st3 *  "\t\tenzyme_dup, xij, u_xij, \n";
    st3 = st3 *  "\t\tenzyme_dup, xik, u_xik, \n";
    st3 = st3 *  "\t\tenzyme_dup, xil, u_xil, \n";
    st3 = st3 *  "\t\tenzyme_const, qi, \n";
    st3 = st3 *  "\t\tenzyme_const, qj, \n";
    st3 = st3 *  "\t\tenzyme_const, qk, \n";
    st3 = st3 *  "\t\tenzyme_const, ql, \n";
    st3 = st3 *  "\t\tenzyme_const, ti, \n";
    st3 = st3 *  "\t\tenzyme_const, tj, \n";
    st3 = st3 *  "\t\tenzyme_const, tk, \n";
    st3 = st3 *  "\t\tenzyme_const, tl, \n";
    st3 = st3 *  "\t\tenzyme_const, ai, \n";
    st3 = st3 *  "\t\tenzyme_const, aj, \n";
    st3 = st3 *  "\t\tenzyme_const, ak, \n";
    st3 = st3 *  "\t\tenzyme_const, al, \n";
    st3 = st3 *  "\t\tenzyme_const, mu, \n";
    st3 = st3 *  "\t\tenzyme_const, eta, \n";
    st3 = st3 *  "\t\tenzyme_const, kappa, \n";
    st3 = st3 *  "\t\tdim, ncq, nmu, neta, nkappa, ng); \n";
    st2 = st2 * st3 * "}\n";
    st4 = tmp;
    st4 = replace(st4, "(T *u, T *xij," => "Gradient(T *u, T *du, T *u_xij, T *xij,");
    st4 = replace(st4, "u, xij," => "u, du, u_xij, xij,");
    st4 = replace(st4, "<<<" => "Gradient<<<");
    st2 = st2 * "\n" * st4;
    #strgpu = strgpu * "\n" * st1 * "\n" * st2;
    strgpu = strgpu * "\n" *  "#ifdef _ENZYME\n" * st1 * "\n" * st2 * "#endif\n";

    strcpu = replace(stropu, "opu" => "cpu");
    strcpu = replace(strcpu, "for (int i = 0; i <ng; i++) {" => "#pragma omp parallel for\n\tfor (int i = 0; i <ng; i++) {");
end

if ifile==1
    ioopu = open(foldername * "/" * opufile * ".cpp", "w");
    write(ioopu, stropu);
    close(ioopu);

    iocpu = open(foldername * "/" * cpufile * ".cpp", "w");
    write(iocpu, strcpu);
    close(iocpu);

    iogpu = open(foldername * "/" * gpufile * ".cu", "w");
    write(iogpu, strgpu);
    close(iogpu);
end

return stropu, strcpu, strgpu

end

max_stars_repo_name: cesmix-mit/MDP

max_issues_repo_name: cesmix-mit/MDP

max_forks_repo_name: cesmix-mit/MDP


text:
using Test
using PrettyTables
using Tables
using Markdown

data = Any[1    false      1.0     0x01 ;
           2     true      2.0     0x02 ;
           3    false      3.0     0x03 ;
           4     true      4.0     0x04 ;
           5    false      5.0     0x05 ;
           6     true      6.0     0x06 ;]

println("Text backend")
println("============")
println()
include("./text_backend.jl")
println()

println("HTML backend")
println("============")
println()
include("./html_backend.jl")
println()

println("LaTeX backend")
println("=============")
println()
include("./latex_backend.jl")
println()

println("General")
println("=======")
println()

include("./general.jl")
println()


text:
module AlgebraResultTypes

function result_field(::Type{T}) where {T <: Number}
    isconcretetype(T) || return Number
    o = one(T)
    typeof(o / o - o + (o + o))
end

function result_field(::Type{T}, ::Type{S}) where {T <: Number, S <: Number}
    RT = result_field(T)
    RS = result_field(S)
    if isconcretetype(RT) && isconcretetype(RS)
        a = one(RT)
        b = one(RS)
        typeof(a / b + a * b - b / a - a / a + b / b)
    else
        Number
    end
end

"""
    result_field(T1, T2, ...)

Return a supertype of the result type of applying operation `+`, `-`, `*`, `/` on the given
types. Ideally, for concrete types, this is the narrowest concrete type.

You may want to apply `widen` to the result for complex calculations.

Formally, for any values `x1::T1`, `x2::T2`, ..., where  `T1, T2, ... <: Number`, and
operations `op1, op2, ... ∈ (+, -, *, /)`,

```julia
op1(x1, op2(x2, op3(x3, ...))) isa result_field(T1, T2, T3, ...)
```

Any violation of this is a bug, and should be reported as an issue.

The implementation uses heuristics, and may not find the narrowest type, falling back to
`Number` for non-concrete types. Please open an issue if you think this can be improved for
some concrete types.
"""
function result_field(::Type{T}, ::Type{S}, Ts...) where {T <: Number, S <: Number}
    result_field(result_field(T, S), Ts...)
end

function result_ring(::Type{T}) where {T <: Number}
    isconcretetype(T) || return Number
    o = one(T)
    typeof(o * o - o + (o + o))
end

function result_ring(::Type{T}, ::Type{S}) where {T <: Number, S <: Number}
    RT = result_ring(T)
    RS = result_ring(S)
    if isconcretetype(RT) && isconcretetype(RS)
        a = one(RT)
        b = one(RS)
        typeof(a * b + b * a - a + b)
    else
        Number
    end
end

"""
    result_ring(T1, T2, ...)

Return a supertype of the result type of applying operation `+`, `-`, `*`, on the given
types. Ideally, for concrete types, this is the narrowest concrete type.

You may want to apply `widen` to the result for complex calculations.

See [`result_field`](@ref) for details, *mutatis mutandis*.
"""
function result_ring(::Type{T}, ::Type{S}, Ts...) where {T <: Number, S <: Number}
    result_ring(result_ring(T, S), Ts...)
end

"""
    number_type(x)

When the argument is a `Number`, return its type, when a container, return its element type
in case it can be determined to be `<: Number`.

# Recommended usage

Simplify

```julia
function foo(x::T1, A::AbstractArray{T2}, b::AbstractVector{T3}) where {T1,T2,T3}
    T = result_field(T1, T2, T3)
    ...
end
```

to

```julia
function foo(x, A, b)
    T = result_field(number_type.(x, A, b)...)
    ...
end
```

in situations where the types are not needed otherwise.
"""
number_type(::T) where {T <: Number} = T

number_type(::AbstractArray{T}) where {T <: Number} = T

end # module


text:
@testset "accessor functions for HLAModelResult" begin
    tmp = tempname()

    if !isfile(joinpath(@__DIR__, "data", "result.jls"))
        result = @suppress Escape.run(
            Escape.HLAModel{4}(), Escape.HLADataset("Test").data[1],
            iter = 10, chains = 1
        )

        serialize(joinpath(@__DIR__, "data", "result.jls"), result)
    end

    result = deserialize(joinpath(@__DIR__, "data", "result.jls"))

    @test Escape.stan_input(result) === result.sf.data
    @test Escape.stanfit(result) === result.sf
    @test Escape.hla_data(result) === result.data
    @test Escape.hla_model(result) === result.model
end

@testset "replacement_summary(::HLAModelResult)" begin
    if !isfile(joinpath(@__DIR__, "data", "result.jls"))
        result = @suppress Escape.run(
            Escape.HLAModel{4}(), Escape.HLADataset("Test").data[1],
            result_dir = tempdir(),
            result_name = splitdir(tmp)[end],
            iter = 200, warmup = 200, chains = 4
        )

        serialize(joinpath(@__DIR__, "data", "result.jls"), result)
    end

    result = deserialize(joinpath(@__DIR__, "data", "result.jls"))

    @test @suppress Escape.replacement_summary(result) isa DataFrame
end

@testset "reduce_size!(::HLAModelResult)" begin
    ds = Escape.HLADataset("Test")
    m = Escape.HLAModel{4}()
    data = ds.data[1]

    res = @suppress Escape.run(m, data, iter = 5, warmup = 5, chains = 1,
        keep_all_parameters = true)

    previous_size = Base.summarysize(res)
    Escape.reduce_size!(res)

    @test Base.summarysize(res) < previous_size
end

@testset "diagnostics(::HLAModelResult)" begin
    ds = Escape.HLADataset("Test")
    data = ds.data[1]

    res = @suppress Escape.run(Escape.HLAModel{1}(), data, iter = 5, warmup = 5, chains = 1)

    @test Escape.diagnostics(res) == res.sf.diagnostics
end

@testset "load_result(::String)" begin
    ds = Escape.HLADataset("Test")

    save_file = tempname() * ".jld2"
    res = @suppress Escape.run_model(ds.data[1], warmup = 10, iter = 10, chains = 1,
        save_file = save_file)

    @test Escape.load_result(save_file) isa Escape.HLAModelResult
end


text:
module PhaseSpaces

export Q_of_θφ,Q_of_θϕ,P_of_θφ,P_of_θϕ,θ_of_QP,φ_of_QP,ϕ_of_QP,jz,jx,jy,arc_between_θφ,arc_between_θϕ,arc_between_QP
    """
    ```julia
    function Q_of_θϕ(θ,ϕ)
    ```

    Returns
    ```math
        Q=\\sqrt{2 (1 - \\cos(\\theta))}\\cos(\\phi).
    ```

    Also [`Q_of_θφ(θ,φ)`](@ref Q_of_θφ).
    """
    Q_of_θϕ(θ::Real,ϕ::Real)=sqrt(2*(1-cos(θ)))*cos(ϕ)

    """
    See [`Q_of_θϕ`](@ref).
    """
    Q_of_θφ(θ::Real,φ::Real)=Q_of_θϕ(θ,φ)

    """
    ```julia
    function P_of_θϕ(θ,ϕ)
    ```

    Returns
    ```math
        P=- \\sqrt{2 (1 - \\cos(\\theta))}\\sin(\\phi).
    ```
    Also [`P_of_θφ(θ,φ)`](@ref P_of_θφ).
    """
    P_of_θϕ(θ::Real,ϕ::Real)=-sqrt(2*(1-cos(θ)))*sin(ϕ)

    """
    See [`P_of_θϕ`](@ref).
    """
    P_of_θφ(θ::Real,φ::Real)=P_of_θϕ(θ,φ)
    """
    ```julia
    function θ_of_QP(Q,P)
    ```
    Returns
    ```math
        \\theta =- \\arccos\\left(1 - \\frac{Q^2 + P^2}{2}\\right).
    ```
    """
    θ_of_QP(Q::Real,P::Real)=acos(1-(Q^2+P^2)/2)
    """
    ```julia
    function ϕ_of_QP(Q,P)
    ```

    Returns
    ```math
        \\phi = \\text{arctan2}(-P,Q)\\in [0,2 \\pi ],
    ```
    where ``\\text{arctan2}`` is the [2-argument arctangent](https://en.wikipedia.org/wiki/Atan2).

    Also [`φ_of_QP(Q,P)`](@ref φ_of_QP).
    """
    ϕ_of_QP(Q::Real,P::Real)=mod(atan(-P,Q),2*pi)

    """
    See [`ϕ_of_QP`](@ref).
    """
    φ_of_QP(Q::Real,P::Real)=ϕ_of_QP(Q,P)

    """
    ```julia
    function jz(Q,P)
    ```
    Returns
    ```math
        j_z = -  \\cos(\\theta(Q,P)).
    ```
    where ``\\text{arctan2}`` is the [2-argument arctangent](https://en.wikipedia.org/wiki/Atan2).
    """
    jz(Q::Real,P::Real)=-cos(θ_of_QP(Q,P))
    """
    ```julia
    function jx(Q,P)
    ```
    Returns
    ```math
        j_x = \\sin(\\theta(Q,P))\\cos(\\phi(Q,P)).
    ```
    """
    jx(Q::Real,P::Real)=sin(θ_of_QP(Q,P))*cos(φ_of_QP(Q,P))
    """
    ```julia
    function jy(Q,P)
    ```
    Returns
    ```math
        j_y = \\sin(\\theta(Q,P))\\sin(\\phi(Q,P)).
    ```
    """
    jy(Q::Real,P::Real)=sin(θ_of_QP(Q,P))*sin(φ_of_QP(Q,P))
    """
    ```julia
    function arc_between_θϕ(θ1,φ1,θ2,φ2)
    ```
    Returns
    ```math
        \\Theta = \\arccos(\\cos(\\theta_1)\\cos(\\theta_2)+ \\sin(\\theta_1)\\sin(\\theta_2)\\cos(\\phi_1 - \\phi_2)).
    ```
    Also [`arc_between_θφ(θ1,φ1,θ2,φ2)`](@ref arc_between_θφ).

    """
    arc_between_θϕ(θ1::Real,ϕ1::Real,θ2::Real,ϕ2::Real)=acos(clamp(cos(θ1)*cos(θ2)+ sin(θ1)*sin(θ2)*cos(ϕ1 - ϕ2),-1,1))

    """
    See [`arc_between_θϕ`](@ref).
    """
    arc_between_θφ(θ1::Real,φ1::Real,θ2::Real,φ2::Real)=arc_between_θϕ(θ1,φ1,θ2,φ2)
    """
    ```julia
    function arc_between_QP(Q1,P1,Q2,P2)
    ```
    Returns
    ```julia
        arc_between_θϕ(θ_of_QP(Q1,P1),ϕ_of_QP(Q1,P1),θ_of_QP(Q2,P2),ϕ_of_QP(Q2,P2)).
    ```
    """
    arc_between_QP(Q1::Real,P1::Real,Q2::Real,P2::Real)=arc_between_θϕ(θ_of_QP(Q1,P1),ϕ_of_QP(Q1,P1),θ_of_QP(Q2,P2),ϕ_of_QP(Q2,P2))
end


text:
# Julia wrapper for header: /usr/local/include/libavformat/avio.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

export
    url_poll,
    url_open_protocol,
    url_alloc,
    url_connect,
    url_open,
    url_read,
    url_read_complete,
    url_write,
    url_seek,
    url_close,
    url_filesize,
    url_get_file_handle,
    url_get_max_packet_size,
    url_get_filename,
    av_url_read_pause,
    av_url_read_seek,
    url_set_interrupt_cb,
    av_protocol_next,
    av_register_protocol2,
    init_put_byte,
    av_alloc_put_byte,
    get_buffer,
    get_partial_buffer,
    get_byte,
    get_le16,
    get_le24,
    get_le32,
    get_le64,
    get_be16,
    get_be24,
    get_be32,
    get_be64,
    put_byte,
    put_nbyte,
    put_buffer,
    put_le64,
    put_be64,
    put_le32,
    put_be32,
    put_le24,
    put_be24,
    put_le16,
    put_be16,
    put_tag,
    av_url_read_fpause,
    av_url_read_fseek,
    url_fopen,
    url_fclose,
    url_fseek,
    url_fskip,
    url_ftell,
    url_fsize,
    url_fgetc,
    url_setbufsize,
    put_flush_packet,
    url_open_dyn_buf,
    url_open_dyn_packet_buf,
    url_close_dyn_buf,
    url_fdopen,
    url_feof,
    url_ferror,
    udp_set_remote_url,
    udp_get_local_port,
    init_checksum,
    get_checksum,
    put_strz,
    url_fgets,
    get_strz,
    url_is_streamed,
    url_fileno,
    url_fget_max_packet_size,
    url_open_buf,
    url_close_buf,
    url_exist,
    avio_check,
    avio_set_interrupt_cb,
    avio_alloc_context,
    avio_w8,
    avio_write,
    avio_wl64,
    avio_wb64,
    avio_wl32,
    avio_wb32,
    avio_wl24,
    avio_wb24,
    avio_wl16,
    avio_wb16,
    avio_put_str,
    avio_put_str16le,
    avio_seek,
    avio_skip,
    avio_tell,
    avio_size,
    avio_flush,
    avio_read,
    avio_r8,
    avio_rl16,
    avio_rl24,
    avio_rl32,
    avio_rl64,
    avio_rb16,
    avio_rb24,
    avio_rb32,
    avio_rb64,
    avio_get_str,
    avio_get_str16le,
    avio_get_str16be,
    avio_open,
    avio_open2,
    avio_close,
    avio_open_dyn_buf,
    avio_close_dyn_buf,
    avio_enum_protocols,
    avio_pause,
    avio_seek_time

function url_poll(poll_table,n::Integer,timeout::Integer)
    ccall((:url_poll,libavformat),Cint,(Ptr{URLPollEntry},Cint,Cint),poll_table,n,timeout)
end

function url_open_protocol(puc,up,url,flags::Integer)
    ccall((:url_open_protocol,libavformat),Cint,(Ptr{Ptr{URLContext}},Ptr{URLProtocol},Ptr{Uint8},Cint),puc,up,url,flags)
end

function url_alloc(h,url,flags::Integer)
    ccall((:url_alloc,libavformat),Cint,(Ptr{Ptr{URLContext}},Ptr{Uint8},Cint),h,url,flags)
end

function url_connect(h)
    ccall((:url_connect,libavformat),Cint,(Ptr{URLContext},),h)
end

function url_open(h,url,flags::Integer)
    ccall((:url_open,libavformat),Cint,(Ptr{Ptr{URLContext}},Ptr{Uint8},Cint),h,url,flags)
end

function url_read(h,buf,size::Integer)
    ccall((:url_read,libavformat),Cint,(Ptr{URLContext},Ptr{Cuchar},Cint),h,buf,size)
end

function url_read_complete(h,buf,size::Integer)
    ccall((:url_read_complete,libavformat),Cint,(Ptr{URLContext},Ptr{Cuchar},Cint),h,buf,size)
end

function url_write(h,buf,size::Integer)
    ccall((:url_write,libavformat),Cint,(Ptr{URLContext},Ptr{Cuchar},Cint),h,buf,size)
end

function url_seek(h,pos::Int64,whence::Integer)
    ccall((:url_seek,libavformat),Int64,(Ptr{URLContext},Int64,Cint),h,pos,whence)
end

function url_close(h)
    ccall((:url_close,libavformat),Cint,(Ptr{URLContext},),h)
end

function url_filesize(h)
    ccall((:url_filesize,libavformat),Int64,(Ptr{URLContext},),h)
end

function url_get_file_handle(h)
    ccall((:url_get_file_handle,libavformat),Cint,(Ptr{URLContext},),h)
end

function url_get_max_packet_size(h)
    ccall((:url_get_max_packet_size,libavformat),Cint,(Ptr{URLContext},),h)
end

function url_get_filename(h,buf,buf_size::Integer)
    ccall((:url_get_filename,libavformat),Void,(Ptr{URLContext},Ptr{Uint8},Cint),h,buf,buf_size)
end

function av_url_read_pause(h,pause::Integer)
    ccall((:av_url_read_pause,libavformat),Cint,(Ptr{URLContext},Cint),h,pause)
end

function av_url_read_seek(h,stream_index::Integer,timestamp::Int64,flags::Integer)
    ccall((:av_url_read_seek,libavformat),Int64,(Ptr{URLContext},Cint,Int64,Cint),h,stream_index,timestamp,flags)
end

function url_set_interrupt_cb(interrupt_cb)
    ccall((:url_set_interrupt_cb,libavformat),Void,(Ptr{Void},),interrupt_cb)
end

function av_protocol_next(p)
    ccall((:av_protocol_next,libavformat),Ptr{URLProtocol},(Ptr{URLProtocol},),p)
end

function av_register_protocol2(protocol,size::Integer)
    ccall((:av_register_protocol2,libavformat),Cint,(Ptr{URLProtocol},Cint),protocol,size)
end

function init_put_byte(s,buffer,buffer_size::Integer,write_flag::Integer,opaque,read_packet,write_packet,seek)
    ccall((:init_put_byte,libavformat),Cint,(Ptr{AVIOContext},Ptr{Cuchar},Cint,Cint,Ptr{Void},Ptr{Void},Ptr{Void},Ptr{Void}),s,buffer,buffer_size,write_flag,opaque,read_packet,write_packet,seek)
end

function av_alloc_put_byte(buffer,buffer_size::Integer,write_flag::Integer,opaque,read_packet,write_packet,seek)
    ccall((:av_alloc_put_byte,libavformat),Ptr{AVIOContext},(Ptr{Cuchar},Cint,Cint,Ptr{Void},Ptr{Void},Ptr{Void},Ptr{Void}),buffer,buffer_size,write_flag,opaque,read_packet,write_packet,seek)
end

function get_buffer(s,buf,size::Integer)
    ccall((:get_buffer,libavformat),Cint,(Ptr{AVIOContext},Ptr{Cuchar},Cint),s,buf,size)
end

function get_partial_buffer(s,buf,size::Integer)
    ccall((:get_partial_buffer,libavformat),Cint,(Ptr{AVIOContext},Ptr{Cuchar},Cint),s,buf,size)
end

function get_byte(s)
    ccall((:get_byte,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function get_le16(s)
    ccall((:get_le16,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function get_le24(s)
    ccall((:get_le24,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function get_le32(s)
    ccall((:get_le32,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function get_le64(s)
    ccall((:get_le64,libavformat),Uint64,(Ptr{AVIOContext},),s)
end

function get_be16(s)
    ccall((:get_be16,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function get_be24(s)
    ccall((:get_be24,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function get_be32(s)
    ccall((:get_be32,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function get_be64(s)
    ccall((:get_be64,libavformat),Uint64,(Ptr{AVIOContext},),s)
end

function put_byte(s,b::Integer)
    ccall((:put_byte,libavformat),Void,(Ptr{AVIOContext},Cint),s,b)
end

function put_nbyte(s,b::Integer,count::Integer)
    ccall((:put_nbyte,libavformat),Void,(Ptr{AVIOContext},Cint,Cint),s,b,count)
end

function put_buffer(s,buf,size::Integer)
    ccall((:put_buffer,libavformat),Void,(Ptr{AVIOContext},Ptr{Cuchar},Cint),s,buf,size)
end

function put_le64(s,val::Uint64)
    ccall((:put_le64,libavformat),Void,(Ptr{AVIOContext},Uint64),s,val)
end

function put_be64(s,val::Uint64)
    ccall((:put_be64,libavformat),Void,(Ptr{AVIOContext},Uint64),s,val)
end

function put_le32(s,val::Integer)
    ccall((:put_le32,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function put_be32(s,val::Integer)
    ccall((:put_be32,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function put_le24(s,val::Integer)
    ccall((:put_le24,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function put_be24(s,val::Integer)
    ccall((:put_be24,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function put_le16(s,val::Integer)
    ccall((:put_le16,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function put_be16(s,val::Integer)
    ccall((:put_be16,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function put_tag(s,tag)
    ccall((:put_tag,libavformat),Void,(Ptr{AVIOContext},Ptr{Uint8}),s,tag)
end

function av_url_read_fpause(h,pause::Integer)
    ccall((:av_url_read_fpause,libavformat),Cint,(Ptr{AVIOContext},Cint),h,pause)
end

function av_url_read_fseek(h,stream_index::Integer,timestamp::Int64,flags::Integer)
    ccall((:av_url_read_fseek,libavformat),Int64,(Ptr{AVIOContext},Cint,Int64,Cint),h,stream_index,timestamp,flags)
end

function url_fopen(s,url,flags::Integer)
    ccall((:url_fopen,libavformat),Cint,(Ptr{Ptr{AVIOContext}},Ptr{Uint8},Cint),s,url,flags)
end

function url_fclose(s)
    ccall((:url_fclose,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function url_fseek(s,offset::Int64,whence::Integer)
    ccall((:url_fseek,libavformat),Int64,(Ptr{AVIOContext},Int64,Cint),s,offset,whence)
end

function url_fskip(s,offset::Int64)
    ccall((:url_fskip,libavformat),Cint,(Ptr{AVIOContext},Int64),s,offset)
end

function url_ftell(s)
    ccall((:url_ftell,libavformat),Int64,(Ptr{AVIOContext},),s)
end

function url_fsize(s)
    ccall((:url_fsize,libavformat),Int64,(Ptr{AVIOContext},),s)
end

function url_fgetc(s)
    ccall((:url_fgetc,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function url_setbufsize(s,buf_size::Integer)
    ccall((:url_setbufsize,libavformat),Cint,(Ptr{AVIOContext},Cint),s,buf_size)
end

function put_flush_packet(s)
    ccall((:put_flush_packet,libavformat),Void,(Ptr{AVIOContext},),s)
end

function url_open_dyn_buf(s)
    ccall((:url_open_dyn_buf,libavformat),Cint,(Ptr{Ptr{AVIOContext}},),s)
end

function url_open_dyn_packet_buf(s,max_packet_size::Integer)
    ccall((:url_open_dyn_packet_buf,libavformat),Cint,(Ptr{Ptr{AVIOContext}},Cint),s,max_packet_size)
end

function url_close_dyn_buf(s,pbuffer)
    ccall((:url_close_dyn_buf,libavformat),Cint,(Ptr{AVIOContext},Ptr{Ptr{Uint8}}),s,pbuffer)
end

function url_fdopen(s,h)
    ccall((:url_fdopen,libavformat),Cint,(Ptr{Ptr{AVIOContext}},Ptr{URLContext}),s,h)
end

function url_feof(s)
    ccall((:url_feof,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function url_ferror(s)
    ccall((:url_ferror,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function udp_set_remote_url(h,uri)
    ccall((:udp_set_remote_url,libavformat),Cint,(Ptr{URLContext},Ptr{Uint8}),h,uri)
end

function udp_get_local_port(h)
    ccall((:udp_get_local_port,libavformat),Cint,(Ptr{URLContext},),h)
end

function init_checksum(s,update_checksum,checksum::Culong)
    ccall((:init_checksum,libavformat),Void,(Ptr{AVIOContext},Ptr{Void},Culong),s,update_checksum,checksum)
end

function get_checksum(s)
    ccall((:get_checksum,libavformat),Culong,(Ptr{AVIOContext},),s)
end

function put_strz(s,buf)
    ccall((:put_strz,libavformat),Void,(Ptr{AVIOContext},Ptr{Uint8}),s,buf)
end

function url_fgets(s,buf,buf_size::Integer)
    ccall((:url_fgets,libavformat),Ptr{Uint8},(Ptr{AVIOContext},Ptr{Uint8},Cint),s,buf,buf_size)
end

function get_strz(s,buf,maxlen::Integer)
    ccall((:get_strz,libavformat),Ptr{Uint8},(Ptr{AVIOContext},Ptr{Uint8},Cint),s,buf,maxlen)
end

function url_is_streamed(s)
    ccall((:url_is_streamed,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function url_fileno(s)
    ccall((:url_fileno,libavformat),Ptr{URLContext},(Ptr{AVIOContext},),s)
end

function url_fget_max_packet_size(s)
    ccall((:url_fget_max_packet_size,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function url_open_buf(s,buf,buf_size::Integer,flags::Integer)
    ccall((:url_open_buf,libavformat),Cint,(Ptr{Ptr{AVIOContext}},Ptr{Uint8},Cint,Cint),s,buf,buf_size,flags)
end

function url_close_buf(s)
    ccall((:url_close_buf,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function url_exist(url)
    ccall((:url_exist,libavformat),Cint,(Ptr{Uint8},),url)
end

function avio_check(url,flags::Integer)
    ccall((:avio_check,libavformat),Cint,(Ptr{Uint8},Cint),url,flags)
end

function avio_set_interrupt_cb(interrupt_cb)
    ccall((:avio_set_interrupt_cb,libavformat),Void,(Ptr{Void},),interrupt_cb)
end

function avio_alloc_context(buffer,buffer_size::Integer,write_flag::Integer,opaque,read_packet,write_packet,seek)
    ccall((:avio_alloc_context,libavformat),Ptr{AVIOContext},(Ptr{Cuchar},Cint,Cint,Ptr{Void},Ptr{Void},Ptr{Void},Ptr{Void}),buffer,buffer_size,write_flag,opaque,read_packet,write_packet,seek)
end

function avio_w8(s,b::Integer)
    ccall((:avio_w8,libavformat),Void,(Ptr{AVIOContext},Cint),s,b)
end

function avio_write(s,buf,size::Integer)
    ccall((:avio_write,libavformat),Void,(Ptr{AVIOContext},Ptr{Cuchar},Cint),s,buf,size)
end

function avio_wl64(s,val::Uint64)
    ccall((:avio_wl64,libavformat),Void,(Ptr{AVIOContext},Uint64),s,val)
end

function avio_wb64(s,val::Uint64)
    ccall((:avio_wb64,libavformat),Void,(Ptr{AVIOContext},Uint64),s,val)
end

function avio_wl32(s,val::Integer)
    ccall((:avio_wl32,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function avio_wb32(s,val::Integer)
    ccall((:avio_wb32,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function avio_wl24(s,val::Integer)
    ccall((:avio_wl24,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function avio_wb24(s,val::Integer)
    ccall((:avio_wb24,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function avio_wl16(s,val::Integer)
    ccall((:avio_wl16,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function avio_wb16(s,val::Integer)
    ccall((:avio_wb16,libavformat),Void,(Ptr{AVIOContext},Uint32),s,val)
end

function avio_put_str(s,str)
    ccall((:avio_put_str,libavformat),Cint,(Ptr{AVIOContext},Ptr{Uint8}),s,str)
end

function avio_put_str16le(s,str)
    ccall((:avio_put_str16le,libavformat),Cint,(Ptr{AVIOContext},Ptr{Uint8}),s,str)
end

function avio_seek(s,offset::Int64,whence::Integer)
    ccall((:avio_seek,libavformat),Int64,(Ptr{AVIOContext},Int64,Cint),s,offset,whence)
end

function avio_skip(s,offset::Int64)
    ccall((:avio_skip,libavformat),Int64,(Ptr{AVIOContext},Int64),s,offset)
end

function avio_tell(s)
    ccall((:avio_tell,libavformat),Int64,(Ptr{AVIOContext},),s)
end

function avio_size(s)
    ccall((:avio_size,libavformat),Int64,(Ptr{AVIOContext},),s)
end

function avio_flush(s)
    ccall((:avio_flush,libavformat),Void,(Ptr{AVIOContext},),s)
end

function avio_read(s,buf,size::Integer)
    ccall((:avio_read,libavformat),Cint,(Ptr{AVIOContext},Ptr{Cuchar},Cint),s,buf,size)
end

function avio_r8(s)
    ccall((:avio_r8,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function avio_rl16(s)
    ccall((:avio_rl16,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function avio_rl24(s)
    ccall((:avio_rl24,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function avio_rl32(s)
    ccall((:avio_rl32,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function avio_rl64(s)
    ccall((:avio_rl64,libavformat),Uint64,(Ptr{AVIOContext},),s)
end

function avio_rb16(s)
    ccall((:avio_rb16,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function avio_rb24(s)
    ccall((:avio_rb24,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function avio_rb32(s)
    ccall((:avio_rb32,libavformat),Uint32,(Ptr{AVIOContext},),s)
end

function avio_rb64(s)
    ccall((:avio_rb64,libavformat),Uint64,(Ptr{AVIOContext},),s)
end

function avio_get_str(pb,maxlen::Integer,buf,buflen::Integer)
    ccall((:avio_get_str,libavformat),Cint,(Ptr{AVIOContext},Cint,Ptr{Uint8},Cint),pb,maxlen,buf,buflen)
end

function avio_get_str16le(pb,maxlen::Integer,buf,buflen::Integer)
    ccall((:avio_get_str16le,libavformat),Cint,(Ptr{AVIOContext},Cint,Ptr{Uint8},Cint),pb,maxlen,buf,buflen)
end

function avio_get_str16be(pb,maxlen::Integer,buf,buflen::Integer)
    ccall((:avio_get_str16be,libavformat),Cint,(Ptr{AVIOContext},Cint,Ptr{Uint8},Cint),pb,maxlen,buf,buflen)
end

function avio_open(s,url,flags::Integer)
    ccall((:avio_open,libavformat),Cint,(Ptr{Ptr{AVIOContext}},Ptr{Uint8},Cint),s,url,flags)
end

function avio_open2(s,url,flags::Integer,int_cb,options)
    ccall((:avio_open2,libavformat),Cint,(Ptr{Ptr{AVIOContext}},Ptr{Uint8},Cint,Ptr{AVIOInterruptCB},Ptr{Ptr{AVDictionary}}),s,url,flags,int_cb,options)
end

function avio_close(s)
    ccall((:avio_close,libavformat),Cint,(Ptr{AVIOContext},),s)
end

function avio_open_dyn_buf(s)
    ccall((:avio_open_dyn_buf,libavformat),Cint,(Ptr{Ptr{AVIOContext}},),s)
end

function avio_close_dyn_buf(s,pbuffer)
    ccall((:avio_close_dyn_buf,libavformat),Cint,(Ptr{AVIOContext},Ptr{Ptr{Uint8}}),s,pbuffer)
end

function avio_enum_protocols(opaque,output::Integer)
    ccall((:avio_enum_protocols,libavformat),Ptr{Uint8},(Ptr{Ptr{Void}},Cint),opaque,output)
end

function avio_pause(h,pause::Integer)
    ccall((:avio_pause,libavformat),Cint,(Ptr{AVIOContext},Cint),h,pause)
end

function avio_seek_time(h,stream_index::Integer,timestamp::Int64,flags::Integer)
    ccall((:avio_seek_time,libavformat),Int64,(Ptr{AVIOContext},Cint,Int64,Cint),h,stream_index,timestamp,flags)
end


text:
"""
Example demonstrating the usage of the IEX package.

Downloads historical TOPS feeds from IEX and extracts trade events to parquet files.

Change the PARQUET_DIR constant to adjust the output file.
"""

import Base: Threads
import InvestorsExchange as IEX
import Logging
import Parquet: write_parquet
import Pkg

# add additional non-IEX dependencies
Pkg.add(["Logging", "Parquet"])

# this is the output directory for parquet files containing the trade messages
#  defaults to "./trade_data" if no argument passed
const PARQUET_DIR = isempty(ARGS) ? "./trade_data" : ARGS[1]

# set up console loggingogging
logger = Logging.ConsoleLogger()
Logging.global_logger(logger)

# define methods for downloading and parsing PCAP files in an efficient, parallelized manner
function rewrite_trades(in_filepath::String, out_filepath::String)::Union{String, Nothing}
    trade_messages = IEX.read_trade_report_messages(in_filepath; show_progress_bar=false)
    rm(in_filepath)
    df = IEX.assemble_trade_report_frame(trade_messages)
    if nrow(df) > 0
        write_parquet(out_filepath, df)
        return out_filepath
    end
    return nothing
end

function async_download(download_links, out_dir, out_filepath_channel)
    for link in download_links
        @Logging.info "Downloading from $link"
        filepath = IEX.download_file(link, out_dir; show_progress_bar=false)
        @Logging.info "Completed download of $filepath"
        push!(out_filepath_channel, filepath)
    end
    # signal the end
    push!(out_filepath_channel, nothing)
end

#### actually kick off the downloading! ####
try mkdir(PARQUET_DIR) catch end

# get list of all TOPS 1.6 download links, filtering out those already downloaded
downloaded_dates = Set(filepath[1:8] for filepath in readdir(PARQUET_DIR))
pay = IEX.query_hist_filenames()
download_links = String[]
dates = sort(collect(keys(pay)); rev=true)
for d in dates
    if d in downloaded_dates
        continue
    end
    for blob in pay[d]
        if blob["feed"] == "TOPS" && blob["version"] == "1.6"
            push!(download_links, blob["link"])
        end
    end
end
@Logging.info "Found $(length(download_links)) un-downloaded days to download."

# Using an async process, download files up to a maximum of K waiting to be processed
dl_filepaths = Channel(2)  # Threads.nthreads() + 2 files on disk in worst case
pcap_dir = joinpath(tempdir(), "tmp_iex_download")
try mkdir(pcap_dir) catch end
@Logging.info "Downloading PCAP files to $pcap_dir"
@async async_download(download_links, pcap_dir, dl_filepaths)

# using threads, read trade data from downloaded files, save trade data, and delete files
@Logging.info "Extracting trades to parquet files in $PARQUET_DIR"
thread_results = []
while true
    in_filepath = take!(dl_filepaths)
    if in_filepath === nothing
        break
    end
    out_filename = splitext(splitext(basename(in_filepath))[1])[1] * ".parquet"
    out_filepath = joinpath(PARQUET_DIR, out_filename)
    @Logging.info("Spawning worker thread to rewrite $in_filepath to $out_filepath")
    res = @Threads.spawn rewrite_trades(in_filepath, out_filepath)
    pushfirst!(thread_results, res)
end
while length(thread_results) > 0
    wait(pop!(thread_results))
end
rm(pcap_dir, recursive=true)


text:
abstract type DiffEvoCrossoverOperator{NP,NC} <: CrossoverOperator{NP,NC} end

# FIXME is it possible somehow to do arithmetic operations with N?
struct DiffEvoRandBin{N} <: DiffEvoCrossoverOperator{N,1}
    cr::Float64   # probability to crossover the dimension
    f::Float64    # scale parameter

    DiffEvoRandBin{N}(cr::Number, f::Number) where N = new{N}(cr, f)
    DiffEvoRandBin{N}(options::Parameters) where N = new{N}(options[:DEX_cr], options[:DEX_f])
end

const DEX_DefaultOptions = ParamsDict(
    :DEX_f => 0.6,
    :DEX_cr => 0.7
)

crossover_parameters(xover::DiffEvoRandBin, pop, target_index) = xover.cr, xover.f

const DiffEvoRandBin1 = DiffEvoRandBin{3}
const DiffEvoRandBin2 = DiffEvoRandBin{5}

function apply!(xover::DiffEvoCrossoverOperator{3,1},
                target, target_index::Int, pop, parentIndices)
    @assert length(parentIndices) == 3
    cr, f = crossover_parameters(xover, pop, target_index)
    p1ix, p2ix, p3ix = parentIndices
    # Always ensure at least one parameter is xovered
    mut_ix = rand(1:length(target))
    @inbounds for i in 1:length(target)
        if i == mut_ix || rand() <= cr
            target[i] = pop[i,p3ix] + f * (pop[i,p1ix] - pop[i,p2ix])
        elseif target_index == 0
            target[i] = pop[i,p3ix]
        end
    end
    return target
end

function apply!(xover::DiffEvoCrossoverOperator{5,1},
                target, target_index::Int, pop, parentIndices)
    @assert length(parentIndices) == 5
    cr, f = crossover_parameters(xover, pop, target_index)
    p1ix, p2ix, p3ix, p4ix, p5ix = parentIndices
    # Always ensure at least one parameter is xovered
    mut_ix = rand(1:length(target))
    @inbounds for i in 1:length(target)
        if i == mut_ix || rand() <= cr
            target[i] = pop[i,p3ix] +
                f * (pop[i,p1ix] - pop[i,p2ix]) +
                f * (pop[i,p4ix] - pop[i,p5ix])
        elseif target_index == 0
            target[i] = pop[i,p3ix]
        end
    end
    return target
end


text:
#   This file is part of UnitSystems.jl
#   It is licensed under the MIT license
#   UnitSystems Copyright (C) 2021 Michael Reed
#       _           _                         _
#      | |         | |                       | |
#   ___| |__   __ _| | ___ __ __ ___   ____ _| | __ _
#  / __| '_ \ / _` | |/ / '__/ _` \ \ / / _` | |/ _` |
# | (__| | | | (_| |   <| | | (_| |\ V / (_| | | (_| |
#  \___|_| |_|\__,_|_|\_\_|  \__,_| \_/ \__,_|_|\__,_|
#
#   https://github.com/chakravala
#   https://crucialflow.com

export deka,hecto,kilo,mega,giga,tera,peta,exa,zetta,yotta
export deci,centi,milli,micro,nano,pico,femto,atto,zepto,yocto
export byte,kibi,mebi,gibi,tebi,pebi,exbi,zebi,yobi

export slug, ft, KJ1990, KJ2014, RK1990, RK2014, mₑ1990, mₑ2014, temp, units, °R, T₀, eV
export slugs, kilograms, lbm, meters, feet, rankine, kelvin, moles, molecules, universal
export Universe, UnitSystem, US, universe, HOUR, DAY, th, lc, mc, tcq, lcq, mcq
export similitude, 𝟙, F, M, L, T, Q, Θ, N, J, A, Λ, C, sackurtetrode
export °R, τ, 𝟏𝟎, 𝟐, 𝟑, 𝟓, nm, 𝟏, mₑ, μ₀, Mᵤ, Rᵤ, αG, GG, slug, ħ, μₚₑ, αL, 𝟕, 𝟏𝟏, 𝟏𝟗, 𝟒𝟑

const EMU2019,ESU2019,stiffness = EMU,ESU,fluence

# == Metric is different
const eV = electronvolt(SI2019)
const κ = einstein(SI2019)
const σ = stefan(SI2019) #
const μB = magneton(SI2019) #
const ε₀ = vacuumpermittivity(SI2019) #
const kₑ = electrostatic(SI2019) #
const mₚ = protonmass(SI2019)
const mᵤ = atomicmass(SI2019)
const 𝔉 = faraday(SI2019) #
const Φ₀ = magneticfluxquantum(SI2019) #
const Z₀ = vacuumimpedance(SI2019) #
const G₀ = conductancequantum(SI2019) #
const Eₕ = hartree(SI2019)
const a₀ = bohr(SI2019)
const rₑ = electronradius(SI2019)
const RH,Ry = R∞*mₚ/(electronmass(SI2019)+mₚ),𝘩*𝘤*R∞

const ℓP = length(PlanckGauss,SI2019)
const tP = time(PlanckGauss,SI2019)
const TP = temperature(PlanckGauss,SI2019)

const lS = length(Stoney,SI2019)
const tS = time(Stoney,SI2019)
const mS = mass(Stoney,SI2019)
const qS = charge(Stoney,SI2019)

const lA = length(Hartree,SI2019)
const tA = time(Hartree,SI2019)
const mA = mass(Hartree,SI2019)
const qA = charge(Hartree,SI2019)

const lQCD = length(QCD,SI2019)
const tQCD = time(QCD,SI2019)
const mQCD = mass(QCD,SI2019)

# non standard units

const BTU = thermalunit(British)
const BTUftlb = thermalunit(British) # BTU⋅ft⁻¹⋅lb⁻¹
const BTUJ = thermalunit(SI2019) # BTU⋅J⁻¹
const HP = horsepower(Metric)
const gal = gallon(Metric)
const kcal = kilocalorie(SI2019)
const cal = calorie(SI2019)
const universal = molargas

# constant aliases

const US,mpe, meu, mpu, ainv, aG = UnitSystem,μₚₑ, μₑᵤ, μₚᵤ, αinv, αG
const Mu,Ru,SB,hh,cc,m0,e0,ke,me,mp,mu,ee,FF,Z0,G0,Eh,a0,re,g0,lP,aL,ϵ₀ = Mᵤ,Rᵤ,σ,𝘩,𝘤,μ₀,ε₀,kₑ,mₑ,mₚ,mᵤ,𝘦,𝔉,Z₀,G₀,Eₕ,a₀,rₑ,g₀,ℓP,αL,ε₀
export κ, G, GG, NA, kB, Rᵤ, σ, 𝘩, ħ, 𝘤, μ₀, ε₀, kₑ, mₑ, mₚ, mᵤ, 𝘦, 𝔉, Φ₀, Z₀, G₀, Eₕ, R∞, a₀, rₑ, KJ, RK, Ru, SB, hh, cc, m0, e0, ke, me, mp, mu, ee, FF, Z0, G0, Eh, a0, re, μB
export αG, αinv, μₚₑ, μₑᵤ, μₚᵤ, mpe, meu, mpu, mP, δμ₀, Mᵤ, Mu, RH, Ry, ΔνCs, Kcd, ainv
export cal, kcal, calₜₕ, kcalₜₕ, calᵢₜ, kcalᵢₜ, ℓP, g₀, g0, atm, lbm, BTUJ, BTUftlb, aG
export lP, tP, TP, lS, tS, mS, qS, lA, tA, mA, qA, lQCD, tQCD, mQCD, ϵ₀, αL, aL

@doc """
    Constant{D} <: Real

Numerical constant `D` used in `UnitSystem` derivations.
```Julia
julia> Constant(100)
$(Constant(100))
```
Can be multiplied, added, subtracted, and so on.
""" Constant

# engineering unit systems docs

@doc """
    Metric = MetricSystem(milli,𝟐*τ/𝟏𝟎^7)

Standard `Metric` system based on exact `molarmass` and `vacuumpermeability`.

```Julia
julia> boltzmann(Metric) # J⋅K⁻¹
$(boltzmann(Metric))

julia> planckreduced(Metric) # J⋅s⋅rad⁻¹
$(planckreduced(Metric))

julia> lightspeed(Metric) # m⋅s⁻¹
$(lightspeed(Metric))

julia> vacuumpermeability(Metric) # H⋅m⁻¹
$(vacuumpermeability(Metric))

julia> electronmass(Metric) # kg
$(electronmass(Metric))

julia> molarmass(Metric) # kg⋅mol⁻¹
$(molarmass(Metric))

julia> luminousefficacy(Metric) # lm⋅W⁻¹
$(luminousefficacy(Metric))
```
""" Metric, MKS

@doc """
    SI2019 = MetricSystem(Mᵤ,μ₀)

Systeme International d'Unites based on approximate `molarmass` and `vacuumpermeability`.

```Julia
julia> boltzmann(SI2019) # J⋅K⁻¹
$(boltzmann(SI2019))

julia> planckreduced(SI2019) # J⋅s⋅rad⁻¹
$(planckreduced(SI2019))

julia> lightspeed(SI2019) # m⋅s⁻¹
$(lightspeed(SI2019))

julia> vacuumpermeability(SI2019) # H⋅m⁻¹
$(vacuumpermeability(SI2019))

julia> electronmass(SI2019) # kg
$(electronmass(SI2019))

julia> molarmass(SI2019) # kg⋅mol⁻¹
$(molarmass(SI2019))

julia> luminousefficacy(SI2019) # lm⋅W⁻¹
$(luminousefficacy(SI2019))
```
""" SI2019, SI

@doc """
    MetricEngineering = MetricSystem(milli,𝟐*τ/𝟏𝟎^7,Rᵤ,g₀)

Standard `MetricEngineering` system based on kilogram and kilopond (kilogram-force) units.

```Julia
julia> boltzmann(MetricEngineering) # kgf⋅m⋅K⁻¹
$(boltzmann(MetricEngineering))

julia> planckreduced(MetricEngineering) # kgf⋅m⋅s⋅rad⁻¹
$(planckreduced(MetricEngineering))

julia> lightspeed(MetricEngineering) # m⋅s⁻¹
$(lightspeed(MetricEngineering))

julia> vacuumpermeability(MetricEngineering) # kgf⋅s²⋅C⁻²
$(vacuumpermeability(MetricEngineering))

julia> electronmass(MetricEngineering) # kg
$(electronmass(MetricEngineering))

julia> molarmass(MetricEngineering) # kg⋅mol⁻¹
$(molarmass(MetricEngineering))

julia> luminousefficacy(MetricEngineering) # lm⋅s⋅m⁻¹⋅kgf⁻¹
$(luminousefficacy(MetricEngineering))

julia> gravity(MetricEngineering) # kg⋅m⋅kgf⁻¹⋅s⁻²
$(gravity(MetricEngineering))
```
""" MetricEngineering, ME

@doc """
    SI2019Engineering = MetricSystem(Mᵤ,μ₀,Rᵤ,g₀)

Systeme International d'Unites based on kilogram and kilopond (kilogram-force) units.

```Julia
julia> boltzmann(SI2019Engineering) # kgf⋅m⋅K⁻¹
$(boltzmann(SI2019Engineering))

julia> planckreduced(SI2019Engineering) # kgf⋅m⋅s⋅rad⁻¹
$(planckreduced(SI2019Engineering))

julia> lightspeed(SI2019Engineering) # m⋅s⁻¹
$(lightspeed(SI2019Engineering))

julia> vacuumpermeability(SI2019Engineering) # kgf⋅s²⋅C⁻²
$(vacuumpermeability(SI2019Engineering))

julia> electronmass(SI2019Engineering) # kg
$(electronmass(SI2019Engineering))

julia> molarmass(SI2019Engineering) # kg⋅mol⁻¹
$(molarmass(SI2019Engineering))

julia> luminousefficacy(SI2019Engineering) # lm⋅s⋅m⁻¹⋅kgf⁻¹
$(luminousefficacy(SI2019Engineering))

julia> gravity(SI2019Engineering) # kg⋅m⋅kgf⁻¹⋅s⁻²
$(gravity(SI2019Engineering))
```
""" SI2019Engineering, SIE

@doc """
    SI1976 = MetricSystem(milli,𝟐*τ/𝟏𝟎^7,8.31432)

Reference `UnitSystem` with universal gas constant of `8.31432` from 1976 standard atmosphere.

```Julia
julia> boltzmann(SI1976) # J⋅K⁻¹
$(boltzmann(SI1976))

julia> planckreduced(SI1976) # J⋅s⋅rad⁻¹
$(planckreduced(SI1976))

julia> lightspeed(SI1976) # m⋅s⁻¹
$(lightspeed(SI1976))

julia> vacuumpermeability(SI1976) # H⋅m⁻¹
$(vacuumpermeability(SI1976))

julia> electronmass(SI1976) # kg
$(electronmass(SI1976))

julia> molarmass(SI1976) # kg⋅mol⁻¹
$(molarmass(SI1976))

julia> luminousefficacy(SI1976) # lm⋅W⁻¹
$(luminousefficacy(SI1976))
```
""" SI1976

@doc """
    CODATA = ConventionalSystem(RK2014,KJ2014,Rᵤ2014)

Reference `UnitSystem` based on Committee on Data of the International Science Council.

```Julia
julia> josephson(CODATA) # Hz⋅V⁻¹
$(josephson(CODATA))

julia> klitzing(CODATA) # Ω
$(klitzing(CODATA))

julia> boltzmann(CODATA) # J⋅K⁻¹
$(boltzmann(CODATA))

julia> planckreduced(CODATA) # J⋅s⋅rad⁻¹
$(planckreduced(CODATA))

julia> lightspeed(CODATA) # m⋅s⁻¹
$(lightspeed(CODATA))

julia> vacuumpermeability(CODATA) # H⋅m⁻¹
$(vacuumpermeability(CODATA))

julia> electronmass(CODATA) # kg
$(electronmass(CODATA))

julia> molarmass(CODATA) # kg⋅mol⁻¹
$(molarmass(CODATA))

julia> luminousefficacy(CODATA) # lm⋅W⁻¹
$(luminousefficacy(CODATA))
```
""" CODATA

@doc """
    Conventional = ConventionalSystem(RK1990,KJ2014)

Conventional electronic `UnitSystem` with 1990 tuned `josephson` and `klitzing` constants.

```Julia
julia> josephson(Conventional) # Hz⋅V⁻¹
$(josephson(Conventional))

julia> klitzing(Conventional) # Ω
$(klitzing(Conventional))

julia> boltzmann(Conventional) # J⋅K⁻¹
$(boltzmann(Conventional))

julia> planckreduced(Conventional) # J⋅s⋅rad⁻¹
$(planckreduced(Conventional))

julia> lightspeed(Conventional) # m⋅s⁻¹
$(lightspeed(Conventional))

julia> vacuumpermeability(Conventional) # H⋅m⁻¹
$(vacuumpermeability(Conventional))

julia> electronmass(Conventional) # kg
$(electronmass(Conventional))

julia> molarmass(Conventional) # kg⋅mol⁻¹
$(molarmass(Conventional))

julia> luminousefficacy(Conventional) # lm⋅W⁻¹
$(luminousefficacy(Conventional))
```
""" Conventional

@doc """
    International = ElectricSystem(Metric,$Ωᵢₜ,$Vᵢₜ)

International `UnitSystem` with United States measurements of `Ωᵢₜ` and `Vᵢₜ`.

```Julia
julia> resistance(International,Metric) # Ω⋅Ω⁻¹
$(resistance(International,Metric))

julia> electricpotential(International,Metric) # V⋅V⁻¹
$(electricpotential(International,Metric))

julia> boltzmann(International) # J⋅K⁻¹
$(boltzmann(International))

julia> planckreduced(International) # J⋅s⋅rad⁻¹
$(planckreduced(International))

julia> lightspeed(International) # m⋅s⁻¹
$(lightspeed(International))

julia> vacuumpermeability(International) # H⋅m⁻¹
$(vacuumpermeability(International))

julia> electronmass(International) # kg
$(electronmass(International))

julia> molarmass(International) # kg⋅mol⁻¹
$(molarmass(International))

julia> luminousefficacy(International) # lm⋅W⁻¹
$(luminousefficacy(International))
```
""" International

@doc """
    InternationalMean = ElectricSystem(Metric,1.00049,1.00034)

International `UnitSystem` with mean measurements of `Ωᵢₜ` and `Vᵢₜ`.

```Julia
julia> resistance(InternationalMean,Metric) # Ω⋅Ω⁻¹
$(resistance(InternationalMean,Metric))

julia> electricpotential(InternationalMean,Metric) # V⋅V⁻¹
$(electricpotential(InternationalMean,Metric))

julia> boltzmann(InternationalMean) # J⋅K⁻¹
$(boltzmann(InternationalMean))

julia> planckreduced(InternationalMean) # J⋅s⋅rad⁻¹
$(planckreduced(InternationalMean))

julia> lightspeed(InternationalMean) # m⋅s⁻¹
$(lightspeed(InternationalMean))

julia> vacuumpermeability(InternationalMean) # H⋅m⁻¹
$(vacuumpermeability(InternationalMean))

julia> electronmass(InternationalMean) # kg
$(electronmass(InternationalMean))

julia> molarmass(InternationalMean) # kg⋅mol⁻¹
$(molarmass(InternationalMean))

julia> luminousefficacy(International) # lm⋅W⁻¹
$(luminousefficacy(International))
```
""" InternationalMean

@doc """
    Meridian = EntropySystem(Metric,𝟏,em,em^3,𝟏,τ/𝟐^6/𝟓^7,milli)

Modern ideal `Meridian` system defined by France's original `earthmeter` definition.

```Julia
julia> greatcircle(Meridian) # em
$(greatcircle(Meridian))

julia> boltzmann(Meridian) # eJ⋅K⁻¹
$(boltzmann(Meridian))

julia> planckreduced(Meridian) # eJ⋅s⋅rad⁻¹
$(planckreduced(Meridian))

julia> lightspeed(Meridian) # em⋅s⁻¹
$(lightspeed(Meridian))

julia> vacuumpermeability(Meridian) # kegf⋅s²⋅eC⁻²
$(vacuumpermeability(Meridian))

julia> electronmass(Meridian) # keg
$(electronmass(Meridian))

julia> molarmass(Meridian) # keg⋅eg-mol⁻¹
$(molarmass(Meridian))

julia> luminousefficacy(Meridian) # lm⋅W⁻¹
$(luminousefficacy(Meridian))
```
""" Meridian

@doc """
    MeridianEngineering = EntropySystem(MetricEngineering,𝟏,em,em^3,𝟏,τ/𝟐^6/𝟓^7/g₀^2,milli)

Modern ideal engineering `UnitSystem` variant of the original French `Meridian` system.

```Julia
julia> greatcircle(MeridianEngineering) # em
$(greatcircle(MeridianEngineering))

julia> boltzmann(MeridianEngineering) # kegf⋅em⋅K⁻¹
$(boltzmann(MeridianEngineering))

julia> planckreduced(MeridianEngineering) # kegf⋅em⋅s⋅rad⁻¹
$(planckreduced(MeridianEngineering))

julia> lightspeed(MeridianEngineering) # em⋅s⁻¹
$(lightspeed(MeridianEngineering))

julia> vacuumpermeability(MeridianEngineering) # kegf⋅s²⋅eC⁻²
$(vacuumpermeability(MeridianEngineering))

julia> electronmass(MeridianEngineering) # keg
$(electronmass(MeridianEngineering))

julia> molarmass(MeridianEngineering) # keg⋅eg-mol⁻¹
$(molarmass(MeridianEngineering))

julia> luminousefficacy(MeridianEngineering) # lm⋅s⋅m⁻¹⋅kgf⁻¹
$(luminousefficacy(MeridianEngineering))

julia> gravity(MeridianEngineering) # keg⋅em⋅kegf⁻¹⋅s⁻²
$(gravity(MeridianEngineering))
```
""" MeridianEngineering

cgstext(US,AMP,cgs=eval(US)) = """
```Julia
julia> boltzmann($US) # erg⋅K⁻¹
$(boltzmann(cgs))

julia> planckreduced($US) # erg⋅s⋅rad⁻¹
$(planckreduced(cgs))

julia> lightspeed($US) # cm⋅s⁻¹
$(lightspeed(cgs))

julia> vacuumpermeability($US) # statH⋅cm⁻¹
$(vacuumpermeability(cgs))

julia> electronmass($US) # g
$(electronmass(cgs))

julia> molarmass($US) # g⋅mol⁻¹
$(molarmass(cgs))

julia> luminousefficacy($US) # lm⋅s⋅erg⁻¹
$(luminousefficacy(cgs))

julia> rationalization($US)
$(rationalization(cgs))
```
"""

for U ∈ (:CGSm,:CGSe,:EMU,:ESU)
    (EU,AMP) = QuoteNode.(U ∉ (:CGSe,:ESU) ? (:EMU,:Bi) : (:ESU,:statA))
@eval @doc """
    $($(QuoteNode(U))) = GaussSystem(Metric,$($EU≠:EMU ? "(𝟏𝟎*𝘤)^-2" : "𝟏"),𝟐*τ)

Centimetre-gram-second `UnitSystem` variant based on `$($EU)` (non-rationalized).

$(cgstext($(QuoteNode(U)),$AMP))
""" $U

#=U ∉ (:CGSm,:CGSe) && @eval @doc """
    $(Symbol($(QuoteNode(U)),:2019)) = EntropySystem(SI2019,𝟏,0.01,0.001,𝟏,$($EU≠:EMU ? "1e3*μ₀/𝘤^2" : "1e7*μ₀"))

Centimetre-gram-second `UnitSystem` variant of tuned `SI2019` based on `$($EU)` (rationalized).

$(cgstext(Symbol($(QuoteNode(U)),:2019),$AMP))
""" $(Symbol(U,:2019))=#
end

#=@doc """
    Thomson = GaussSystem(Metric,𝟏,𝟐*τ,𝟏/𝟐)

Centimetre-gram-second `UnitSystem` variant `Thomson` (EMU-Lorentz, non-rationalized).

```Julia
julia> boltzmann(Thomson) # erg⋅K⁻¹
$(boltzmann(Thomson))

julia> planckreduced(Thomson) # erg⋅s⋅rad⁻¹
$(planckreduced(Thomson))

julia> lightspeed(Thomson) # cm⋅s⁻¹
$(lightspeed(Thomson))

julia> vacuumpermeability(Thomson) # abH⋅cm⁻¹
$(vacuumpermeability(Thomson))

julia> electronmass(Thomson) # g
$(electronmass(Thomson))

julia> molarmass(Thomson) # g⋅mol⁻¹
$(molarmass(Thomson))

julia> luminousefficacy(Thomson) # lm⋅s⋅erg⁻¹
$(luminousefficacy(Thomson))

julia> rationalization(Thomson)
$(rationalization(Thomson))

julia> lorentz(Thomson)
$(lorentz(Thomson))
```
""" Thomson=#

@doc """
    Gauss = GaussSystem(Metric,𝟏,𝟐*τ,𝟏𝟎^-2/𝘤)

Centimetre-gram-second `UnitSystem` variant `CGS` (Gauss-Lorentz, non-rationalized).

```Julia
julia> boltzmann(Gauss) # erg⋅K⁻¹
$(boltzmann(Gauss))

julia> planckreduced(Gauss) # erg⋅s⋅rad⁻¹
$(planckreduced(Gauss))

julia> lightspeed(Gauss) # cm⋅s⁻¹
$(lightspeed(Gauss))

julia> vacuumpermeability(Gauss) # statH⋅cm⁻¹
$(vacuumpermeability(Gauss))

julia> electronmass(Gauss) # g
$(electronmass(Gauss))

julia> molarmass(Gauss) # g⋅mol⁻¹
$(molarmass(Gauss))

julia> luminousefficacy(Gauss) # lm⋅s⋅erg⁻¹
$(luminousefficacy(Gauss))

julia> rationalization(Gauss)
$(rationalization(Gauss))

julia> lorentz(Gauss)
$(lorentz(Gauss))
```
""" Gauss, CGS

@doc """
    LorentzHeaviside = GaussSystem(Metric,𝟏,𝟏,centi/𝘤)

Centimetre-gram-second `UnitSystem` variant `HLU` (Heaviside-Lorentz, rationalized).

```Julia
julia> boltzmann(LorentzHeaviside) # erg⋅K⁻¹
$(boltzmann(LorentzHeaviside))

julia> planckreduced(LorentzHeaviside) # erg⋅s⋅rad⁻¹
$(planckreduced(LorentzHeaviside))

julia> lightspeed(LorentzHeaviside) # cm⋅s⁻¹
$(lightspeed(LorentzHeaviside))

julia> vacuumpermeability(HLU) # hlH⋅cm⁻¹
$(vacuumpermeability(LorentzHeaviside))

julia> electronmass(LorentzHeaviside) # g
$(electronmass(LorentzHeaviside))

julia> molarmass(LorentzHeaviside) # g⋅mol⁻¹
$(molarmass(LorentzHeaviside))

julia> luminousefficacy(LorentzHeaviside) # lm⋅s⋅erg⁻¹
$(luminousefficacy(LorentzHeaviside))

julia> rationalization(LorentzHeaviside)
$(rationalization(LorentzHeaviside))

julia> lorentz(LorentzHeaviside)
$(lorentz(LorentzHeaviside))
```
""" LorentzHeaviside, HLU

@doc """
    Kennelly = GaussSystem(Metric,𝟏𝟎^-7,𝟐*τ,𝟏,𝟏,𝟏)

Kennelly ? variant `UnitSystem` of the standard `Metric` units ???

```Julia
julia> boltzmann(Kennelly) # J⋅K⁻¹
$(boltzmann(Kennelly))

julia> planckreduced(Kennelly) # J⋅s⋅rad⁻¹
$(planckreduced(Kennelly))

julia> lightspeed(Kennelly) # m⋅s⁻¹
$(lightspeed(Kennelly))

julia> vacuumpermeability(Kennelly) # H⋅m⁻¹
$(vacuumpermeability(Kennelly))

julia> electronmass(Kennelly) # kg
$(electronmass(Kennelly))

julia> molarmass(Kennelly) # kg⋅mol⁻¹
$(molarmass(Kennelly))

julia> luminousefficacy(Kennelly) # lm⋅W⁻¹
$(luminousefficacy(Kennelly))

julia> rationalization(Kennelly)
$(rationalization(Kennelly))
```
""" Kennelly

@doc """
    GravitationalMetric = EntropySystem(Metric,𝟏,𝟏,g₀)

Standard `GravitationalMetric` system based on `hyl` and `kilopond` units.

```Julia
julia> boltzmann(GravitationalMetric) # kgf⋅m⋅K⁻¹
$(boltzmann(GravitationalMetric))

julia> planckreduced(GravitationalMetric) # kgf⋅m⋅s⋅rad⁻¹
$(planckreduced(GravitationalMetric))

julia> lightspeed(GravitationalMetric) # m⋅s⁻¹
$(lightspeed(GravitationalMetric))

julia> vacuumpermeability(GravitationalMetric) # H⋅m⁻¹
$(vacuumpermeability(GravitationalMetric))

julia> electronmass(GravitationalMetric) # hyl
$(electronmass(GravitationalMetric))

julia> molarmass(GravitationalMetric) # hyl⋅mol⁻¹
$(molarmass(GravitationalMetric))

julia> luminousefficacy(GravitationalMetric) # lm⋅s⋅m⁻¹⋅kgf⁻¹
$(luminousefficacy(GravitationalMetric))
```
""" GravitationalMetric, GM

@doc """
    GraviationalSI2019 = EntropySystem(SI2019,𝟏,𝟏,g₀)

Gravitational Systeme International d'Unites based on `hyl` and `kilopond` units.

```Julia
julia> boltzmann(GravitationalSI2019) # kgf⋅m⋅K⁻¹
$(boltzmann(GravitationalSI2019))

julia> planckreduced(GravitationalSI2019) # kgf⋅m⋅s⋅rad⁻¹
$(planckreduced(GravitationalSI2019))

julia> lightspeed(GravitationalSI2019) # m⋅s⁻¹
$(lightspeed(GravitationalSI2019))

julia> vacuumpermeability(GravitationalSI2019) # kgf⋅s²⋅C⁻²
$(vacuumpermeability(GravitationalSI2019))

julia> electronmass(GravitationalSI2019) # hyl
$(electronmass(GravitationalSI2019))

julia> molarmass(GravitationalSI2019) # hyl⋅mol⁻¹
$(molarmass(GravitationalSI2019))

julia> luminousefficacy(GravitationalMetric) # lm⋅s⋅m⁻¹⋅kgf⁻¹
$(luminousefficacy(GravitationalMetric))
```
""" GravitationalSI2019, GSI, GSI2019

@doc """
    GravitationalMeridian = EntropySystem(Metric,𝟏,em,g₀*em^3,𝟏,τ/𝟐^6/𝟓^7/g₀,milli)

Gravitational `UnitSystem` variant of the original French `Meridian` unit defintion.

```Julia
julia> greatcircle(GravitationalMeridian) # em
$(greatcircle(GravitationalMeridian))

julia> boltzmann(GravitationalMeridian) # kegf⋅em⋅K⁻¹
$(boltzmann(GravitationalMeridian))

julia> planckreduced(GravitationalMeridian) # kegf⋅em⋅s⋅rad⁻¹
$(planckreduced(GravitationalMeridian))

julia> lightspeed(GravitationalMeridian) # em⋅s⁻¹
$(lightspeed(GravitationalMeridian))

julia> vacuumpermeability(GravitationalMeridian) # kegf⋅s²⋅eC⁻²
$(vacuumpermeability(GravitationalMeridian))

julia> electronmass(GravitationalMeridian) # ehyl
$(electronmass(GravitationalMeridian))

julia> molarmass(GravitationalMeridian) # ehyl⋅eg-mol⁻¹
$(molarmass(GravitationalMeridian))

julia> luminousefficacy(GravitationalMeridian) # lm⋅s⋅em⁻¹⋅kegf⁻¹
$(luminousefficacy(GravitationalMeridian))
```
""" GravitationalMeridian

@doc """
    MTS = EntropySystem(SI2019,𝟏,𝟏,kilo)

Metre-tonne-second `UnitSystem` variant of `Metric` system.

```Julia
julia> boltzmann(MTS) # kJ⋅K⁻¹
$(boltzmann(MTS))

julia> planckreduced(MTS) # kJ⋅s⋅rad⁻¹
$(planckreduced(MTS))

julia> lightspeed(MTS) # m⋅s⁻¹
$(lightspeed(MTS))

julia> vacuumpermeability(MTS) # kH⋅m⁻¹
$(vacuumpermeability(MTS))

julia> electronmass(MTS) # t
$(electronmass(MTS))

julia> molarmass(MTS) # t⋅mol⁻¹
$(molarmass(MTS))

julia> luminousefficacy(MTS) # lm⋅kW⁻¹
$(luminousefficacy(MTS))
```
""" MTS

@doc """
    KKH = EntropySystem(Metric,HOUR,kilo,𝟏)

Kilometer-kilogram-hour `UnitSystem` variant of `Metric` system.

```Julia
julia> boltzmann(KKH) # kg⋅km²⋅h⁻²⋅K⁻¹
$(boltzmann(KKH))

julia> planckreduced(KKH) # kg⋅km²⋅h⁻¹
$(planckreduced(KKH))

julia> lightspeed(KKH) # km⋅hr⁻¹
$(lightspeed(KKH))

julia> vacuumpermeability(KKH) # kg⋅km⋅C⁻²
$(vacuumpermeability(KKH))

julia> electronmass(KKH) # kg
$(electronmass(KKH))

julia> molarmass(KKH) # kg⋅mol⁻¹
$(molarmass(KKH))

julia> luminousefficacy(KKH) # lm⋅h³⋅kg⁻¹⋅km⁻²
$(luminousefficacy(KKH))
```
""" KKH

@doc """
    IAU☉ = EntropySystem(Metric,DAY,au,GM☉/G)

Solar `UnitSystem` defined by International Astronomical Union and `solarmass`.

```Julia
julia> boltzmann(IAU) # M⊙⋅au²⋅D⁻²⋅K⁻¹
$(boltzmann(IAU))

julia> planckreduced(IAU) # M⊙⋅au²⋅D⁻¹⋅rad⁻¹
$(planckreduced(IAU))

julia> lightspeed(IAU) # au⋅D⁻¹
$(lightspeed(IAU))

julia> vacuumpermeability(IAU) # M⊙⋅au²⋅C⁻²
$(vacuumpermeability(IAU))

julia> electronmass(IAU) # M⊙
$(electronmass(IAU))

julia> molarmass(IAU) # M☉⋅mol⁻¹
$(molarmass(IAU))

julia> luminousefficacy(IAU) # lm⋅D³⋅M☉⁻¹⋅au⁻²
$(luminousefficacy(IAU))

julia> gaussgravitation(IAU) # D⁻¹
$(gaussgravitation(IAU))
```
""" IAU☉, IAU

@doc """
    IAUE = EntropySystem(Metric,DAY,LD,GME/G)

Astronomical (Earth) `UnitSystem` defined by `lunardistance` around the `earthmass`.

```Julia
julia> boltzmann(IAUE) # ME⋅LD²⋅D⁻²⋅K⁻¹
$(boltzmann(IAUE))

julia> planckreduced(IAUE) # ME⋅LD²⋅D⁻¹⋅rad⁻¹
$(planckreduced(IAUE))

julia> lightspeed(IAUE) # LD⋅D⁻¹
$(lightspeed(IAUE))

julia> vacuumpermeability(IAUE) # ME⋅LD²⋅C⁻²
$(vacuumpermeability(IAUE))

julia> electronmass(IAUE) # ME
$(electronmass(IAUE))

julia> molarmass(IAUE) # ME⋅mol⁻¹
$(molarmass(IAUE))

julia> luminousefficacy(IAUE) # lm⋅D³⋅ME⁻¹⋅LD⁻²
$(luminousefficacy(IAUE))

julia> turn(IAU)/gaussianmonth(IAU) # D⁻¹
$(turn(IAU)/gaussianmonth(IAU))
```
""" IAUE

@doc """
    IAUJ = EntropySystem(Metric,DAY,JD,GMJ/G)

Astronomical (Jupiter) `UnitSystem` defined by `jupiterdistance` around the `solarmass`.

```Julia
julia> boltzmann(IAUJ) # MJ⋅JD²⋅D⁻²⋅K⁻¹
$(boltzmann(IAUJ))

julia> planckreduced(IAUJ) # MJ⋅JD²⋅D⁻¹⋅rad⁻¹
$(planckreduced(IAUJ))

julia> lightspeed(IAUJ) # JD⋅D⁻¹
$(lightspeed(IAUJ))

julia> vacuumpermeability(IAUJ) # MJ⋅JD²⋅C⁻²
$(vacuumpermeability(IAUJ))

julia> electronmass(IAUJ) # MJ
$(electronmass(IAUJ))

julia> molarmass(IAUJ) # MJ⋅mol⁻¹
$(molarmass(IAUJ))

julia> luminousefficacy(IAUJ) # lm⋅D³⋅MJ⁻¹⋅JD⁻²
$(luminousefficacy(IAUJ))

julia> sqrt(gravitation(IAUJ)*solarmass(IAUJ)/jupiterdistance(IAUJ)^3) # D⁻¹
$(sqrt(gravitation(IAUJ)*solarmass(IAUJ)/jupiterdistance(IAUJ)^3))
```
""" IAUJ

#=@doc """
    Astronomical = AstronomicalSystem(Metric)

Astronomical `UnitSystem` defined by making the `newton` gravitational constant 1.

```Julia
julia> boltzmann(Astronomical)
$(boltzmann(Astronomical))

julia> planckreduced(Astronomical)
$(planckreduced(Astronomical))

julia> lightspeed(Astronomical)
$(lightspeed(Astronomical))

julia> vacuumpermeability(Astronomical)
$(vacuumpermeability(Astronomical))

julia> electronmass(Astronomical)
$(electronmass(Astronomical))

julia> molarmass(Astronomical)
$(molarmass(Astronomical))

julia> luminousefficacy(Astronomical)
$(luminousefficacy(Astronomical))

julia> gravitation(Astronomical)
$(gravitation(Astronomical))
```
""" Astronomical=#

@doc """
    Hubble = EntropySystem(Metric,th,𝘤*th,𝟏)

Hubble `UnitSystem` defined by `hubble` parameter.

```Julia
julia> boltzmann(Hubble)
$(boltzmann(Hubble))

julia> planckreduced(Hubble)
$(planckreduced(Hubble))

julia> lightspeed(Hubble)
$(lightspeed(Hubble))

julia> vacuumpermeability(Hubble)
$(vacuumpermeability(Hubble))

julia> electronmass(Hubble)
$(electronmass(Hubble))

julia> molarmass(Hubble)
$(molarmass(Hubble))

julia> luminousefficacy(Hubble)
$(luminousefficacy(Hubble))

julia> hubble(Hubble)
$(hubble(Hubble))

julia> cosmological(Hubble)
$(cosmological(Hubble))
```
""" Hubble

@doc """
    Cosmological = EntropySystem(Metric,lc/𝘤,lc,mc)

Cosmological scale `UnitSystem` defined by `darkenergydensity`.

```Julia
julia> boltzmann(Cosmological)
$(boltzmann(Cosmological))

julia> planckreduced(Cosmological)
$(planckreduced(Cosmological))

julia> lightspeed(Cosmological)
$(lightspeed(Cosmological))

julia> vacuumpermeability(Cosmological)
$(vacuumpermeability(Cosmological))

julia> electronmass(Cosmological)
$(electronmass(Cosmological))

julia> molarmass(Cosmological)
$(molarmass(Cosmological))

julia> luminousefficacy(Cosmological)
$(luminousefficacy(Cosmological))

julia> hubble(Cosmological)
$(hubble(Cosmological))

julia> cosmological(Cosmological)
$(cosmological(Cosmological))
```
""" Cosmological

@doc """
    CosmologicalQuantum = EntropySystem(Metric,tcq,lcq,mcq)

Cosmological quantum scale `UnitSystem` defined by `darkenergydensity`.

```Julia
julia> boltzmann(CosmologicalQuantum)
$(boltzmann(CosmologicalQuantum))

julia> planckreduced(CosmologicalQuantum)
$(planckreduced(CosmologicalQuantum))

julia> lightspeed(CosmologicalQuantum)
$(lightspeed(CosmologicalQuantum))

julia> vacuumpermeability(CosmologicalQuantum)
$(vacuumpermeability(CosmologicalQuantum))

julia> electronmass(CosmologicalQuantum)
$(electronmass(CosmologicalQuantum))

julia> molarmass(CosmologicalQuantum)
$(molarmass(CosmologicalQuantum))

julia> luminousefficacy(CosmologicalQuantum)
$(luminousefficacy(CosmologicalQuantum))
```
""" CosmologicalQuantum

@doc """
    British = RankineSystem(Metric,ft,slug)

British Gravitational `UnitSystem` historically used by Britain and United States.

```Julia
julia> boltzmann(British) # ft⋅lb⋅°R⁻¹
$(boltzmann(British))

julia> planckreduced(British) # ft⋅lb⋅s⋅rad⁻¹
$(planckreduced(British))

julia> lightspeed(British) # ft⋅s⁻¹
$(lightspeed(British))

julia> vacuumpermeability(British) # slug⋅ft⋅C⁻²
$(vacuumpermeability(British))

julia> electronmass(British) # slugs
$(electronmass(British))

julia> molarmass(British) # slug⋅slug-mol⁻¹
$(molarmass(British))

julia> luminousefficacy(British) # lm⋅s⋅ft⁻¹⋅lb⁻¹
$(luminousefficacy(British))
```
""" British, BritishGravitational, BG

@doc """
    English = RankineSystem(Metric,ft,lb,g₀/ft)

English Engineering `UnitSystem` historically used in the United States of America.

```Julia
julia> boltzmann(English) # ft⋅lbf⋅°R⁻¹
$(boltzmann(English))

julia> planckreduced(English) # ft⋅lbf⋅s⋅rad⁻¹
$(planckreduced(English))

julia> lightspeed(English) # ft⋅s⁻¹
$(lightspeed(English))

julia> vacuumpermeability(English) # lbm⋅ft⋅C⁻²
$(vacuumpermeability(English))

julia> electronmass(English) # lbm
$(electronmass(English))

julia> molarmass(English) # lbm⋅lb-mol⁻¹
$(molarmass(English))

julia> luminousefficacy(English) # lm⋅s⋅ft⁻¹⋅lbf⁻¹
$(luminousefficacy(English))

julia> gravity(English) # lbm⋅ft⋅lbf⁻¹⋅s⁻²
$(gravity(English))
```
""" English, EnglishEngineering, EE

@doc """
    Survey = RankineSystem(Metric,ftUS,lb,g₀/ftUS)

English Engineering `UnitSystem` based on the geophysical US survey foot (1200/3937).

```Julia
julia> boltzmann(Survey) # ftUS⋅lbf⋅°R⁻¹
$(boltzmann(Survey))

julia> planckreduced(Survey) # ftUS⋅lbf⋅s⋅rad⁻¹
$(planckreduced(Survey))

julia> lightspeed(Survey) # ftUS⋅s⁻¹
$(lightspeed(Survey))

julia> vacuumpermeability(Survey) # lbm⋅ftUS⋅C⁻²
$(vacuumpermeability(Survey))

julia> electronmass(Survey) # lbm
$(electronmass(Survey))

julia> molarmass(Survey) # lbm⋅lb-mol⁻¹
$(molarmass(Survey))

julia> luminousefficacy(Survey) # lm⋅s⋅ft⁻¹⋅lbf⁻¹
$(luminousefficacy(Survey))

julia> gravity(Survey) # lbm⋅ftUS⋅lbf⁻¹⋅s⁻²
$(gravity(Survey))
```
""" Survey, EnglishUS

@doc """
    FPS = RankineSystem(Metric,ft,lb)

Absolute English `UnitSystem` based on the foot, pound, second, and poundal.

```Julia
julia> boltzmann(FPS) # ft⋅pdl⋅°R⁻¹
$(boltzmann(FPS))

julia> planckreduced(FPS) # ft⋅pdl⋅s⋅rad⁻¹
$(planckreduced(FPS))

julia> lightspeed(FPS) # ft⋅s⁻¹
$(lightspeed(FPS))

julia> vacuumpermeability(FPS) # lb⋅ft⋅C⁻²
$(vacuumpermeability(FPS))

julia> electronmass(FPS) # lb
$(electronmass(FPS))

julia> molarmass(FPS) # lb⋅lb-mol⁻¹
$(molarmass(FPS))

julia> luminousefficacy(FPS) # lm⋅s³⋅lb⁻¹⋅ft⁻²
$(luminousefficacy(FPS))
```
""" FPS, AbsoluteEnglish, AE

@doc """
    IPS = RankineSystem(Metric,ft/𝟐^2/𝟑,lb*g₀*𝟐^2*𝟑/ft)

British Gravitational `UnitSystem` historically used in the United States of America.

```Julia
julia> boltzmann(IPS) # in⋅lb⋅°R⁻¹
$(boltzmann(IPS))

julia> planckreduced(IPS) # in⋅lb⋅s⋅rad⁻¹
$(planckreduced(IPS))

julia> lightspeed(IPS) # in⋅s⁻¹
$(lightspeed(IPS))

julia> vacuumpermeability(IPS) # slinch⋅in⋅C⁻²
$(vacuumpermeability(IPS))

julia> electronmass(IPS) # slinch
$(electronmass(IPS))

julia> molarmass(IPS) # slinch⋅slinch-mol⁻¹
$(molarmass(IPS))

julia> luminousefficacy(IPS) # lm⋅s⋅in⁻¹⋅lb⁻¹
$(luminousefficacy(IPS))
```
""" IPS

@doc """
    FFF = EntropySystem(Metric,𝟐*𝟕*DAY,fur,𝟐*𝟑^2*𝟓*lb,°R,0,𝟏)

Furlong–firkin–fortnight `FFF` is a humorous `UnitSystem` based on unusal impractical units.

```Julia
julia> boltzmann(FFF) # fir⋅fur²⋅ftn⁻²⋅F⁻¹
$(boltzmann(FFF))

julia> planckreduced(FFF) # fir⋅fur²⋅ftn⁻¹⋅rad⁻¹
$(planckreduced(FFF))

julia> lightspeed(FFF) # fur⋅ftn⁻¹
$(lightspeed(FFF))

julia> vacuumpermeability(FFF) # fir⋅fur⋅Inf⁻²
$(vacuumpermeability(FFF))

julia> electronmass(FFF) # fir
$(electronmass(FFF))

julia> molarmass(FFF) # fir⋅fir-mol⁻¹
$(molarmass(FFF))

julia> luminousefficacy(FFF) # lm⋅ftn³⋅fir⁻¹⋅fur⁻²
$(luminousefficacy(FFF))
```
""" FFF

@doc """
    MPH = EntropySystem(FPS,HOUR,mi,𝟏)

Mile-pound-hour specification based on `FPS` absolute `UnitSystem`.

```Julia
julia> boltzmann(MPH) # lbf⋅mi²⋅hr⁻²⋅F⁻¹
$(boltzmann(MPH))

julia> planckreduced(MPH) # lbf⋅mi²⋅hr⁻¹⋅rad⁻¹
$(planckreduced(MPH))

julia> lightspeed(MPH) # mi⋅hr⁻¹
$(lightspeed(MPH))

julia> vacuumpermeability(MPH) # lbm⋅mi⋅C⁻²
$(vacuumpermeability(MPH))

julia> electronmass(MPH) # lbm
$(electronmass(MPH))

julia> molarmass(MPH) # lbm⋅lb-mol⁻¹
$(molarmass(MPH))

julia> luminousefficacy(MPH) # lm⋅h³⋅lb⁻¹⋅mi⁻²
$(luminousefficacy(MPH))
```
""" MPH

@doc """
    Nautical = EntropySystem(Metric,HOUR,nm,em^3,𝟏,τ*𝟑^3/𝟐^10/𝟓^12,milli)

Nautical miles, kilo-earthgram, hour specification based on `Meridian` definition.

```Julia
julia> greatcircle(Nautical) # nm
$(greatcircle(Nautical))

julia> boltzmann(Nautical) # keg⋅nm²⋅hr⁻²⋅K⁻¹
$(boltzmann(Nautical))

julia> planckreduced(Nautical) # keg⋅nm²⋅hr⁻¹⋅rad⁻¹
$(planckreduced(Nautical))

julia> lightspeed(Nautical) # nm⋅hr⁻¹
$(lightspeed(Nautical))

julia> vacuumpermeability(Nautical) # keg⋅nm⋅eC⁻²
$(vacuumpermeability(Nautical))

julia> electronmass(Nautical) # keg
$(electronmass(Nautical))

julia> molarmass(Nautical) # keg⋅eg-mol⁻¹
$(molarmass(Nautical))

julia> luminousefficacy(Nautical) # lm⋅h³⋅keg⁻¹⋅nm⁻²
$(luminousefficacy(Nautical))
```
""" Nautical

# natural unit system docs

textunits(U,S) = """
```Julia
julia> boltzmann($S)
$(boltzmann(U))

julia> planckreduced($S)
$(planckreduced(U))

julia> lightspeed($S)
$(lightspeed(U))

julia> vacuumpermeability($S)
$(vacuumpermeability(U))

julia> electronmass($S)
$(electronmass(U))
```
"""

@doc """
    Planck = UnitSystem(𝟏,𝟏,𝟏,𝟏,√(𝟐*τ*αG))

Planck `UnitSystem` with the `electronmass` value `√(4π*αG)` using gravitational coupling.

$(textunits(Planck,:Planck))
""" Planck

@doc """
    PlanckGauss = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ,√αG)

Planck (Gauss) `UnitSystem` with `permeability` of `4π` and `electronmass` coupling `√αG`.

$(textunits(PlanckGauss,:PlanckGauss))

The well known `PlanckGauss` values for `length`, `time`, `mass`, and `temperature` are:
```Julia
julia> length(PlanckGauss,Metric) # ℓP
$(length(PlanckGauss,Metric))

julia> time(PlanckGauss,Metric) # tP
$(time(PlanckGauss,Metric))

julia> mass(PlanckGauss,Metric) # mP
$(mass(PlanckGauss,Metric))

julia> temperature(PlanckGauss,Metric) # TP
$(temperature(PlanckGauss,Metric))
```
""" PlanckGauss

@doc """
    Stoney = UnitSystem(𝟏,𝟏/α,𝟏,𝟐*τ,√(αG/α)}

Stoney `UnitSystem` with `permeability` of `4π` and `electronmass` coupling `√(αG/α)`.

$(textunits(Stoney,:Stoney))

The well known `Stoney` values for `length`, `time`, `mass`, and `charge` are:
```Julia
julia> length(Stoney,Metric) # lS
$(length(Stoney,Metric))

julia> time(Stoney,Metric) # tS
$(time(Stoney,Metric))

julia> mass(Stoney,Metric) # mS
$(mass(Stoney,Metric))

julia> charge(Stoney,Metric) # qS
$(charge(Stoney,Metric))
```
""" Stoney

@doc """
    Hartree = UnitSystem(𝟏,𝟏,𝟏/α,𝟐*τ*α^2,𝟏)

Hartree atomic `UnitSystem` with `lightspeed` of `αinv` and `permeability` of `𝟐*τ*α^2`.

$(textunits(Hartree,:Hartree))

The well known `Hartree` atomic unit values for `length`, `time`, `mass`, and `charge` are:
```Julia
julia> length(Hartree,Metric) # lA
$(length(Hartree,Metric))

julia> time(Hartree,Metric) # tA
$(time(Hartree,Metric))

julia> mass(Hartree,Metric) # mA
$(mass(Hartree,Metric))

julia> charge(Hartree,Metric) # qA
$(charge(Hartree,Metric))
```
""" Hartree

@doc """
    Rydberg = UnitSystem(𝟏,𝟏,𝟐/α,τ/𝟐*α^2,𝟏/𝟐)

Rydberg `UnitSystem` with `lightspeed` of `𝟐/α` and `permeability` of `π*α^2`.

$(textunits(Rydberg,:Rydberg))
""" Rydberg

@doc """
    Schrodinger = UnitSystem(𝟏,𝟏,𝟏/α,𝟐*τ*α^2,√(αG/α))

Schrodinger `UnitSystem` with `permeability` of `4π/αinv^2` and `electronmass` of `√(αG*αinv)`.

$(textunits(Schrodinger,:Schrodinger))
""" Schrodinger

@doc """
    Electronic = UnitSystem(𝟏,𝟏/α,𝟏,𝟐*τ,𝟏}

Electronic `UnitSystem` with `planckreduced` of `1/α` and `permeability` of `4π`.

$(textunits(Electronic,:Electronic))
""" Electronic

@doc """
    Natural = UnitSystem(𝟏,𝟏,𝟏,𝟏,𝟏)

Natural `UnitSystem` with all primary constants having unit value.

$(textunits(Natural,:Natural))

The well known `Natural` values for `length`, `time`, `mass`, and `charge` are:
```Julia
julia> length(Natural,Metric)
$(length(Natural,Metric))

julia> time(Natural,Metric)
$(time(Natural,Metric))

julia> mass(Natural,Metric)
$(mass(Natural,Metric))

julia> charge(Natural,Metric)
$(charge(Natural,Metric))
```
""" Natural

@doc """
    NaturalGauss = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ,𝟏}

Natural (Gauss) `UnitSystem` with the Gaussian `permeability` value of `4π`.

$(textunits(NaturalGauss,:NaturalGauss))
""" NaturalGauss

@doc """
    QCD = UnitSystem(𝟏,𝟏,𝟏,𝟏,𝟏/μₚₑ)

Qunatum chromodynamics `UnitSystem` with `electronmass` of `𝟏/μₚₑ` or `𝟏/$μₚₑ`.

$(textunits(QCD,:QCD))

The well known `QCD` values for `length`, `time`, `mass`, and `charge` are:
```Julia
julia> length(QCD,Metric) # lQCD
$(length(QCD,Metric))

julia> time(QCD,Metric) # tQCD
$(time(QCD,Metric))

julia> mass(QCD,Metric) # mQCD
$(mass(QCD,Metric))

julia> charge(QCD,Metric)
$(charge(QCD,Metric))
```
""" QCD

@doc """
    QCDGauss = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ,𝟏/μₚₑ)

Qunatum chromodynamics (Gauss) `UnitSystem` with `electronmass` of `𝟏/μₚₑ`.

$(textunits(QCDGauss,:QCDGauss))

The well known `QCDGauss` values for `length`, `time`, `mass`, and `charge` are:
```Julia
julia> length(QCDGauss,Metric) # lQCD
$(length(QCDGauss,Metric))

julia> time(QCDGauss,Metric) # tQCD
$(time(QCDGauss,Metric))

julia> mass(QCDGauss,Metric) # mQCD
$(mass(QCDGauss,Metric))

julia> charge(QCDGauss,Metric)
$(charge(QCDGauss,Metric))
```
""" QCDGauss

@doc """
    QCDoriginal = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ*α,𝟏/μₚₑ)

Qunatum chromodynamics (original) `UnitSystem` with `permeability` of `4π*α`.

$(textunits(QCDoriginal,:QCDoriginal))

The well known `QCDoriginal` values for `length`, `time`, `mass`, and `charge` are:
```Julia
julia> length(QCDoriginal,Metric) # lQCD
$(length(QCDoriginal,Metric))

julia> time(QCDoriginal,Metric) # tQCD
$(time(QCDoriginal,Metric))

julia> mass(QCDoriginal,Metric) # mQCD
$(mass(QCDoriginal,Metric))

julia> charge(QCDoriginal,Metric)
$(charge(QCDoriginal,Metric))
```
""" QCDoriginal


text:
typealias RegSolveAlg Cuint

const REG_SOLVE_FGMRES = RegSolveAlg(0)
const REG_SOLVE_LGMRES = RegSolveAlg(1)

immutable RegSolveCtrl{T<:ElFloatType}
    alg::RegSolveAlg
    relTol::T
    relTolRefine::T
    maxIts::ElInt
    maxRefineIts::ElInt
    restart::ElInt
    progress::ElBool
    time::ElBool
end

function RegSolveCtrl{T<:ElFloatType}(::Type{T};
                    alg = REG_SOLVE_FGMRES,
                    relTol = eps(T)^0.5,
                    relTolRefine = eps(T)^0.8,
                    maxIts = 4,
                    maxRefineIts = 2,
                    restart = 4,
                    progress = false,
                    time = false)

    RegSolveCtrl{T}(RegSolveAlg(alg),
        T(relTol),
        T(relTolRefine),
        ElInt(maxIts),
        ElInt(maxRefineIts),
        ElInt(restart),
        ElBool(progress),
        ElBool(time))
end


text:
module CausalityTools

using DynamicalSystems
using Distances
using Reexport
using AbstractFFTs
using Statistics
using RecipesBase
using StaticArrays
using LinearAlgebra
using Measures

@reexport using TimeseriesSurrogates
@reexport using StateSpaceReconstruction
@reexport using PerronFrobenius
@reexport using TransferEntropy
@reexport using CrossMappings

using StateSpaceReconstruction: GroupSlices

import DynamicalSystemsBase:
    DynamicalSystem,
    ContinuousDynamicalSystem,
    DiscreteDynamicalSystem,
    Dataset,
    trajectory

# Example systems
include("systems/Systems.jl")

# Surrogate wrappers for embeddings and Datasets
include("surrogates/surrogates.jl")

# Wrappers of the different methods.
include("method_wrappers/highlevel_methods.jl")

# Plot recipes, also for all sub-packages
include("plot_recipes/recipes.jl")

export
Dataset,
DynamicalSystem,
DiscreteDynamicalSystem,
ContinuousDynamicalSystem,
trajectory

end # module


text:
# https://github.com/JuliaLang/julia/blob/b166d0d15f616f4a025ac5905a115399cc932ddc/base/compiler/typeinfer.jl#L706-L756

# compute (and cache) an inferred AST and return the current best estimate of the result type
function typeinf_edge(interp::AbstractInterpreter, method::Method, @nospecialize(atypes), sparams::SimpleVector, caller::InferenceState)
    mi = specialize_method(method, atypes, sparams)::MethodInstance
    code = get(code_cache(interp), mi, nothing)
    if code isa CodeInstance # return existing rettype if the code is already inferred
        update_valid_age!(caller, WorldRange(min_world(code), max_world(code)))
        if isdefined(code, :rettype_const)
            if isa(code.rettype_const, Vector{Any}) && !(Vector{Any} <: code.rettype)
                return PartialStruct(code.rettype, code.rettype_const), mi
            else
                return Const(code.rettype_const), mi
            end
        else
            return code.rettype, mi
        end
    end
    if ccall(:jl_get_module_infer, Cint, (Any,), method.module) == 0
        return Any, nothing
    end
    if !caller.cached && caller.parent === nothing
        # this caller exists to return to the user
        # (if we asked resolve_call_cyle, it might instead detect that there is a cycle that it can't merge)
        frame = false
    else
        frame = resolve_call_cycle!(interp, mi, caller)
    end
    if frame === false
        # completely new
        lock_mi_inference(interp, mi)
        result = InferenceResult(mi)
        frame = InferenceState(result, #=cached=#true, interp) # always use the cache for edge targets
        if frame === nothing
            # can't get the source for this, so we know nothing
            unlock_mi_inference(interp, mi)
            return Any, nothing
        end
        if caller.cached || caller.limited # don't involve uncached functions in cycle resolution
            frame.parent = caller
        end
        typeinf(interp, frame)
        update_valid_age!(frame, caller)
        return widenconst_bestguess(frame.bestguess), frame.inferred ? mi : nothing
    elseif frame === true
        # unresolvable cycle
        return Any, nothing
    end
    # return the current knowledge about this cycle
    frame = frame::InferenceState
    update_valid_age!(frame, caller)
    return widenconst_bestguess(frame.bestguess), nothing
end


text:
@testset "Test Saving and Loading PLS1 Models" begin

	Xtr        = [1 -2; 2 -4; 4.0 -6]
	Ytr        = [-2; -4; -6.0]
	Xt         = [6 -8; 8 -10; 10.0 -12]
	model1    = PLSRegressor.fit(Xtr,Ytr,nfactors=2)
	pred1     = PLSRegressor.predict(model1,Xt)

	PLSRegressor.save(model1)
	model2    = PLSRegressor.load()

	pred2     = PLSRegressor.predict(model2,Xt)
    rm(PLSRegressor.MODEL_FILENAME)
	@test all(pred1 .== pred2)

end

@testset "PLS1 Pediction Tests (in sample)" begin

	@testset "Single Column Prediction Test" begin

		X        = [1; 2; 3.0][:,:]
		Y        = [1; 2; 3.0]
		model    = PLSRegressor.fit(X,Y,nfactors=1)
		pred     = PLSRegressor.predict(model,X)
		@test isequal(round.(pred),[1; 2; 3.0])

	end

	@testset "Constant Values Prediction Tests (Ax + b) | A=0, b=1 " begin

		X        = [1 3;2 1;3 2.0]
		Y        = [1; 1; 1.0]
		try
			PLSRegressor.fit(X,Y,nfactors=2)
		catch
			@test true
		end

	end

	@testset "Linear Prediction Tests " begin

		X        = [1 2; 2 4; 4.0 6]
		Y        = [2; 4; 6.0]
		model    = PLSRegressor.fit(X,Y,nfactors=2)
		pred     = PLSRegressor.predict(model,X)
		@test isequal(round.(pred),[2; 4; 6.0])

		X           = [1 -2; 2 -4; 4.0 -6]
		Y           = [-2; -4; -6.0]
		model       = PLSRegressor.fit(X,Y,nfactors=2)
		pred        = PLSRegressor.predict(model,X)
		@test isequal(round.(pred),[-2; -4; -6.0])

	end

	@testset "Linear Prediction Tests (Ax + b)" begin

		Xtr        = [1 2; 2 4; 4.0 6]
		Ytr        = [2; 4; 6.0]
		Xt         = [6 8; 8 10; 10.0 12] # same sample
		model    = PLSRegressor.fit(Xtr,Ytr,nfactors=2)
		pred     = PLSRegressor.predict(model,Xt)
		@test isequal(round.(pred),[8; 10; 12.0])

		Xtr        = [1 2; 2 4.0; 4.0 6; 6 8]
		Ytr        = [2; 4; 6.0; 8]
		Xt         = [1 2; 2 4.0] # a subsample

		model    = PLSRegressor.fit(Xtr,Ytr,nfactors=2,centralize=true)
		pred     = PLSRegressor.predict(model,Xt)
		@test isequal(round.(pred),[2; 4])

	end

end;

@testset "PLS1 Pediction Tests (out of sample)" begin

	@testset "Linear Prediction Tests (Ax + b) | A>0" begin

		Xtr        = [1 2; 2 4; 4.0 6]
		Ytr        = [2; 4; 6.0]
		Xt         = [6 8; 8 10; 10.0 12]
		model    = PLSRegressor.fit(Xtr,Ytr,nfactors=2)
		pred     = PLSRegressor.predict(model,Xt)
		@test isequal(round.(pred),[8; 10; 12.0])

		Xtr        = [1 2; 2 4; 4.0 6]
		Ytr        = [4; 6; 8.0]
		Xt         = [6 8; 8 10; 10.0 12]
		model    = PLSRegressor.fit(Xtr,Ytr,nfactors=2)
		pred     = PLSRegressor.predict(model,Xt)
		@test isequal(round.(pred),[10; 12; 14.0])

	end

	@testset "Linear Prediction Tests (Ax + b) | A<0" begin

		Xtr        = [1 -2; 2 -4; 4.0 -6]
		Ytr        = [-2; -4; -6.0]
		Xt         = [6 -8; 8 -10; 10.0 -12]
		model    = PLSRegressor.fit(Xtr,Ytr,nfactors=2)
		pred     = PLSRegressor.predict(model,Xt)
		@test isequal(round.(pred),[-8; -10; -12.0])

		Xtr        = [1 -2; 2 -4; 4.0 -6]
		Ytr        = [-4; -6; -8.0]
		Xt         = [6 -8; 8 -10; 10.0 -12]
		model    = PLSRegressor.fit(Xtr,Ytr,nfactors=2)
		pred     = PLSRegressor.predict(model,Xt)
		@test isequal(round.(pred),[-10; -12; -14.0])

	end

end;


text:
#input Img_Noising and Img_Origin
#return the PSNR

function psnr(Img1::Array{Float32,3}, Img2::Array{Float32,3}) :: Float64

    if size(Img1) != size(Img2)
        println("Images should be in the same size")
        return
    end

    (N,M) = size(Img1)

    10 * log10(255^2 / mean((Img1 - Img2).^2))

end


text:
"""

Update Stan language model file (if necessary).

$(SIGNATURES)

# Extended help

### Method
```julia
StanSample.update_model_file(
  file::String,
  str::String
)
```
### Required arguments
```julia
* `file::AbstractString`                : File for Stan model
* `str::AbstractString`                 : Stan model string
```

Internal, not exported.
"""
function update_model_file(file::AbstractString, model::AbstractString)

  model1 = strip(parse_and_interpolate(model))
  model2 = ""
  if isfile(file)
    resfile = open(file, "r")
    model2 = strip(parse_and_interpolate(read(resfile, String)))
    model1 != model2 && rm(file)
  end
  if model1 != model2
    println("\n$(file) updated.")
    strmout = open(file, "w")
    write(strmout, model1)
    close(strmout)
  end

end

"""

Parse and interpolate Stan functionality into the Stan Language model before compilation
of the model by stanc.

$(SIGNATURES)

# Extended help

### Method
```julia
StanSample.parse_and_interpolate(
  model::AbstractString)
)
```
### Required arguments
```julia
* `model::AbstractString`              : String with Stan model
```

Internal, not exported.
"""
function parse_and_interpolate(model::AbstractString)
  newmodel = ""
  lines = split(model, "\n")
  for l in lines
    ls = String(strip(l))
    replace_strings = findall("#include", ls)
    if length(replace_strings) == 1 &&
        # handle the case the include line is commented out
        length(ls) > 2 && !(ls[1:2] == "//")
      for r in replace_strings
        ls = split(strip(ls[r[end]+1:end]), " ")[1]
        func = open(f -> read(f, String), strip(ls))
        newmodel *= "   "*func*"\n"
      end
    else
      if length(replace_strings) > 1
        error("Improper number of includes in line `$l`")
      else
        newmodel *= l*"\n"
      end
    end
  end
  newmodel
end


text:
platforms_and_sources = Dict(
    Platform("x86_64", "linux") => [
        ArchiveSource("https://developer.nvidia.com/compute/machine-learning/cudnn/secure/8.2.4/10.2_20210831/cudnn-10.2-linux-x64-v8.2.4.15.tgz",
                      "d23c94a3115a1c77116a6c127d9175fbf59f723364374f26a34699075f3222f1")],
    Platform("x86_64", "windows") => [
        ArchiveSource("https://developer.nvidia.com/compute/machine-learning/cudnn/secure/8.2.4/10.2_20210831/cudnn-10.2-windows10-x64-v8.2.4.15.zip",
                      "a13eb10cfd7e6b7b8f39d8593038855b911012c29f03990878622bdae873c4a8")],
    Platform("aarch64", "linux") => [
        FileSource("https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/arm64/libcudnn8_8.2.4.15-1+cuda10.2_arm64.deb", "3f08dbe14c3becb9fa1ed85cd4a080efb30edb0c4beb2fc1a2e14da3f2eefb79"),
        FileSource("https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/arm64/libcudnn8-dev_8.2.4.15-1+cuda10.2_arm64.deb", "4816575e8a14baf3fc1619cb01c6dc2afd4f1b39210079d271208088ecc48702")
    ]
)

max_stars_repo_name: cmhamel/Yggdrasil

max_issues_repo_name: cmhamel/Yggdrasil

max_forks_repo_name: cmhamel/Yggdrasil


text:
using Publish
using FluxTraining

p = Publish.Project(FluxTraining)
rm("dev", recursive = true, force = true)
rm(p.env["version"], recursive = true, force = true)
deploy(FluxTraining; root = "/FluxTraining.jl", force = true, label = "dev")