text:
module Quadhps
using FastGaussQuadrature, FastClosures, StaticArrays

struct _Helper{T}
  abstol::T
  reltol::T
  max_depth::Int
  split::Int
  function _Helper(abstol::T, reltol::T, max_depth::Int, split::Int
      ) where {T<:Real}
    @assert split > 0 && max_depth >= 0 "$split, $max_depth"
    return new{T}(abstol, reltol, max_depth, split)
  end
end

#const memo = Dict{Int64, Tuple{Array{Float64,1},Array{Float64,1},
#                               Array{Float64,1}}}()
const memo = Dict()

@inline function memoisedgausslengendre(n::Int)
  if !haskey(memo, n)
    x, w = FastGaussQuadrature.gausslegendre(n)
    memo[n] = (x, w)
  end
  return memo[n]
end

@inline function calculate_node_weight(h::_Helper, n::Int,
    a, b)
  x, w = memoisedgausslengendre(n)
  halfdifference = @. (b - a) / 2
  halfsum = @. (b + a) / 2
  y = @. x * halfdifference + halfsum
  return y, w, halfdifference
end

@inline function simdmapreduce(f::T, op, iter) where {T<:Function}
  @inbounds output = f(iter[1])
  @inbounds @simd for i ∈ 2:length(iter)
    output += f(iter[i])
  end
  return output
end

@inline function applyquadrature(f::T, op, x, w) where {T<:Function}
  @inbounds output = f(x[1]) * w[1]
  @inbounds @simd for i ∈ 2:length(w)
    output += f(x[i]) * w[i]
  end
  return output
end

@inline function quad(f::T, h::_Helper, a, b, n::Int
    ) where {T<:Function}
  x, w, normalisation = calculate_node_weight(h, n, a, b)
  return applyquadrature(f, +, x, w) * normalisation
end

@inline function quad(f::T, h::_Helper, a, b, c, n::Int
    ) where {T<:Function}
  @assert a < b < c "$a, $b, $c"
  U = promote_type(typeof(a), typeof(b), typeof(c))
  @assert isapprox(b .- a, c .- b, rtol=sqrt(eps(U)), atol=0) "$a, $b, $c"
  x, w, normalisation = calculate_node_weight(h, n, a, b)
  b_a = b .- a
  reductionop = @closure x -> (f(x) .+ f(x .+ b_a))
  return applyquadrature(reductionop, +, x, w) * normalisation
end

@inline function hasconverged(a, b, h::_Helper, l::Int,
    nrm::T) where {T<:Function}
  all(@. nrm(a - b) < h.split^l * h.reltol * nrm(a + b) / 2) && return true
  all(@. nrm(a + b) / 2 <= h.abstol) && return true
  l > h.max_depth && return true
  return false
end

function quadhp(f::T, h::_Helper, a, b,
    n::Int, l::Int, nrm::U) where {T<:Function, U<:Function}
  @assert -Inf < a < b < Inf "a = $a, b = $b"
  @assert ispow2(n) "n is $n"
  qp = quad(f, h, a, b, n)
  qh = quad(f, h, a, (b .+ a) / 2, b, Int(n / 2))
  hasconverged(qp, qh, h, l, nrm) && return @SVector [(qp + qh) / 2, @. nrm(qp .- qh)]
  reductionop = @closure i -> quadhp(f, h, a .+ i * (b .- a) / h.split,
    a .+ (i + 1) * (b .- a) / h.split, 2n, l + 1, nrm)
  return simdmapreduce(reductionop, +, 0:(h.split - 1))
end

const default_order = 32
const default_split = 2
const default_max_depth = 8

function quadhp(f::T, a, b; norm::U=abs,
                rtol::Real=eps(), atol::Real=0.0,
                order::Int=default_order, max_depth::Int=default_max_depth,
                split::Int=default_split) where {T<:Function, U<:Function}
  return quadhp(f, _Helper(atol, rtol, max_depth, split), a, b, order, 0, norm)
end

function quadhp(f::T, ab...; norm::U=abs,
                rtol::Real=eps(), atol::Real=0.0,
                order::Int=default_order, max_depth::Int=default_max_depth,
                split::Int=default_split) where {T<:Function, U<:Function}
  reductionop = @closure i -> quadhp(f, ab[i], ab[i+1], norm=norm, rtol=rtol,
    atol=atol, order=order, max_depth=max_depth, split=split)
  return simdmapreduce(reductionop, +, 1:(length(ab)-1))
end

end # module


text:
using PooksoftBase
using Test

# default test = returns true
function default_package_test()
    return true
end

@testset "default_test_set" begin
    default_package_test() == true
end

ext: jl


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

name = "LibxcBuilder"
version = v"4.3.4"

# Collection of sources required to build LibxcBuilder
sources = [
    "https://gitlab.com/libxc/libxc/-/archive/4.3.4/libxc-4.3.4.tar.gz" =>
    "2d5878dd69f0fb68c5e97f46426581eed2226d1d86e3080f9aa99af604c65647",

]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir
cd libxc-4.3.4/
autoreconf -i
./configure --prefix=$prefix --host=$target --enable-shared
make
make install VERBOSE=1

"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [
    MacOS(:x86_64),
    Linux(:x86_64, libc=:glibc),
    Linux(:i686, libc=:glibc),
    # Windows(:i686),
    # Windows(:x86_64),
]

# The products that we will ensure are always built
products(prefix) = [
    ExecutableProduct(prefix, "xc-threshold", :xcthreshold),
    LibraryProduct(prefix, "libxc", :libxc),
    ExecutableProduct(prefix, "xc-info", :xcinfo)
]

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

]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)


text:
push!(LOAD_PATH,"../src")

using Documenter, OpenTrick

makedocs(sitename="OpenTrick Documentation")


text:
###############################################################################
#
# Creating Plant Hydraulic system
#
###############################################################################
"""
    create_grass(
                z_root::FT,
                z_canopy::FT,
                soil_bounds::Array{FT,1},
                air_bounds::Array{FT,1}
    ) where {FT<:AbstractFloat}

Create a [`GrassLikeOrganism`](@ref), given
- `z_root` Maximal root depth (negative value)
- `z_canopy` Maximal canopy height (positive value)
- `soil_bounds` Array of soil layer boundaries starting from 0
- `air_bounds` Array of air layer boundaries starting from 0
"""
function create_grass(
            z_root::FT,
            z_canopy::FT,
            soil_bounds::Array{FT,1},
            air_bounds::Array{FT,1}
) where {FT<:AbstractFloat}
    # determine how many layers in roots and canopy
    _n_root  = 0;
    _r_index = Int[]
    for i in eachindex(soil_bounds)
        _z = soil_bounds[i];
        if _z > z_root
            _n_root += 1;
            push!(_r_index, i);
        else
            break
        end
    end

    _n_canopy = 0;
    _c_index  = Int[];
    for i in eachindex(air_bounds)
        _z = air_bounds[i]
        if _z < z_canopy
            _n_canopy += 1;
            push!(_c_index, i);
        elseif _z >= z_canopy
            break
        end
    end

    # create evenly distributed root system for now
    _roots = RootHydraulics{FT}[];
    for i in _r_index
        _Δh = abs(soil_bounds[i+1] + soil_bounds[i]) / 2;
        _rt = RootHydraulics{FT}(
                    area=1/_n_root,
                    k_max=25/_n_root,
                    k_rhiz=5e14/_n_root,
                    Δh=_Δh);
        push!(_roots, _rt);
    end

    # create leaves
    _leaves = [LeafHydraulics{FT}(area=1500/_n_canopy) for i in 1:_n_canopy];

    # return plant
    return GrassLikeOrganism{FT}(_n_root,
                                 _n_canopy,
                                 _roots,
                                 _leaves,
                                 _r_index,
                                 _c_index,
                                 zeros(FT,_n_root),
                                 zeros(FT,_n_root),
                                 zeros(FT,_n_root))
end

"""
    create_palm(z_root::FT,
                z_trunk::FT,
                z_canopy::FT,
                soil_bounds::Array{FT,1},
                air_bounds::Array{FT,1}
    ) where {FT<:AbstractFloat}

Create a [`PalmLikeOrganism`](@ref), given
- `z_root` Maximal root depth (negative value)
- `z_trunk` Maximal trunk height (positive value)
- `z_canopy` Maximal canopy height (positive value)
- `soil_bounds` Array of soil layer boundaries starting from 0
- `air_bounds` Array of air layer boundaries starting from 0
"""
function create_palm(
            z_root::FT,
            z_trunk::FT,
            z_canopy::FT,
            soil_bounds::Array{FT,1},
            air_bounds::Array{FT,1}
) where {FT<:AbstractFloat}
    # determine how many layers in roots and canopy
    _n_root  = 0;
    _r_index = Int[]
    for i in eachindex(soil_bounds)
        _z = soil_bounds[i];
        if _z > z_root
            _n_root += 1;
            push!(_r_index, i);
        else
            break
        end
    end

    _n_canopy = 0;
    _c_index  = Int[];
    for i in 1:(length(air_bounds)-1)
        _z0 = air_bounds[i];
        _z1 = air_bounds[i+1];
        if _z0 <= z_trunk < z_canopy <= _z1
            _n_canopy += 1;
            push!(_c_index, i);
            break
        elseif _z0 < z_trunk < _z1 < z_canopy
            _n_canopy += 1;
            push!(_c_index, i);
        elseif z_trunk <= _z0 < _z1 < z_canopy
            _n_canopy += 1;
            push!(_c_index, i);
        elseif z_trunk <= _z0 <= z_canopy < _z1
            _n_canopy += 1;
            push!(_c_index, i-1);
            break
        elseif z_canopy <= _z0 < _z1
            break
        end
    end

    # create evenly distributed root system for now
    _roots = RootHydraulics{FT}[];
    for i in _r_index
        _Δh = abs(soil_bounds[i+1] + soil_bounds[i]) / 2;
        _rt = RootHydraulics{FT}(
                    area=1/_n_root,
                    k_max=25/_n_root,
                    k_rhiz=5e14/_n_root,
                    Δh=_Δh);
        push!(_roots, _rt);
    end

    # create Trunk
    _trunk   = StemHydraulics{FT}(
                    k_max=50,
                    Δh=z_trunk);

    # create leaves
    _leaves = [LeafHydraulics{FT}(area=1500/_n_canopy) for i in 1:_n_canopy];

    # return plant
    return PalmLikeOrganism{FT}(_n_root,
                                _n_canopy,
                                _roots,
                                _trunk,
                                _leaves,
                                _r_index,
                                _c_index,
                                zeros(FT,_n_root),
                                zeros(FT,_n_root),
                                zeros(FT,_n_root))
end

"""
    create_tree(z_root::FT,
                z_trunk::FT,
                z_canopy::FT,
                soil_bounds::Array{FT,1},
                air_bounds::Array{FT,1}
    ) where {FT<:AbstractFloat}

Create a [`TreeLikeOrganism`](@ref), given
- `z_root` Maximal root depth (negative value)
- `z_trunk` Maximal trunk height (positive value)
- `z_canopy` Maximal canopy height (positive value)
- `soil_bounds` Array of soil layer boundaries starting from 0
- `air_bounds` Array of air layer boundaries starting from 0
"""
function create_tree(
            z_root::FT,
            z_trunk::FT,
            z_canopy::FT,
            soil_bounds::Array{FT,1},
            air_bounds::Array{FT,1}
) where {FT<:AbstractFloat}
    # determine how many layers in roots and canopy
    _n_root  = 0;
    _r_index = Int[]
    for i in eachindex(soil_bounds)
        _z = soil_bounds[i];
        if _z > z_root
            _n_root += 1;
            push!(_r_index, i);
        else
            break
        end
    end

    _n_canopy = 0;
    _c_index  = Int[];
    for i in eachindex(air_bounds)
        _z0 = air_bounds[i];
        _z1 = air_bounds[i+1];
        if _z0 <= z_trunk < z_canopy <= _z1
            _n_canopy += 1;
            push!(_c_index, i);
            break
        elseif _z0 < z_trunk < _z1 < z_canopy
            _n_canopy += 1;
            push!(_c_index, i);
        elseif z_trunk <= _z0 < _z1 < z_canopy
            _n_canopy += 1;
            push!(_c_index, i);
        elseif z_trunk <= _z0 <= z_canopy < _z1
            _n_canopy += 1;
            push!(_c_index, i-1);
            break
        elseif z_canopy <= _z0 < _z1
            break
        end
    end

    # create evenly distributed root system for now
    _roots = RootHydraulics{FT}[];
    for i in _r_index
        _Δh = abs(soil_bounds[i+1] + soil_bounds[i]) / 2;
        _rt = RootHydraulics{FT}(
                    area=1/_n_root,
                    k_max=25/_n_root,
                    k_rhiz=5e14/_n_root,
                    Δh=_Δh);
        push!(_roots, _rt);
    end

    # create Trunk
    _k_trunk = z_canopy / z_trunk * 50;
    _trunk   = StemHydraulics{FT}(
                    k_max=_k_trunk,
                    Δh=z_trunk);

    # create Branches
    _k_branch = z_canopy / (z_canopy - z_trunk) * 50;
    _branch   = StemHydraulics{FT}[];
    for i in _c_index
        _Δh = (air_bounds[i] + max(air_bounds[i+1], z_trunk)) / 2 - z_trunk;
        _st = StemHydraulics{FT}(
                    area=1/_n_canopy,
                    k_max=_k_branch/_n_canopy,
                    Δh=_Δh);
        push!(_branch, _st);
    end

    # create leaves
    _leaves = [LeafHydraulics{FT}(area=1500/_n_canopy) for i in 1:_n_canopy];

    # return plant
    return TreeLikeOrganism{FT}(_n_root,
                                _n_canopy,
                                _roots,
                                _trunk,
                                _branch,
                                _leaves,
                                _r_index,
                                _c_index,
                                zeros(FT,_n_root),
                                zeros(FT,_n_root),
                                zeros(FT,_n_root))
end

max_stars_repo_name: bbuman/Land

max_issues_repo_name: bbuman/Land

max_forks_repo_name: bbuman/Land


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: marketplace_entitlement_service
using AWS.Compat
using AWS.UUIDs

"""
    GetEntitlements()

GetEntitlements retrieves entitlement values for a given product. The results can be filtered based on customer identifier or product dimensions.

# Required Parameters
- `ProductCode`: Product code is used to uniquely identify a product in AWS Marketplace. The product code will be provided by AWS Marketplace when the product listing is created.

# Optional Parameters
- `Filter`: Filter is used to return entitlements for a specific customer or for a specific dimension. Filters are described as keys mapped to a lists of values. Filtered requests are unioned for each value in the value list, and then intersected for each filter key.
- `MaxResults`: The maximum number of items to retrieve from the GetEntitlements operation. For pagination, use the NextToken field in subsequent calls to GetEntitlements.
- `NextToken`: For paginated calls to GetEntitlements, pass the NextToken from the previous GetEntitlementsResult.
"""
get_entitlements(ProductCode; aws_config::AWSConfig=global_aws_config()) = marketplace_entitlement_service("GetEntitlements", Dict{String, Any}("ProductCode"=>ProductCode); aws_config=aws_config)
get_entitlements(ProductCode, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = marketplace_entitlement_service("GetEntitlements", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ProductCode"=>ProductCode), args)); aws_config=aws_config)


text:
module PythonInterop

using Pkg
Pkg.add("PyCall")
using PyCall

function __init__()
    py"""
    import numpy as np

    def sinpi(x):
        return np.sin(np.pi * x)

    def pyfib(n, fib):
        # print("hello from python")
        if(n < 2):
            return n
        else:
            return fib(n-1, pyfib) + fib(n-2, pyfib)
    """
end

function py_sinpi(x)
    py"sinpi"(x)
end

function get_pyfib()
    py"pyfib"
end

function jlfib(n, fib)
    # println("hello from julia")
    n < 2 ? n : fib(n-1, fib) + fib(n-2, fib)
end

end


text:
using Query
using DataFrames
using DataArrays
using TypedTables
using NamedTuples
using DataStreams
using CSV
using SQLite
using JSON
using Feather
using Base.Test

immutable Person
    Name::String
    Friends::Vector{String}
end

@testset begin

source_df = DataFrame(name=["John", "Sally", "Kirk"], age=[23., 42., 59.], children=[3,5,2])

q = @from i in source_df begin
    @where i.age>30. && i.children > 2
    @select {Name=lowercase(i.name)}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(1,1)
@test q[1,:Name]=="sally"

source_dict = Dict("John"=>34., "Sally"=>56.)

q = @from i in source_dict begin
    @where i.second>36.
    @select {Name=lowercase(i.first)}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(1,1)
@test q[1,:Name]=="sally"

q = @from i in source_dict begin
    @where i.second>36.
    @select lowercase(i.first)
    @collect
end

@test isa(q, Array{String,1})
@test length(q)==1
@test q[1]=="sally"

source_array = Array(Person,0)
push!(source_array, Person("John", ["Sally", "Miles", "Frank"]))
push!(source_array, Person("Sally", ["Don", "Martin"]))

q = @from i in source_array begin
    @where length(i.Friends) > 2
    @select {i.Name, Friendcount=length(i.Friends)}
    @collect
end

@test isa(q,Array{NamedTuples._NT_NameFriendcount{String,Int},1})
@test length(q)==1
@test q[1].Name=="John"
@test q[1].Friendcount==3

q = @from i in source_array begin
    @where length(i.Friends) > 2
    @select {i.Name, Friendcount=length(i.Friends)}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(1,2)
@test q[1,:Name]=="John"
@test q[1,:Friendcount]==3

source_typedtable = @Table(name=Nullable{String}["John", "Sally", "Kirk"], age=Nullable{Float64}[23., 42., 59.], children=Nullable{Int}[3,5,2])

q = @from i in source_typedtable begin
    @where i.age>30 && i.children>2
    @select {Name=lowercase(get(i.name))}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(1,1)
@test q[1,:Name]=="sally"

source_df2 = DataFrame(a=[1,2,3], b=[1.,2.,3.])
source_typedtable2 = @Table(c=[2.,4.,2.], d=["John", "Jim","Sally"])

q = @from i in source_df2 begin
    @join j in source_typedtable2 on get(i.a) equals convert(Int,j.c)
    @select {i.a,i.b,j.c,j.d,e="Name: $(j.d)"}
    @collect DataFrame
end

@test isa(q,DataFrame)
@test size(q)==(2,5)
@test q[1,:a]==2
@test q[1,:b]==2.
@test q[1,:c]==2.
@test q[1,:d]=="John"
@test q[1,:e]=="Name: John"
@test q[2,:a]==2
@test q[2,:b]==2.
@test q[2,:c]==2.
@test q[2,:d]=="Sally"
@test q[2,:e]=="Name: Sally"

q = @from i in source_df2 begin
    @join j in (@from i in source_typedtable2 begin
                    @where i.c<3.
                    @select i
                end) on get(i.a) equals convert(Int,j.c)
    @select {i.a,i.b,j.c,j.d,e="Name: $(j.d)"}
    @collect DataFrame
end

@test isa(q,DataFrame)
@test size(q)==(2,5)
@test q[1,:a]==2
@test q[1,:b]==2.
@test q[1,:c]==2.
@test q[1,:d]=="John"
@test q[1,:e]=="Name: John"
@test q[2,:a]==2
@test q[2,:b]==2.
@test q[2,:c]==2.
@test q[2,:d]=="Sally"
@test q[2,:e]=="Name: Sally"

q = @from i in source_df begin
    @let count = length(i.name)
    @let kids_per_year = i.children / i.age
    @where count > 4
    @select {Name=i.name, Count=count, KidsPerYear=kids_per_year}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(1,3)
@test q[1,:Name]=="Sally"
@test q[1,:Count]==5
@test q[1,:KidsPerYear]≈0.119047619047

q = @from i in source_df begin
    @orderby i.age
    @select lowercase(i.name)
    @collect
end

@test isa(q, Array{Nullable{String},1})
@test length(q)==3
@test q==["john", "sally", "kirk"]

q = @from i in source_df begin
    @orderby descending(i.age)
    @select lowercase(i.name)
    @collect
end

@test isa(q, Array{Nullable{String},1})
@test length(q)==3
@test q==["kirk", "sally", "john"]

q = @from i in source_df begin
    @orderby ascending(i.age)
    @select lowercase(i.name)
    @collect
end

@test isa(q, Array{Nullable{String},1})
@test length(q)==3
@test q==["john", "sally", "kirk"]

source_nestedsort = [(4,3),(4,3),(1,2),(1,1)]
q = @from i in source_nestedsort begin
    @orderby i[1], descending(i[2])
    @select i
    @collect
end

@test isa(q, Array{Tuple{Int,Int},1})
@test length(q)==4
@test q==[(1,2),(1,1),(4,3),(4,3)]

# We need to use a typed const here, otherwise type inference stands no chance
const closure_var_1::Int = 1

q = @from i in source_df begin
    @let k = i.children + closure_var_1
    @join j in source_df2 on i.children*closure_var_1 equals j.a*closure_var_1
    @where i.age>closure_var_1
    @orderby i.age*closure_var_1
    @select i.children + closure_var_1
    @collect
end

@test isa(q, Array{Nullable{Int},1})
@test length(q)==2
@test q[1]==4
@test q[2]==3

q = @from i in [5,4,4,6,1] begin
    @orderby i
    @select i
    @collect
end

@test isa(q,Array{Int,1})
@test length(q)==5
@test q==[1,4,4,5,6]

q = @from i in [5,4,4,6,1] begin
    @orderby descending(i)
    @select i
    @collect
end

@test isa(q,Array{Int,1})
@test length(q)==5
@test q==[6,5,4,4,1]

# Test phase 3 query translation

q = @from i in source_array begin
    @select i
    @collect
end

@test isa(q,Array{Person,1})
@test length(q)==2
@test q[1].Name=="John"
@test q[1].Friends==["Sally", "Miles", "Frank"]
@test q[2].Name=="Sally"
@test q[2].Friends==["Don", "Martin"]

q = @from i in CSV.Source("data.csv") begin
    @where i.Children > 2
    @select get(i.Name)
    @collect
end

@test isa(q,Array{String,1})
@test length(q)==2
@test q[1]=="John"
@test q[2]=="Kirk"

q = @from i in source_df begin
    @from j in source_df2
    @select {Name=i.name,Age=i.age,Children=i.children,A=j.a,B=j.b}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(9,5)
@test q[:Name]==["John","John","John","Sally","Sally","Sally","Kirk","Kirk","Kirk"]
@test q[:Age]==[23.,23.,23.,42.,42.,42.,59.,59.,59.]
@test q[:Children]==[3,3,3,5,5,5,2,2,2]
@test q[:A]==[1,2,3,1,2,3,1,2,3]
@test q[:B]==[1.,2.,3.,1.,2.,3.,1.,2.,3.]

source_nested_dict = Dict(:a=>[1,2,3], :b=>[4,5])

q = @from i in source_nested_dict begin
    @from j in i.second
    @select {Key=i.first,Value=j}
    @collect
end

@test isa(q, Array{@NT(Key::Symbol,Value::Int),1})
@test length(q)==5
@test in(@NT(Key=>:a,Value=>1), q)
@test in(@NT(Key=>:a,Value=>2), q)
@test in(@NT(Key=>:a,Value=>3), q)
@test in(@NT(Key=>:b,Value=>4), q)
@test in(@NT(Key=>:b,Value=>5), q)

q = @from i in source_df begin
    @from j in source_df2
    @where j.a>1
    @select {Name=i.name,Age=i.age,Children=i.children,A=j.a,B=j.b}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(6,5)
@test q[:Name]==["John","John","Sally","Sally","Kirk","Kirk"]
@test q[:Age]==[23.,23.,42.,42.,59.,59.]
@test q[:Children]==[3,3,5,5,2,2]
@test q[:A]==[2,3,2,3,2,3]
@test q[:B]==[2.,3.,2.,3.,2.,3.]

source_nested_dict = Dict(:a=>[1,2,3], :b=>[4,5])

q = @from i in source_nested_dict begin
    @from j in i.second
    @where j>2
    @select {Key=i.first,Value=j}
    @collect
end

@test isa(q, Array{@NT(Key::Symbol,Value::Int),1})
@test length(q)==3
@test in(@NT(Key=>:a,Value=>3), q)
@test in(@NT(Key=>:b,Value=>4), q)
@test in(@NT(Key=>:b,Value=>5), q)

source_df_groupby = DataFrame(name=["John", "Sally", "Kirk"], children=[3,2,2])

x = @from i in source_df_groupby begin
    @group i.name by i.children
    @collect
end

@test isa(x, Array{Grouping{Nullable{Int},Nullable{String}}})
@test length(x)==2
@test x[1].key==3
@test x[1][:]==["John"]
@test x[2].key==2
@test x[2][:]==["Sally", "Kirk"]

x = @from i in source_df_groupby begin
    @group i by i.children
    @collect
end

@test isa(x, Array{Grouping{Nullable{Int},NamedTuples._NT_namechildren{Nullable{String},Nullable{Int}}},1})
@test length(x)==2
@test x[1].key==3
@test x[1][1].name=="John";
@test x[2].key==2
@test x[2][1].name=="Sally";
@test x[2][2].name=="Kirk";

q = @from i in source_df_groupby begin
    @group i by i.children into g
    @select {Children=g.key,Number_of_parents=length(g)}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(2,2)
@test q[:Children]==[3,2]
@test q[:Number_of_parents]==[1,2]

q = @from i in source_df begin
    @where i.age>30. && i.children > 2
    @select i into j
    @select {Name=lowercase(j.name)}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(1,1)
@test q[1,:Name]=="sally"

q = @from i in source_df2 begin
    @join j in source_typedtable2 on get(i.a) equals convert(Int,j.c) into k
    @select {i.a,i.b,c=k}
    @collect
end

@test isa(q,Array{NamedTuples._NT_abc{Nullable{Int},Nullable{Float64},Array{NamedTuples._NT_cd{Float64,String},1}},1})
@test length(q)==3
@test q[1].a==1
@test q[1].b==1.
@test isa(q[1].c, Array{NamedTuples._NT_cd{Float64,String},1})
@test length(q[1].c)==0
@test q[2].a==2
@test q[2].b==2.
@test isa(q[2].c, Array{NamedTuples._NT_cd{Float64,String},1})
@test length(q[2].c)==2
@test q[2].c[1].c==2.
@test q[2].c[1].d== "John"
@test q[2].c[2].c==2.
@test q[2].c[2].d== "Sally"
@test q[3].a==3
@test q[3].b==3.
@test isa(q[3].c, Array{NamedTuples._NT_cd{Float64,String},1})
@test length(q[3].c)==0

q = @from i in source_df2 begin
    @join j in source_typedtable2 on get(i.a) equals convert(Int,j.c) into k
    @where length(k)>0
    @select {i.a,i.b,c=k}
    @collect
end

@test isa(q,Array{NamedTuples._NT_abc{Nullable{Int},Nullable{Float64},Array{NamedTuples._NT_cd{Float64,String},1}},1})
@test length(q)==1
@test q[1].a==2
@test q[1].b==2.
@test isa(q[1].c, Array{NamedTuples._NT_cd{Float64,String},1})
@test length(q[1].c)==2
@test q[1].c[1].c==2.
@test q[1].c[1].d== "John"
@test q[1].c[2].c==2.
@test q[1].c[2].d== "Sally"

sqlite_db = SQLite.DB(joinpath(Pkg.dir("SQLite"), "test", "Chinook_Sqlite.sqlite"))

q = @from i in SQLite.Source(sqlite_db,"SELECT * FROM Employee") begin
    @where i.ReportsTo==2
    @select {Name=i.LastName, Adr=i.Address}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(3,2)
@test q[:Name]==["Peacock","Park","Johnson"]
@test q[:Adr]==["1111 6 Ave SW", "683 10 Street SW", "7727B 41 Ave"]

source_json_string = """
{
    "Students": [
        {
            "Name": "John",
            "Parents": [ {"name": "Paul"}, {"name": "Mary"}]
        },
        {
            "Name": "Steward",
            "Parents": [ {"name": "George"} ]
        },
        {
            "Name": "Felix",
            "Parents": [ {"name": "Greg"}, {"name": "Susan"}]
        },
        {
            "Name": "Sara",
            "Parents": [ {"name": "Susan"}]
        }
    ]
}
"""

q = @from student in JSON.parse(source_json_string)["Students"] begin
    @from parent in student["Parents"]
    @select {Student=student["Name"], Parent=parent["name"]}
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(6,2)
@test q[:Student] == Any["John", "John", "Steward", "Felix", "Felix", "Sara"]
@test q[:Parent] == Any["Paul", "Mary", "George", "Greg", "Susan", "Susan"]

q = @from i in Feather.Source(joinpath(Pkg.dir("Feather"),"test", "data", "airquality.feather")) begin
    @where i.Day==2
    @select i.Month
    @collect
end

@test isa(q, Array{Int32,1})
@test q==[5,6,7,8,9]

source_df_nulls = DataFrame(name=@data(["John", "Sally", NA, "Kirk"]), age=[23., 42., 54., 59.], children=@data([3,NA,8,2]))
q = @from i in source_df_nulls begin
    @select i
    @collect DataFrame
end

@test isa(q, DataFrame)
@test size(q)==(4,3)
@test q[1,:name]=="John"
@test q[2,:name]=="Sally"
@test isna(q[3,:name])
@test q[4,:name]=="Kirk"
@test q[:age]==@data([23., 42., 54., 59.])
@test q[1,:children]==3
@test isna(q[2,:children])
@test q[3,:children]==8
@test q[4,:children]==2

include("test_ndsparsedata.jl")

end

@testset "Operators" begin
include("test_operators.jl")
end

@testset "Examples" begin
    include("../example/01-DataFrame.jl")
    include("../example/02-Dict.jl")
    include("../example/03-Array.jl")
    include("../example/04-SQLite.jl")
    include("../example/05-Nullable.jl")
    include("../example/06-Generator.jl")
    include("../example/07-typedtables.jl")
    include("../example/08-join.jl")
    include("../example/09-let.jl")
    include("../example/10-orderby.jl")
    include("../example/11-Datastream.jl")
    is_installed("NDSparseData") && include("../example/12-NDSparseData.jl")
    include("../example/13-selectmany.jl")
    include("../example/14-groupby.jl")
    include("../example/15-groupinto.jl")
    include("../example/16-selectinto.jl")
    include("../example/17-groupjoin.jl")
    include("../example/18-orderby-nested.jl")
    include("../example/19-feather.jl")
    include("../example/20-json.jl")
    include("../example/21-nulls.jl")
end


text:
include("isValidPair.jl");
function isValidSet(set)
    setLength = length(set);
    if (setLength < 2)
        return true;
    end
    for j = 1:(setLength-1)
        for k = (j+1):setLength
            valid = isValidPair(set[j], set[k]);
            if (!valid)
                return false;
            end
        end
    end
    return true;
end

max_stars_repo_name: driesverhees/dobble

max_issues_repo_name: driesverhees/dobble

max_forks_repo_name: driesverhees/dobble


text:
using BinaryBuilder

name = "Unishox"
version = v"1.0.2"
sources = [
    ArchiveSource("https://github.com/siara-cc/Unishox2/archive/refs/tags/$(version).tar.gz", "24391d16d4f84f239bb97eb704d80231221a9a58743a87ae1ca7eed27cf7e9bb"),
]

script = raw"""
cd $WORKSPACE/srcdir/Unishox*
mkdir -p "${libdir}"
cc -o ${libdir}/libunishox.${dlext} unishox2.c -shared -std=gnu11 -fPIC -Werror -Wall -Wcast-align -Wpointer-arith -Wformat-security -Wmissing-format-attribute -W -Wno-error=format-nonliteral
"""

platforms = supported_platforms()

products = [
    LibraryProduct("libunishox", :libunishox),
]

dependencies = Dependency[
]

build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; preferred_gcc_version=v"7", julia_compat="1.6")

max_stars_repo_name: jakebolewski/Yggdrasil

max_issues_repo_name: jakebolewski/Yggdrasil

max_forks_repo_name: jakebolewski/Yggdrasil


text:
using Accessors

export flatten

"""
    flatten(x::Tuple)
    flatten(x::NamedTuple)

`flatten` a nested tuple or named tuple. The result will be a tuple consisting of the
leaves.

EXAMPLE:
```
julia> x = randnt(3,2)
(y = (f = :f, b = :b, t = :t), w = (m = :m, f = :f), s = (m = :m, v = :v, q = :q))

julia> flatten(x)
(:f, :b, :t, :m, :f, :m, :v, :q)
```
"""

flatten(x, y...) = (flatten(x)..., flatten(y...)...)
flatten(x::Tuple) = flatten(x...)
flatten(x::NamedTuple) = flatten(values(x)...)
flatten(x) = (x,)

using GeneralizedGenerated

"""
    leaf_setter(x::Tuple)
    leaf_setter(x::NamedTuple)
    leaf_setter(::Type)

Return a function for constructing values with the same schema as `x`, given
values for the leaves.

EXAMPLE:
```
julia> x = randnt(2,2)
(b = (b = :b, n = :n), k = (h = :h, t = :t))

julia> f = leaf_setter(x)
function = (##265, ##266, ##267, ##268;) -> begin
    begin
        (b = (b = var"##265", n = var"##266"), k = (h = var"##267", t = var"##268"))
    end
end

julia> @btime (\$f)(1,2,3,4)
  0.010 ns (0 allocations: 0 bytes)
(b = (b = 1, n = 2), k = (h = 3, t = 4))
```
"""
function leaf_setter end

export leaf_setter

leaf_setter(::Type{T}) where {T} = leaf_setter(schema(T))

@gg function leaf_setter(x::NamedTuple)
    x = schema(x)
    _leaf_setter(x)
end

@gg function leaf_setter(x::Tuple)
    x = schema(x)
    _leaf_setter(x)
end

function _leaf_setter(x)
    (names, body) = exprify(x)
    args = Expr(:tuple, names...)

    return :($args -> $body)
end

export Leaves

struct Leaves end

import Accessors

Accessors.OpticStyle(::Leaves) = ModifyBased()

function Accessors.modify(f, obj, ::Leaves)
    vs = flatten(unwrap(obj))
    args = f.(vs)
    return leaf_setter(obj)(args...)
end


text:
using DataFrames

using Plots
using JLD2

using Distributions
using StatsBase
using IterTools
using EmpiricalBayes
using KernelDensity
using LaTeXStrings
using RCall
using FileIO

brad_degs = collect(1:15)

n_settings = 8

j = parse(Int64, ARGS[1])

par_comb = []
for (set,k) in IterTools.product(1:n_settings, 1:6)
    push!(par_comb, Dict(:setting => set, :k=>k))
end

s = par_comb[j][:setting]
setting_idx = s
k = par_comb[j][:k]

#set_idx = [Regex(string("mysim_",x, )) for x in 1:n_settings];

set_idx = Regex(string("mysim_",s,"_",k,"_"))

marginal_grid = collect(range(-6,stop=6,length=1001));
prior_grid = collect(range(-3,stop=3,length=121));
marginal_h = marginal_grid[2]-marginal_grid[1];

true_dists = [EmpiricalBayes.easy_dist, EmpiricalBayes.hard_dist]

#true_dists = zip( true_dists, d_trues)
xs = collect(-3.0:0.25:3.0)
minimax_σs = [0.2]
ms = [10_000; 40_000]
targets =[ [PosteriorTarget(PosteriorMeanNumerator(x)) for x in xs],
           [PosteriorTarget(LFSRNumerator(x)) for x in xs]]
combs = []

for (true_dist, target, σ, m) in IterTools.product(true_dists, targets, minimax_σs, ms)
    push!(combs, Dict(:dist=>true_dist, :target=>target, :σ=>σ, :m=>m ))
end

my_df = DataFrame( setting_idx = Int64[],
                   true_theta = Float64[],
                   method = String[],
                   dof = Int64[],
                   x=Float64[],
                   est = Float64[],
                   ci_left = Float64[],
                   ci_right = Float64[],
                   max_bias = Float64[])

#for setting_idx=1:n_settings
    res_list = readdir("/scratch/users/ignat/sims/base_sim_Jan10_v2");
    res_list = res_list[occursin.(Ref(set_idx), res_list)]

    # just to get d_true once
    file = string("/scratch/users/ignat/sims/base_sim_Jan10_v2/", res_list[1]);
    res = FileIO.load(file,"res");
    setting_idx = res[1]
    combo = res[2]
    d_true = NormalConvolutionProblem(combo[:dist], marginal_grid);

    for f in 1:length(res_list)
        @show f
        file = string("/scratch/users/ignat/sims/base_sim_Jan10_v2/", res_list[f]);
        res = FileIO.load(file,"res");
        setting_idx = res[1]
        combo = res[2]
        res_details = res[3][1]
        brad_combs = res_details[2]
        calib_vec = res_details[1]
        for l in 1:length(calib_vec)
            calib_x = calib_vec[l]
            t = combo[:target][l]
            x = t.num.x
            true_θ = posterior_stats(d_true,t)[3]
            #efron_est = estimate(brad,t)
            calib_est = estimate(calib_x, t)
            calib_ci_left, calib_ci_right = confint(calib_x,t)
            max_bias = maxbias(calib_x, t)
            #efron_ci_left, efron_ci_right = confint(brad, t)
            push!(my_df, (setting_idx, true_θ, "Calibrator", 0, x,
                         calib_est, calib_ci_left, calib_ci_right, max_bias))

            for d in 1:length(brad_degs)
                #@show d
                brad = brad_combs[d]
                d_b = brad_degs[d]
                efron_est = estimate(brad,t; debias=false)
                efron_ci_left, efron_ci_right = confint(brad, t; debias=false)
                efron_max_bias = maxbias(brad, t)
                push!(my_df, (setting_idx, true_θ, "Efron", d_b, x,
                       efron_est, efron_ci_left, efron_ci_right, efron_max_bias))
            end
        end
    end
#end

@save "/scratch/users/ignat/sims/base_sim_Jan10_v2/dfs/df_$(s)_$(k).jld2" my_df

#typeof(calib_x)
#DataFrame(setting_idx = res[1])


text:
using Distributions

# sampling from exact partial posterior
function linreg_exact_posterior(x::Array{Float64,1}, y::Array{Float64,1}, prior_std::Float64, noise_std::Float64)
    # intercept comes first, then slope
    n = length(x)
    @assert n == length(y)
    S0 = prior_std * prior_std * eye(2)
    phi = hcat(ones(n), x)
    @assert size(phi) == (n, 2)
    noise_var = noise_std * noise_std
    noise_precision = 1./noise_var
    SN = inv(inv(S0) + noise_precision * (phi' * phi))
    mN = SN * ((inv(S0) * zeros(2)) + noise_precision * (phi' * y))
    # return the mean vector and covariance matrix
    (mN, SN)
end

immutable ExactLinregSampler <: Sampler
    dist::MvNormal
    function ExactLinregSampler(prior_std::Float64, noise_std::Float64, x::Array{Float64,1}, y::Array{Float64,1})
        (mN, SN) = linreg_exact_posterior(x, y, prior_std, noise_std)
        dist = MvNormal(mN, SN)
        new(dist)
    end
end

function ExactLinregSampler(problem::Problem)
    ExactLinregSampler(problem.prior_std, problem.noise_std, problem.x, problem.y)
end

function simulate(sampler::ExactLinregSampler)
    intercept_and_slope = rand(sampler.dist)
    log_weight = logpdf(sampler.dist, intercept_and_slope)
    (intercept_and_slope, log_weight)
end

function regenerate(sampler::ExactLinregSampler, intercept_and_slope::Array{Float64,1})
    @assert length(intercept_and_slope) == 2
    logpdf(sampler.dist, intercept_and_slope)
end


text:
#= GAP code:
H := [];
for i in [2..30] do
    Add(H, List(AllSmallGroups(i), G->Image(IsomorphismPermGroup(G))));
od;
PrintTo("/tmp/groups.gap", H);
=#

#=julia code
GAPgroups_str = join(readlines("/tmp/group.gap"), "");
GAPgroups_str = replace(GAPgroups_str, "Group"=>"\nPermGroup");
GAPgroups_str = replace(GAPgroups_str, r" *"=>"");
perm_regex = r"((\(\d+(,\d+)*\)?)+)";
print(Meta.parse(replace(GAPgroups_str, perm_regex=> s"perm\"\1\"")))
=#

const SmallPermGroups = Dict(
    i + 1 => x
    for
    (i, x) in enumerate([
        [PermGroup([perm"(1,2)"])],
        [PermGroup([perm"(1,2,3)"])],
        [PermGroup([perm"(1,2,3,4)"]), PermGroup([perm"(1,2)", perm"(3,4)"])],
        [PermGroup([perm"(1,2,3,4,5)"])],
        [
            PermGroup([perm"(1,2)(3,6)(4,5)", perm"(1,3,5)(2,4,6)"]),
            PermGroup([perm"(1,2)", perm"(3,4,5)"]),
        ],
        [PermGroup([perm"(1,2,3,4,5,6,7)"])],
        [
            PermGroup([perm"(1,2,3,4,5,6,7,8)"]),
            PermGroup([perm"(1,2)", perm"(3,4,5,6)"]),
            PermGroup([
                perm"(1,2)(3,8)(4,6)(5,7)",
                perm"(1,3)(2,5)(4,7)(6,8)",
                perm"(1,4)(2,6)(3,7)(5,8)",
            ]),
            PermGroup([
                perm"(1,2,4,6)(3,8,7,5)",
                perm"(1,3,4,7)(2,5,6,8)",
                perm"(1,4)(2,6)(3,7)(5,8)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4)", perm"(5,6)"]),
        ],
        [
            PermGroup([perm"(1,2,3,4,5,6,7,8,9)"]),
            PermGroup([perm"(1,2,3)", perm"(4,5,6)"]),
        ],
        [
            PermGroup([
                perm"(1,2)(3,10)(4,9)(5,8)(6,7)",
                perm"(1,3,5,7,9)(2,4,6,8,10)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5,6,7)"]),
        ],
        [PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11)"])],
        [
            PermGroup([
                perm"(1,2,3,5)(4,10,7,12)(6,11,9,8)",
                perm"(1,3)(2,5)(4,7)(6,9)(8,11)(10,12)",
                perm"(1,4,8)(2,6,10)(3,7,11)(5,9,12)",
            ]),
            PermGroup([perm"(1,2,3)", perm"(4,5,6,7)"]),
            PermGroup([
                perm"(1,2,5)(3,7,12)(4,11,9)(6,10,8)",
                perm"(1,3)(2,6)(4,8)(5,9)(7,11)(10,12)",
                perm"(1,4)(2,7)(3,8)(5,10)(6,11)(9,12)",
            ]),
            PermGroup([
                perm"(1,2)(3,5)(4,10)(6,8)(7,12)(9,11)",
                perm"(1,3)(2,5)(4,7)(6,9)(8,11)(10,12)",
                perm"(1,4,8)(2,6,10)(3,7,11)(5,9,12)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4)", perm"(5,6,7)"]),
        ],
        [PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13)"])],
        [
            PermGroup([
                perm"(1,2)(3,14)(4,13)(5,12)(6,11)(7,10)(8,9)",
                perm"(1,3,5,7,9,11,13)(2,4,6,8,10,12,14)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5,6,7,8,9)"]),
        ],
        [PermGroup([perm"(1,2,3)", perm"(4,5,6,7,8)"])],
        [
            PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)"]),
            PermGroup([perm"(1,2,3,4)", perm"(5,6,7,8)"]),
            PermGroup([
                perm"(1,2,5,8)(3,12,10,16)(4,7,11,14)(6,15,13,9)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,12)(8,13)(11,15)(14,16)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,12)(8,14)(10,15)(13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([
                perm"(1,2,5,8)(3,12,10,16)(4,7,11,14)(6,15,13,9)",
                perm"(1,3,4,9)(2,6,7,12)(5,10,11,15)(8,13,14,16)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,12)(8,14)(10,15)(13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5,6,7,8,9,10)"]),
            PermGroup([
                perm"(1,2,4,7,5,8,11,14)(3,13,9,16,10,6,15,12)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,12)(8,13)(11,15)(14,16)",
                perm"(1,4,5,11)(2,7,8,14)(3,9,10,15)(6,12,13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([
                perm"(1,2)(3,12)(4,14)(5,8)(6,9)(7,11)(10,16)(13,15)",
                perm"(1,3)(2,6)(4,15)(5,10)(7,16)(8,13)(9,11)(12,14)",
                perm"(1,4,5,11)(2,7,8,14)(3,9,10,15)(6,12,13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([
                perm"(1,2,5,8)(3,12,10,16)(4,14,11,7)(6,15,13,9)",
                perm"(1,3)(2,6)(4,15)(5,10)(7,16)(8,13)(9,11)(12,14)",
                perm"(1,4,5,11)(2,7,8,14)(3,9,10,15)(6,12,13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([
                perm"(1,2,5,8)(3,12,10,16)(4,14,11,7)(6,15,13,9)",
                perm"(1,3,5,10)(2,6,8,13)(4,15,11,9)(7,16,14,12)",
                perm"(1,4,5,11)(2,7,8,14)(3,9,10,15)(6,12,13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4)", perm"(5,6,7,8)"]),
            PermGroup([
                perm"(1,2)(3,13)(4,7)(5,8)(6,10)(9,16)(11,14)(12,15)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,12)(8,13)(11,15)(14,16)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,12)(8,14)(10,15)(13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([
                perm"(1,2,5,8)(3,13,10,6)(4,7,11,14)(9,16,15,12)",
                perm"(1,3,5,10)(2,6,8,13)(4,9,11,15)(7,12,14,16)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,12)(8,14)(10,15)(13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([
                perm"(1,2)(3,13)(4,7)(5,8)(6,10)(9,16)(11,14)(12,15)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,12)(8,13)(11,15)(14,16)",
                perm"(1,4,5,11)(2,7,8,14)(3,9,10,15)(6,12,13,16)",
                perm"(1,5)(2,8)(3,10)(4,11)(6,13)(7,14)(9,15)(12,16)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4)", perm"(5,6)", perm"(7,8)"]),
        ],
        [PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17)"])],
        [
            PermGroup([
                perm"(1,2)(3,18)(4,12)(5,17)(6,9)(7,16)(8,15)(10,14)(11,13)",
                perm"(1,3,7,4,8,13,9,14,17)(2,5,10,6,11,15,12,16,18)",
                perm"(1,4,9)(2,6,12)(3,8,14)(5,11,16)(7,13,17)(10,15,18)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5,6,7,8,9,10,11)"]),
            PermGroup([
                perm"(1,2)(3,5)(4,12)(6,9)(7,10)(8,16)(11,14)(13,18)(15,17)",
                perm"(1,3,7)(2,5,10)(4,8,13)(6,11,15)(9,14,17)(12,16,18)",
                perm"(1,4,9)(2,6,12)(3,8,14)(5,11,16)(7,13,17)(10,15,18)",
            ]),
            PermGroup([
                perm"(1,2)(3,10)(4,12)(5,7)(6,9)(8,18)(11,17)(13,16)(14,15)",
                perm"(1,3,7)(2,5,10)(4,8,13)(6,11,15)(9,14,17)(12,16,18)",
                perm"(1,4,9)(2,6,12)(3,8,14)(5,11,16)(7,13,17)(10,15,18)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5)", perm"(6,7,8)"]),
        ],
        [PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19)"])],
        [
            PermGroup([
                perm"(1,2,3,5)(4,18,7,20)(6,19,9,16)(8,14,11,17)(10,15,13,12)",
                perm"(1,3)(2,5)(4,7)(6,9)(8,11)(10,13)(12,15)(14,17)(16,19)(18,20)",
                perm"(1,4,8,12,16)(2,6,10,14,18)(3,7,11,15,19)(5,9,13,17,20)",
            ]),
            PermGroup([perm"(1,2,3,4)", perm"(5,6,7,8,9)"]),
            PermGroup([
                perm"(1,2,3,5)(4,10,19,17)(6,11,20,12)(7,13,16,14)(8,18,15,9)",
                perm"(1,3)(2,5)(4,19)(6,20)(7,16)(8,15)(9,18)(10,17)(11,12)(13,14)",
                perm"(1,4,8,12,16)(2,6,10,14,18)(3,7,11,15,19)(5,9,13,17,20)",
            ]),
            PermGroup([
                perm"(1,2)(3,5)(4,18)(6,16)(7,20)(8,14)(9,19)(10,12)(11,17)(13,15)",
                perm"(1,3)(2,5)(4,7)(6,9)(8,11)(10,13)(12,15)(14,17)(16,19)(18,20)",
                perm"(1,4,8,12,16)(2,6,10,14,18)(3,7,11,15,19)(5,9,13,17,20)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4)", perm"(5,6,7,8,9)"]),
        ],
        [
            PermGroup([
                perm"(1,2,4)(3,8,16)(5,10,12)(6,14,7)(9,20,19)(11,21,15)(13,18,17)",
                perm"(1,3,6,9,12,15,18)(2,5,8,11,14,17,20)(4,7,10,13,16,19,21)",
            ]),
            PermGroup([perm"(1,2,3)", perm"(4,5,6,7,8,9,10)"]),
        ],
        [
            PermGroup([
                perm"(1,2)(3,22)(4,21)(5,20)(6,19)(7,18)(8,17)(9,16)(10,15)(11,14)(12,13)",
                perm"(1,3,5,7,9,11,13,15,17,19,21)(2,4,6,8,10,12,14,16,18,20,22)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5,6,7,8,9,10,11,12,13)"]),
        ],
        [PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23)"])],
        [
            PermGroup([
                perm"(1,2,3,6,4,7,9,13)(5,16,10,21,11,22,17,24)(8,18,14,19,15,23,20,12)",
                perm"(1,3,4,9)(2,6,7,13)(5,10,11,17)(8,14,15,20)(12,18,19,23)(16,21,22,24)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,13)(8,15)(10,17)(12,19)(14,20)(16,22)(18,23)(21,24)",
                perm"(1,5,12)(2,8,16)(3,10,18)(4,11,19)(6,14,21)(7,15,22)(9,17,23)(13,20,24)",
            ]),
            PermGroup([perm"(1,2,3)", perm"(4,5,6,7,8,9,10,11)"]),
            PermGroup([
                perm"(1,2,6)(3,8,20)(4,16,13)(5,9,15)(7,14,10)(11,18,24)(12,23,21)(17,22,19)",
                perm"(1,3,5,11)(2,7,9,17)(4,19,12,10)(6,13,15,21)(8,23,18,16)(14,24,22,20)",
                perm"(1,4,5,12)(2,8,9,18)(3,10,11,19)(6,14,15,22)(7,16,17,23)(13,20,21,24)",
                perm"(1,5)(2,9)(3,11)(4,12)(6,15)(7,17)(8,18)(10,19)(13,21)(14,22)(16,23)(20,24)",
            ]),
            PermGroup([
                perm"(1,2,4,7)(3,13,9,6)(5,16,11,22)(8,19,15,12)(10,24,17,21)(14,18,20,23)",
                perm"(1,3,4,9)(2,6,7,13)(5,10,11,17)(8,14,15,20)(12,18,19,23)(16,21,22,24)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,13)(8,15)(10,17)(12,19)(14,20)(16,22)(18,23)(21,24)",
                perm"(1,5,12)(2,8,16)(3,10,18)(4,11,19)(6,14,21)(7,15,22)(9,17,23)(13,20,24)",
            ]),
            PermGroup([
                perm"(1,2)(3,6)(4,7)(5,16)(8,12)(9,13)(10,21)(11,22)(14,18)(15,19)(17,24)(20,23)",
                perm"(1,3,4,9)(2,6,7,13)(5,10,11,17)(8,14,15,20)(12,18,19,23)(16,21,22,24)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,13)(8,15)(10,17)(12,19)(14,20)(16,22)(18,23)(21,24)",
                perm"(1,5,12)(2,8,16)(3,10,18)(4,11,19)(6,14,21)(7,15,22)(9,17,23)(13,20,24)",
            ]),
            PermGroup([
                perm"(1,2)(3,13)(4,7)(5,16)(6,9)(8,12)(10,24)(11,22)(14,23)(15,19)(17,21)(18,20)",
                perm"(1,3,4,9)(2,6,7,13)(5,10,11,17)(8,14,15,20)(12,18,19,23)(16,21,22,24)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,13)(8,15)(10,17)(12,19)(14,20)(16,22)(18,23)(21,24)",
                perm"(1,5,12)(2,8,16)(3,10,18)(4,11,19)(6,14,21)(7,15,22)(9,17,23)(13,20,24)",
            ]),
            PermGroup([
                perm"(1,2,4,7)(3,6,9,13)(5,16,11,22)(8,19,15,12)(10,21,17,24)(14,23,20,18)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,13)(8,14)(11,17)(12,18)(15,20)(16,21)(19,23)(22,24)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,13)(8,15)(10,17)(12,19)(14,20)(16,22)(18,23)(21,24)",
                perm"(1,5,12)(2,8,16)(3,10,18)(4,11,19)(6,14,21)(7,15,22)(9,17,23)(13,20,24)",
            ]),
            PermGroup([
                perm"(1,2)(3,13)(4,7)(5,16)(6,9)(8,12)(10,24)(11,22)(14,23)(15,19)(17,21)(18,20)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,13)(8,14)(11,17)(12,18)(15,20)(16,21)(19,23)(22,24)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,13)(8,15)(10,17)(12,19)(14,20)(16,22)(18,23)(21,24)",
                perm"(1,5,12)(2,8,16)(3,10,18)(4,11,19)(6,14,21)(7,15,22)(9,17,23)(13,20,24)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5)", perm"(6,7,8,9)"]),
            PermGroup([
                perm"(1,2)(3,14)(4,7)(5,8)(6,10)(9,21)(11,15)(12,16)(13,18)(17,24)(19,22)(20,23)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,13)(8,14)(11,17)(12,18)(15,20)(16,21)(19,23)(22,24)",
                perm"(1,4,11)(2,7,15)(3,9,17)(5,12,19)(6,13,20)(8,16,22)(10,18,23)(14,21,24)",
                perm"(1,5)(2,8)(3,10)(4,12)(6,14)(7,16)(9,18)(11,19)(13,21)(15,22)(17,23)(20,24)",
            ]),
            PermGroup([
                perm"(1,2,5,8)(3,14,10,6)(4,7,12,16)(9,21,18,13)(11,15,19,22)(17,24,23,20)",
                perm"(1,3,5,10)(2,6,8,14)(4,9,12,18)(7,13,16,21)(11,17,19,23)(15,20,22,24)",
                perm"(1,4,11)(2,7,15)(3,9,17)(5,12,19)(6,13,20)(8,16,22)(10,18,23)(14,21,24)",
                perm"(1,5)(2,8)(3,10)(4,12)(6,14)(7,16)(9,18)(11,19)(13,21)(15,22)(17,23)(20,24)",
            ]),
            PermGroup([
                perm"(1,2)(3,13)(4,8)(5,7)(6,9)(10,21)(11,20)(12,16)(14,18)(15,17)(19,24)(22,23)",
                perm"(1,3,9)(2,6,13)(4,11,23)(5,19,17)(7,15,24)(8,22,20)(10,18,12)(14,21,16)",
                perm"(1,4)(2,7)(3,10)(5,12)(6,14)(8,16)(9,17)(11,19)(13,20)(15,22)(18,23)(21,24)",
                perm"(1,5)(2,8)(3,11)(4,12)(6,15)(7,16)(9,18)(10,19)(13,21)(14,22)(17,23)(20,24)",
            ]),
            PermGroup([
                perm"(1,2)(3,6)(4,7)(5,8)(9,13)(10,14)(11,15)(12,16)(17,20)(18,21)(19,22)(23,24)",
                perm"(1,3,9)(2,6,13)(4,11,23)(5,19,17)(7,15,24)(8,22,20)(10,18,12)(14,21,16)",
                perm"(1,4)(2,7)(3,10)(5,12)(6,14)(8,16)(9,17)(11,19)(13,20)(15,22)(18,23)(21,24)",
                perm"(1,5)(2,8)(3,11)(4,12)(6,15)(7,16)(9,18)(10,19)(13,21)(14,22)(17,23)(20,24)",
            ]),
            PermGroup([
                perm"(1,2)(3,6)(4,7)(5,16)(8,12)(9,13)(10,21)(11,22)(14,18)(15,19)(17,24)(20,23)",
                perm"(1,3)(2,6)(4,9)(5,10)(7,13)(8,14)(11,17)(12,18)(15,20)(16,21)(19,23)(22,24)",
                perm"(1,4)(2,7)(3,9)(5,11)(6,13)(8,15)(10,17)(12,19)(14,20)(16,22)(18,23)(21,24)",
                perm"(1,5,12)(2,8,16)(3,10,18)(4,11,19)(6,14,21)(7,15,22)(9,17,23)(13,20,24)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4)", perm"(5,6)", perm"(7,8,9)"]),
        ],
        [
            PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)"]),
            PermGroup([perm"(1,2,3,4,5)", perm"(6,7,8,9,10)"]),
        ],
        [
            PermGroup([
                perm"(1,2)(3,26)(4,25)(5,24)(6,23)(7,22)(8,21)(9,20)(10,19)(11,18)(12,17)(13,16)(14,15)",
                perm"(1,3,5,7,9,11,13,15,17,19,21,23,25)(2,4,6,8,10,12,14,16,18,20,22,24,26)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5,6,7,8,9,10,11,12,13,14,15)"]),
        ],
        [
            PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27)"]),
            PermGroup([perm"(1,2,3)", perm"(4,5,6,7,8,9,10,11,12)"]),
            PermGroup([
                perm"(1,2,5)(3,14,25)(4,7,12)(6,19,17)(8,26,24)(9,22,11)(10,15,20)(13,27,16)(18,23,21)",
                perm"(1,3,8)(2,6,13)(4,9,16)(5,11,18)(7,14,21)(10,17,23)(12,19,24)(15,22,26)(20,25,27)",
                perm"(1,4,10)(2,7,15)(3,9,17)(5,12,20)(6,14,22)(8,16,23)(11,19,25)(13,21,26)(18,24,27)",
            ]),
            PermGroup([
                perm"(1,2,5,4,7,12,10,15,20)(3,14,25,9,22,11,17,6,19)(8,26,24,16,13,27,23,21,18)",
                perm"(1,3,8)(2,6,13)(4,9,16)(5,11,18)(7,14,21)(10,17,23)(12,19,24)(15,22,26)(20,25,27)",
                perm"(1,4,10)(2,7,15)(3,9,17)(5,12,20)(6,14,22)(8,16,23)(11,19,25)(13,21,26)(18,24,27)",
            ]),
            PermGroup([perm"(1,2,3)", perm"(4,5,6)", perm"(7,8,9)"]),
        ],
        [
            PermGroup([
                perm"(1,2,3,5)(4,26,7,28)(6,27,9,24)(8,22,11,25)(10,23,13,20)(12,18,15,21)(14,19,17,16)",
                perm"(1,3)(2,5)(4,7)(6,9)(8,11)(10,13)(12,15)(14,17)(16,19)(18,21)(20,23)(22,25)(24,27)(26,28)",
                perm"(1,4,8,12,16,20,24)(2,6,10,14,18,22,26)(3,7,11,15,19,23,27)(5,9,13,17,21,25,28)",
            ]),
            PermGroup([perm"(1,2,3,4)", perm"(5,6,7,8,9,10,11)"]),
            PermGroup([
                perm"(1,2)(3,5)(4,26)(6,24)(7,28)(8,22)(9,27)(10,20)(11,25)(12,18)(13,23)(14,16)(15,21)(17,19)",
                perm"(1,3)(2,5)(4,7)(6,9)(8,11)(10,13)(12,15)(14,17)(16,19)(18,21)(20,23)(22,25)(24,27)(26,28)",
                perm"(1,4,8,12,16,20,24)(2,6,10,14,18,22,26)(3,7,11,15,19,23,27)(5,9,13,17,21,25,28)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4)", perm"(5,6,7,8,9,10,11)"]),
        ],
        [PermGroup([perm"(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29)"])],
        [
            PermGroup([
                perm"(1,2)(3,5)(4,12)(6,9)(7,10)(8,18)(11,15)(13,16)(14,24)(17,21)(19,22)(20,28)(23,26)(25,30)(27,29)",
                perm"(1,3,7,13,19)(2,5,10,16,22)(4,8,14,20,25)(6,11,17,23,27)(9,15,21,26,29)(12,18,24,28,30)",
                perm"(1,4,9)(2,6,12)(3,8,15)(5,11,18)(7,14,21)(10,17,24)(13,20,26)(16,23,28)(19,25,29)(22,27,30)",
            ]),
            PermGroup([
                perm"(1,2)(3,5)(4,24)(6,21)(7,10)(8,28)(9,18)(11,26)(12,15)(13,30)(14,23)(16,29)(17,20)(19,27)(22,25)",
                perm"(1,3,7)(2,5,10)(4,8,13)(6,11,16)(9,14,19)(12,17,22)(15,20,25)(18,23,27)(21,26,29)(24,28,30)",
                perm"(1,4,9,15,21)(2,6,12,18,24)(3,8,14,20,26)(5,11,17,23,28)(7,13,19,25,29)(10,16,22,27,30)",
            ]),
            PermGroup([
                perm"(1,2)(3,10)(4,24)(5,7)(6,21)(8,30)(9,18)(11,29)(12,15)(13,28)(14,27)(16,26)(17,25)(19,23)(20,22)",
                perm"(1,3,7)(2,5,10)(4,8,13)(6,11,16)(9,14,19)(12,17,22)(15,20,25)(18,23,27)(21,26,29)(24,28,30)",
                perm"(1,4,9,15,21)(2,6,12,18,24)(3,8,14,20,26)(5,11,17,23,28)(7,13,19,25,29)(10,16,22,27,30)",
            ]),
            PermGroup([perm"(1,2)", perm"(3,4,5)", perm"(6,7,8,9,10)"]),
        ],
    ])
)


text:
include("algorithms.jl")
include("conversion.jl")
include("colordiff.jl")
include("din99.jl")


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:4] <= 1)

                     @variable(m, -25.420040452488465 <= q <= 21.65452636072683)

                     add_NL_constraint(m, :(swish(-0.9974376164994152 + 0.7314791518637902*swish(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4])) + 0.4470938857218645*swish(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4])) + 0.10010754470216687*swish(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4])) + -0.8594790184444285*swish(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4])) + -0.4658863904521331*swish(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))) + swish(0.15396139316976853 + -0.4228510094486002*swish(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4])) + -0.8035341866400141*swish(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4])) + -0.07617073018159282*swish(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4])) + 0.3940887684836425*swish(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4])) + 0.6667343490308526*swish(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))) + swish(0.9665409577623398 + -0.449175249339572*swish(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4])) + -0.2640107596849468*swish(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4])) + 0.7284419447850534*swish(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4])) + 0.5662248826250997*swish(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4])) + -0.21454884110410477*swish(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))) + swish(-0.1582635851091898 + 0.5103556986884796*swish(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4])) + -0.6017569427714062*swish(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4])) + -0.23749573380464106*swish(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4])) + -0.2344836196764124*swish(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4])) + 0.07066758651932892*swish(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))) + swish(-0.47638200661148833 + 0.9126631115783219*swish(-0.8376089108524591 + -0.8472902966255957*$(x[1]) + -0.95763763606758*$(x[2]) + 0.3696542730614176*$(x[3]) + -0.09481436100741814*$(x[4])) + 0.35414400688245484*swish(0.34708131238661144 + 0.38455737939114654*$(x[1]) + 0.5946120518836455*$(x[2]) + 0.21996792037412316*$(x[3]) + -0.6970126448723701*$(x[4])) + -0.36037763135774403*swish(-0.38902444039423223 + -0.4012023975891066*$(x[1]) + -0.7732491328671305*$(x[2]) + -0.16777672441934754*$(x[3]) + -0.6363338156602314*$(x[4])) + -0.18657915153735738*swish(0.16738959928165498 + 0.5119956098239467*$(x[1]) + 0.7821421131636019*$(x[2]) + 0.25850635081101103*$(x[3]) + -0.9052769726690872*$(x[4])) + 0.7872605277677782*swish(0.1398101826443119 + 0.0438169969151434*$(x[1]) + -0.2051299657215857*$(x[2]) + 0.7229873931159991*$(x[3]) + 0.6169137554983704*$(x[4]))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
### A Pluto.jl notebook ###
# v0.12.7

using Markdown
using InteractiveUtils

# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49
using Pkg, DrWatson

# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72
begin
	@quickactivate "StatisticsWithJuliaPlutoNotebooks"
	using Random, StatsBase, DataFrames, Plots, Measures
	Random.seed!(1)
end;

# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549
md"## Listing 3.2"

# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b
begin
	pDiscrete = [0.25, 0.25, 0.5]
	xGridD = 0:2
end;

# ╔═╡ 7e20eac0-1f6d-11eb-23c8-f7f93c8ec92b
pContinuous(x) = 3/4*(1 - x^2)

# ╔═╡ 7e212a44-1f6d-11eb-17a5-a56e8476b5cf
xGridC = -1:0.01:1;

# ╔═╡ 7e21ad70-1f6d-11eb-1e7a-5982011bd333
pContinuous2(x) = x < 0 ? x+1 : 1-x

# ╔═╡ 7e2dde18-1f6d-11eb-2165-fd23fbaf928e
begin
	p1 = plot(xGridD, line=:stem, pDiscrete, marker=:circle, c=:blue, ms=6, msw=0)
	p2 = plot(xGridC, pContinuous.(xGridC), c=:blue)
	p3 = plot(xGridC, pContinuous2.(xGridC), c=:blue)

	plot(p1, p2, p3, layout=(1,3), legend=false, ylims=(0,1.1), xlabel="x",
		ylabel=["Probability" "Density" "Density"], size=(1200, 400), margin=5mm)
end

# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3
md"## End of listing 3.2"

# ╔═╡ Cell order:
# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549
# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49
# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72
# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b
# ╠═7e20eac0-1f6d-11eb-23c8-f7f93c8ec92b
# ╠═7e212a44-1f6d-11eb-17a5-a56e8476b5cf
# ╠═7e21ad70-1f6d-11eb-1e7a-5982011bd333
# ╠═7e2dde18-1f6d-11eb-2165-fd23fbaf928e
# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3


text:
#=

# Manipulating handles

## Creating a handle

=#

using SwiftShader_jll # hide
using Vulkan
@set_driver :SwiftShader # hide

const instance = Instance([], [])
const pdevice = first(unwrap(enumerate_physical_devices(instance)))
const device = Device(pdevice, [DeviceQueueCreateInfo(0, [1.0])], [], [])

# The most convenient way to create a handle is through its constructor

buffer = Buffer(
    device,
    100,
    BUFFER_USAGE_TRANSFER_SRC_BIT,
    SHARING_MODE_EXCLUSIVE,
    [];
    flags = BUFFER_CREATE_SPARSE_ALIASED_BIT,
)

# This is equivalent to

unwrap(
    create_buffer(
        device,
        100,
        BUFFER_USAGE_TRANSFER_SRC_BIT,
        SHARING_MODE_EXCLUSIVE,
        [];
        flags = BUFFER_CREATE_SPARSE_ALIASED_BIT,
    ),
)

# [Error handling](@ref) can be performed before unwrapping, e.g.

res = create_buffer(
    device,
    100,
    BUFFER_USAGE_TRANSFER_SRC_BIT,
    SHARING_MODE_EXCLUSIVE,
    [];
    flags = BUFFER_CREATE_SPARSE_ALIASED_BIT,
)
if iserror(res)
    error("Could not create buffer!")
else
    unwrap(res)
end

# Create info parameters can be built separately, such as

info = BufferCreateInfo(
    100,
    BUFFER_USAGE_TRANSFER_SRC_BIT,
    SHARING_MODE_EXCLUSIVE,
    [];
    flags = BUFFER_CREATE_SPARSE_ALIASED_BIT,
)

Buffer(device, info)
#-
create_buffer(device, info)

# Handles allocated in batches (such as command buffers) do not have a dedicated constructor; you will need to call the corresponding function yourself.

command_pool = CommandPool(device, 0)
info = CommandBufferAllocateInfo(command_pool, COMMAND_BUFFER_LEVEL_PRIMARY, 5)
res = allocate_command_buffers(device, info)
iserror(res) && error("Tried to create 5 command buffers, but failed miserably.")
cbuffers = unwrap(res)

# Note that they won't be freed automatically; forgetting to free them after use would result in a memory leak (see [Destroying a handle](@ref)).

# ## Destroying a handle

# The garbage collector will free most handles automatically with a finalizer (see [Automatic finalization](@ref)), but you can force the destruction yourself early with

finalize(buffer) # calls `destroy_buffer`

# This is most useful when you need to release resources associated to a handle, e.g. a `DeviceMemory`.
# Handle types that can be freed in batches don't register finalizers, such as `CommandBuffer` and `DescriptorSet`. They must be freed with

free_command_buffers(device, command_pool, cbuffers)

# or the corresponding `free_descriptor_sets` for `DescriptorSet`s.

max_stars_repo_name: JuliaGPU/VulkanAbstraction

max_issues_repo_name: JuliaGPU/VulkanAbstraction

max_forks_repo_name: JuliaGPU/VulkanAbstraction


text:
using Pumas, PumasTutorials, CSV, Plots

data = PumasTutorials.tutorial_data("data/nca","SD_crossover_IV_oral")
data = CSV.read(data,missingstring="NA")
first(data,10)

timeu = u"hr"
concu = u"mg/L"
amtu  = u"mg"

pop = read_nca(data, id=:ID, time=:time, conc=:DV, amt=:DOSE, ii=24timeu,
    route=:Formulation, occasion=:OCC,timeu=timeu, concu=concu, amtu=amtu)

pop = read_nca(data, id=:ID, time=:time, conc=:DV, amt=:DOSE, ii=24timeu,
    route=:Formulation, occasion=:OCC,timeu=timeu, concu=concu, amtu=amtu, lloq=0.4concu)

NCA.auc(pop,auctype=:last,method=:linear)

NCA.auc(pop,auctype=:inf,method=:linuplogdown)

NCA.auc(pop[1], interval=(0,12).*timeu)

NCA.auc(pop[1], interval=[(0,12).*timeu,(0,6).*timeu])

NCA.auc_extrap_percent(pop)

NCA.lambdaz(pop)

NCA.lambdaz(pop, threshold=3)

NCA.lambdaz(pop, idxs=[18,19,20])

NCA.lambdaz(pop, slopetimes=[18.5,19,19.5].*timeu)

cmax = NCA.cmax(pop[1])

pop[1]

normalizedose(cmax,pop[1])

AUClast = NCA.auc(pop[1],auctype=:last)
normalizedose(AUClast,pop[1])

NCA.lambdazr2(pop)
NCA.lambdazadjr2(pop)
NCA.lambdazintercept(pop)
NCA.lambdaztimefirst(pop)
NCA.lambdaznpoints(pop)

NCA.tmax(pop)
NCA.cmin(pop)
NCA.tmin(pop)

NCA.tlast(pop)
NCA.clast(pop)

NCA.aumc(pop)
NCA.aumclast(pop)

NCA.thalf(pop)

NCA.cl(pop,ithdose=1)

NCA.vss(pop)
NCA.vz(pop)

NCA.accumulationindex(pop)

pop[2]
NCA.cl(pop[2])

report = NCAReport(pop,ithdose=1)
report = NCA.to_dataframe(report)

report = NCAReport(pop,ithdose=1,pred=true)
report = NCA.to_dataframe(report)

CSV.write("./tutorials/nca/report_SD_crossover_IV_oral.csv", report)

using PuMaSTutorials
PuMaSTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])


text:
@testset "Test rescale" begin
	for _ in 1:100
		vec0 = sort(randn(rand(2:500)));
		vec2 = rand(1:100)*randn(2) |> sort
		vec1 = rescale(vec0, vec2)
		diffvec1 = diff(vec1);
		a = diff(vec0)./diffvec1;
		meana = sum(a)/length(a);
		@test all(diffvec1 .>= 0) # increaments have to be all positive
		@test isapprox.(a .- meana, 0; atol=meana*1e-6) |> all
	end

end


text:
using Flux
using Random
using MinimalRLCore

Base.@kwdef struct EvaluateAgent{A, SB, Φ, P}
    agent::A
    prev_s::Φ
    policy::AP
end

function EvaluateAgent(agent::DQNAgent, eval_policy::AP)

    EvaluateAgent(agent,
                  zeros(eltype(agent.state_buffer),
                        size(agent.state_buffer)[1:end-1]...,
                        hist_length(agent.state_buffer)),
                  eval_policy)
end

function MinimalRLCore.start!(agent::EvaluateAgent{DQNAgent},
                              env_s_tp1,
                              rng::AbstractRNG=Random.GLOBAL_RNG)

    agent.prev_s

    agent.state_postproc(agent.state_preproc(env_s_tp1))

end

function MinimalRLCore.step!(agent::EvaluateAgent{DQNAgent},
                             env_s_tp1,
                             r,
                             terminal,
                             rng::AbstractRNG=Random.GLOBAL_RNG)
end


text:
module TestEduction

using Test
using Transducers

@testset "composition" begin
    ed1 = eduction(Map(sin), 1:2)
    ed2 = eduction(Map(cos), ed1)
    ed3 = eduction(Map(tan), ed2)
    @test Transducer(ed1) === Map(sin)
    @test Transducer(ed2) === Map(sin) |> Map(cos)
    @test Transducer(ed3) === Map(sin) |> Map(cos) |> Map(tan)
end

end  # module


text:
module CUDA

using ..CuArrays
import ..Math: @argcheck, LinearAlgebra, tril!
import ..Math: make_lt, make_lt_strict, make_lt!, make_lt_strict!, cayley_orthog,
            unmake_lt, unmake_lt_strict, make_skew
import ..Arr: eye
import ..Flux: TrackedArray, diag0
import Base: \, inv

function make_lt(x::CuArray{T,1}, d::Int)::CuArray{T,2} where T <: Real
    @argcheck (length(x) == Int(d*(d+1)/2))
    make_lt!(CuArrays.zeros(T, d, d), x, d)
end

function make_lt_strict(x::CuArray{T,1}, d::Int)::CuArray{T,2} where T <: Real
    @argcheck (length(x) == Int(d*(d-1)/2))
    return make_lt_strict!(CuArrays.zeros(T, d,d), x, d)
end

function unmake_lt(M::CuMatrix{T}, d)::CuArray{T,1} where T <: Real
    return M[tril!(convert(CuMatrix{Bool}, trues(d,d)))]
end

function unmake_lt_strict(M::CuMatrix{T}, d::Int)::CuArray{T,1} where T <: Real
    return M[tril!(convert(CuMatrix{Bool}, trues(d,d)), -1)]
end

function \(A::CuArray{T, 2}, B::CuArray{T, 2}) where T <: AbstractFloat
        @assert size(A) == size(B) "Only square matrices implemented for ldiv CuArrays (via LU)! (Needs QR for rectangular.)"
        luA, ipiv = CuArrays.CUSOLVER.getrf!(copy(A))
        CuArrays.CUSOLVER.getrs!('N', luA, ipiv, copy(B))
end

function inv(A::CuArray{T, 2}) where T <: AbstractFloat
    d = LinearAlgebra.checksquare(A)
    A \ convert(CuMatrix{T}, eye(d))
end

const CuVecPossiblyTracked{T} = Union{CuVector, TrackedArray{T, 1, CuVector{T}}} where T <: AbstractFloat
const CuMatPossiblyTracked{T} = Union{CuVector, TrackedArray{T, 2, CuMatrix{T}}} where T <: AbstractFloat

function cayley_orthog(x::CuVecPossiblyTracked{T}, d)::CuMatPossiblyTracked{T} where T <: AbstractFloat
    I = convert(CuMatrix{T}, eye(d))            # segfault using UniformScaling I from LinearAlgebra. Not ideal.
    S = make_skew(x, d)
    return (I + S) \ (I - S)  # note this is the more efficient way around than for CPU (legacy)
end

function diag0(x::CuArray{T,1})::CuArray{T,2} where T <: Real
    d = length(x)
    M = CuArrays.zeros(T, d,d)
    M[LinearAlgebra.diagind(M)] = x
    return M
end

# So far, so good. NOW I NEED TO IMPLEMENT INVERSE (INV) JUST LIKE I DID FOR
# LDIV, FOR THE BACKWARD PASS. (So go through generic.jl in LinearAlgebra again...)

end


text:
module CellNumberReindex

using Gridap
using Gridap.CellValuesGallery
using Gridap.CellMapApply: CellMapFromKernel
using Gridap.CellMapApply: IndexCellMapFromKernel
using Base: @pure

import Gridap: reindex
import Base: iterate
import Base: length
import Base: size
import Base: getindex
import Base: IndexStyle

function reindex(values::IndexCellNumber, indices::CellValue{<:IndexLike})
  IterCellNumberFromReindex(values,indices)
end

function reindex(values::IndexCellNumber, indices::IndexCellValue{<:IndexLike})
  IndexCellNumberFromReindex(values,indices)
end

struct IterCellNumberFromReindex{T,V,I} <: IterCellNumber{T}
  values::V
  indices::I
end

function IterCellNumberFromReindex(
  values::IndexCellNumber{T}, indices::CellValue{<:IndexLike}) where T
  V = typeof(values)
  I = typeof(indices)
  IterCellNumberFromReindex{T,V,I}(values,indices)
end

function iterate(s::IterCellNumberFromReindex)
  inext = iterate(s.indices)
  _iterate(s,inext)
end

function iterate(s::IterCellNumberFromReindex,state)
  inext = iterate(s.indices,state)
  _iterate(s,inext)
end

function _iterate(s,inext)
  if inext === nothing; return nothing end
  i, istate = inext
  (s.values[i], istate)
end

length(s::IterCellNumberFromReindex) = length(s.indices)

struct IndexCellNumberFromReindex{T,D,V,I} <: IndexCellNumber{T,D}
  values::V
  indices::I
end

function IndexCellNumberFromReindex(
  values::IndexCellNumber{T}, indices::IndexCellValue{<:IndexLike,D}) where {D,T}
  V = typeof(values)
  I = typeof(indices)
  IndexCellNumberFromReindex{T,D,V,I}(values,indices)
end

function getindex(
  s::IndexCellNumberFromReindex{T,D}, i::Vararg{<:Integer,D}) where {T,D}
  j = s.indices[i...]
  s.values[j]
end

size(s::IndexCellNumberFromReindex) = size(s.indices)

@pure function IndexStyle(
  ::Type{<:IndexCellNumberFromReindex{T,D,V,I}}) where {T,D,V,I}
  IndexStyle(I)
end

end # module


text:
module GeoData

# Use the README as the module docs
@doc let
    path = joinpath(dirname(@__DIR__), "README.md")
    include_dependency(path)
    read(path, String)
end GeoData

using Adapt,
      Dates,
      Missings,
      Mmap,
      ProgressMeter,
      RecipesBase,
      Reexport,
      Requires

@reexport using DimensionalData, GeoFormatTypes

const DD = DimensionalData

using Base: tail, @propagate_inbounds

using DimensionalData: StandardIndices

export AbstractGeoArray, MemGeoArray, DiskGeoArray, GeoArray

export AbstractGeoStack, MemGeoStack, DiskGeoStack, DiskStack, GeoStack

export AbstractGeoSeries, GeoSeries

export Projected, Mapped

export Band, Lat, Lon, Vert, GeoXDim, GeoYDim, GeoZDim

export missingval, boolmask, missingmask, replace_missing,
       aggregate, aggregate!, disaggregate, disaggregate!

export crs, mappedcrs, mappedindex, mappedbounds, projectedindex, projectedbounds

export geoarray, stack, series

const Lon = X
const Lat = Y
const Vert = Z
const GeoXDim = XDim
const GeoYDim = YDim
const GeoZDim = ZDim

# DimensionalData documentation urls
const DDdocs = "https://rafaqz.github.io/DimensionalData.jl/stable/api"
const DDdimdocs = joinpath(DDdocs, "#DimensionalData.Dimension")
const DDarraydocs = joinpath(DDdocs, "#DimensionalData.AbstractDimensionalArray")
const DDabssampleddocs = joinpath(DDdocs, "#DimensionalData.AbstractSampled")
const DDsampleddocs = joinpath(DDdocs, "#DimensionalData.Sampled")
const DDlocusdocs = joinpath(DDdocs, "#DimensionalData.Locus")
const DDselectordocs = joinpath(DDdocs, "#DimensionalData.Selector")
const DDtidocs = joinpath(DDdocs, "#DimensionalData.Ti")

include("mode.jl")
include("dimensions.jl")
include("array.jl")
include("stack.jl")
include("series.jl")
include("utils.jl")
include("aggregate.jl")
include("methods.jl")
include("open.jl")
include("read.jl")
include("sources/grd.jl")
include("show.jl")
include("plotrecipes.jl")
include("convenience.jl")

function __init__()
    @require HDF5="f67ccb44-e63f-5c2f-98bd-6dc0ccc4ba2f" begin
        # This section is for sources that rely on HDF5, not simply any HDF5.
        include("sources/smap.jl")
    end
    @require NCDatasets="85f8d34a-cbdd-5861-8df4-14fed0d494ab" begin
        include("sources/ncdatasets.jl")
    end
    @require ArchGDAL="c9ce4bd3-c3d5-55b8-8973-c0e20141b8c3" begin
        include("resample.jl")
        include("reproject.jl")
        include("sources/gdal.jl")
    end
    @require RasterDataSources="3cb90ccd-e1b6-4867-9617-4276c8b2ca36" begin
        include("sources/rasterdatasources.jl")
    end
end

end


text:
## Test Helpers for Oracles

function portTest(oracle, zstar_val, ustar_vals; unc_lower=nothing, unc_upper=nothing, TOL=1e-3)
	m = RobustModel()

	if unc_lower != nothing
		@defUnc(m, unc_lower[i] <= us[i=1:2] <= unc_upper[i])
	else
		@defUnc(m, us[1:2])
	end

	setDefaultOracle!(m, oracle)
	@defVar(m, xs[1:2] >= 0)
	@addConstraint(m, sum(xs) == 1.)
	@defVar(m, t <= 1e6)
	@addConstraint(m, sum{us[i] * xs[i], i=1:2} >= t)

	@setObjective(m, Max, t)
	@fact solve(m, prefer_cuts=true, report=false, active_cuts=true) --> :Optimal
	@fact getObjectiveValue(m) --> roughly(zstar_val, TOL)
	@fact getValue(xs[1])      --> roughly(ustar_vals[1], TOL)
	@fact getValue(xs[2])      --> roughly(ustar_vals[2], TOL)
end


text:
@everywhere using SharedArrays
@everywhere using Distributions
@everywhere using Random
@everywhere const EPS = 2.2204e-16

@everywhere function nmf(v,r)

    n, m = size(v)
    stopconv = 10000        # stopping criterion (can be adjusted)
    niter = 1000000         # maximum number of iterations (can be adjusted)

    cons = fill(false, (m,m))
    consold = fill(false, (m,m))
    inc = 0
    j = 0

    # initialize random w and h
    w = Random.rand(n, r)
    h = Random.rand(r, m)

    for i = 1:niter

        # divergence-reducing NMF iterations
        x1 = repeat(sum(w, dims=1)', 1, m)
        h = h.*(w'*(v./(w*h)))./x1
        x2 = repeat(sum(h, dims=2)', n, 1)
        w = w.*((v./(w*h))*h')./x2

        # test convergence every 10 iterations

        if i%10 == 0
            j = j + 1

            # adjust small values to avoid undeflow
            h = map(x->max(x, EPS), h)
            w = map(x->max(x, EPS), w)

            # construct connectivity matrix
            index = [i[1] for i in argmax(h, dims=1)]    # find largest factor
            mat1 = repeat(index, m, 1)                   # spread index down
            mat2 = repeat(index', 1, m)                  # spread index right
            cons = mat1==mat2

            if cons == consold             # connectivity matrix has not changed
                inc = inc + 1              # accumulate count
            else
                inc = 0                    # else restart count
            end

            if inc > stopconv
                break                      # assume convergence if connectivity stops changing
            end

            consold = cons

        end
    end

    return w, h
end

@everywhere function to_parallelize(i)

    if i%20 == 0
            @info "Iteration $i."
    end

    # Create a random seed for each iteration
    Random.seed!(i+123456)

    # Generating boostrapped genomes
    bootstrapGenomes = Array{Float64,2}(undef, size(parallelNormGenomes))
    for j = eachindex(parallelGenomesColsSum)
        bootstrapGenomes[:,j] = Random.rand(Multinomial(parallelGenomesColsSum[j], parallelNormGenomes[:,j]))
    end

    bootstrapGenomes = map(x->max(x, EPS), bootstrapGenomes)

    # Solving NMF for these boostrapped genomes
    W, H = nmf(bootstrapGenomes, parallelTotalProcesses)

    for j = 1 : parallelTotalProcesses
        total = sum( W[:, j] )
        W[:, j] = W[:, j] / total
        H[j, :] = H[j, :] * total
    end

    return i, bootstrapGenomes, W, H
end

function extractSignatures(genomes, processes, iterations)

    totalMutationTypes = size(genomes, 1)
    totalGenomes = size(genomes, 2)

    Wall = zeros( totalMutationTypes, processes * iterations )
    Hall = zeros( processes * iterations, totalGenomes )
    genomeErrors = zeros(totalMutationTypes, totalGenomes, iterations)
    genomesReconstructed = zeros(totalMutationTypes, totalGenomes, iterations)

    for (i, bootstrapGenomes, W, H) = pmap(to_parallelize, 1:iterations)
        processCount = (i-1)*processes + 1
        genomeErrors[:, :, i] = bootstrapGenomes -  W * H
        genomesReconstructed[:, :, i] = W * H
        Wall[ :, processCount : (processCount + processes - 1) ] = W
        Hall[ processCount : (processCount + processes - 1), : ] = H

    end

    return Wall, Hall, genomeErrors, genomesReconstructed
end

max_stars_repo_name: ypradat/sigprofilerjulia

max_issues_repo_name: ypradat/sigprofilerjulia

max_forks_repo_name: ypradat/sigprofilerjulia


text:
@testset "PointCoud transforms" begin

    for inplace in [true, false]
        @testset "ScalePointCloud inplace=$(inplace)" begin
            p = rand(Float32, 3, 8, 2) |> gpu
            t1 = ScalePointCloud(2.0; inplace = inplace) |> gpu
            t2 = ScalePointCloud(0.5; inplace = inplace) |> gpu
            pc1 = PointCloud(p) |> gpu
            pc2 = t2(t1(pc1))
            @test pc1.points isa CuArray
            @test pc2.points isa CuArray
            @test all(isapprox.(Array(p), Array(pc2.points), rtol = 1e-5, atol = 1e-5))
        end
    end

    for inplace in [true, false]
        @testset "RotatePointCloud inplace=$(inplace)" begin
            p = rand(Float32, 3, 8, 2)
            rotmat = 2 .* one(rand(Float32, 3, 3))
            rotmat_inv = inv(rotmat)

            t1 = RotatePointCloud(rotmat; inplace = inplace) |> gpu
            t2 = RotatePointCloud(rotmat_inv; inplace = inplace) |> gpu
            pc1 = PointCloud(p) |> gpu
            pc2 = t2(t1(pc1)) |> gpu
            @test t1.rotmat isa CuArray
            @test t2.rotmat isa CuArray
            @test pc1.points isa CuArray
            @test pc2.points isa CuArray
            @test all(isapprox.(Array(p), Array(pc2.points), rtol = 1e-5, atol = 1e-5))
        end
    end

    for inplace in [true, false]
        @testset "ReAlignPointCloud inplace=$(inplace)" begin
            p1 = rand(Float32, 3, 8, 2)
            p2 = rand(Float32, 3, 8, 1)
            tgt = PointCloud(p2)
            src = PointCloud(p1) |> gpu
            t = ReAlignPointCloud(tgt; inplace = inplace) |> gpu
            src_1 = t(src) |> gpu
            @test t.t_min isa CuArray
            @test t.t_max isa CuArray
            @test src.points isa CuArray
            @test src_1.points isa CuArray

            # Transformed PointCloud should be inside the bounding box defined by `tgt` PointCloud
            @test all(
                reshape(maximum(Array(tgt.points), dims = 2), (:, 1)) .>=
                Array(src_1.points) .>=
                reshape(minimum(Array(tgt.points), dims = 2), (:, 1)),
            )
        end
    end

    for inplace in [true, false]
        @testset "NormalizePointCloud inplace=$(inplace)" begin
            p = rand(Float32, 3, 8, 2)
            t = NormalizePointCloud(; inplace = inplace)
            pc1 = PointCloud(p) |> gpu
            pc2 = t(pc1) |> gpu
            @test pc1.points isa CuArray
            @test pc2.points isa CuArray
            @test all(
                isapprox.(mean(Array(pc2.points); dims = 2), 0, rtol = 1e-5, atol = 1e-5),
            )
            @test all(
                isapprox.(std(Array(pc2.points); dims = 2), 1, rtol = 1e-5, atol = 1e-5),
            )
        end
    end

    @testset "Chain" begin
        p = rand(Float32, 3, 8, 2)
        t =
            Chain(
                ScalePointCloud(0.5),
                RotatePointCloud(rand(3, 3)),
                NormalizePointCloud(),
            ) |> gpu
        pc1 = PointCloud(p) |> gpu
        pc1 = t(pc1)
        @test pc1.points isa CuArray
        @test all(isapprox.(mean(Array(pc1.points); dims = 2), 0, rtol = 1e-5, atol = 1e-5))
        @test all(isapprox.(std(Array(pc1.points); dims = 2), 1, rtol = 1e-5, atol = 1e-4))
    end

    _mesh =
        load_trimesh(
            joinpath(@__DIR__, "../assets/teapot.obj"),
            joinpath(@__DIR__, "../assets/sphere.obj"),
        ) |> gpu

    for inplace in [true, false]
        @testset "ScaleTriMesh inplace=$(inplace)" begin
            m = deepcopy(_mesh)
            t1 = ScaleTriMesh(2.0; inplace = inplace) |> gpu
            t2 = ScaleTriMesh(0.5; inplace = inplace) |> gpu
            m2 = t2(t1(m))

            if inplace
                @test m2 === m
            else
                @test m2 !== m
            end
            @test get_verts_packed(m2) isa CuArray{Float32,2}
            @test all(
                isapprox.(
                    cpu(get_verts_packed(_mesh)),
                    cpu(get_verts_packed(m2)),
                    rtol = 1e-5,
                    atol = 1e-5,
                ),
            )
        end
    end

    for inplace in [true, false]
        @testset "RotateTriMesh inplace=$(inplace)" begin
            m = deepcopy(_mesh)
            rotmat = 2 .* one(rand(Float32, 3, 3))
            rotmat_inv = inv(rotmat)
            t1 = RotateTriMesh(rotmat; inplace = inplace) |> gpu
            t2 = RotateTriMesh(rotmat_inv; inplace = inplace) |> gpu
            m2 = t2(t1(m))
            if inplace
                @test m2 === m
            else
                @test m2 !== m
            end
            @test get_verts_packed(m2) isa CuArray{Float32,2}
            @test all(
                isapprox.(
                    cpu(get_verts_packed(_mesh)),
                    cpu(get_verts_packed(m2)),
                    rtol = 1e-5,
                    atol = 1e-5,
                ),
            )
        end
    end

    for inplace in [true, false]
        @testset "ReAlignTriMesh inplace=$(inplace)" begin
            m = deepcopy(_mesh)
            src = Flux3D.scale(m, 2.0)
            tgt = Flux3D.scale(m, 1.0)
            t = ReAlignTriMesh(tgt, 1; inplace = inplace) |> gpu
            src_1 = t(src)
            if inplace
                @test src === src_1
            else
                @test src !== src_1
            end
            @test get_verts_packed(src_1) isa CuArray{Float32,2}
            @test all(
                maximum(get_verts_list(_mesh)[1]; dims = 2) .>=
                get_verts_list(src_1)[1] .>=
                minimum(get_verts_list(_mesh)[1]; dims = 2),
            )
            @test all(
                maximum(get_verts_list(_mesh)[1]; dims = 2) .>=
                get_verts_list(src_1)[2] .>=
                minimum(get_verts_list(_mesh)[1]; dims = 2),
            )
        end
    end

    for inplace in [true, false]
        @testset "NormalizeTriMesh inplace=$(inplace)" begin
            m = deepcopy(_mesh)
            t = NormalizeTriMesh(; inplace = inplace) |> gpu
            m2 = t(m)
            if inplace
                @test m2 === m
            else
                @test m2 !== m
            end
            @test get_verts_packed(m2) isa CuArray{Float32,2}
            @test all(
                isapprox.(
                    mean(cpu(get_verts_list(m2))[1]; dims = 2),
                    0.0,
                    rtol = 1e-5,
                    atol = 1e-5,
                ),
            )
            @test all(
                isapprox.(
                    std(cpu(get_verts_list(m2))[1]; dims = 2),
                    1.0,
                    rtol = 1e-4,
                    atol = 1e-5,
                ),
            )
            @test all(
                isapprox.(
                    mean(cpu(get_verts_list(m2))[2]; dims = 2),
                    0.0,
                    rtol = 1e-5,
                    atol = 1e-5,
                ),
            )
            @test all(
                isapprox.(
                    std(cpu(get_verts_list(m2))[2]; dims = 2),
                    1.0,
                    rtol = 1e-4,
                    atol = 1e-5,
                ),
            )
        end
    end

    for inplace in [true, false]
        @testset "TranslateTriMesh inplace=$(inplace)" begin
            m = deepcopy(_mesh)
            t1 = TranslateTriMesh(1.0; inplace = inplace) |> gpu
            t2 = TranslateTriMesh(-1.0; inplace = inplace) |> gpu
            m2 = t2(t1(m))
            if inplace
                @test m2 === m
            else
                @test m2 !== m
            end
            @test get_verts_packed(m2) isa CuArray{Float32,2}
            @test all(
                isapprox.(
                    cpu(get_verts_packed(_mesh)),
                    cpu(get_verts_packed(m2)),
                    rtol = 1e-5,
                    atol = 1e-5,
                ),
            )
        end
    end

    for inplace in [true, false]
        @testset "OffsetTriMesh inplace=$(inplace)" begin
            m = deepcopy(_mesh)
            _offset = ones(size(get_verts_packed(m)))
            t1 = OffsetTriMesh(_offset; inplace = inplace) |> gpu
            t2 = OffsetTriMesh(_offset .* -1; inplace = inplace) |> gpu
            m2 = t2(t1(m))

            if inplace
                @test m2 === m
            else
                @test m2 !== m
            end
            @test get_verts_packed(m2) isa CuArray{Float32,2}
            @test all(
                isapprox.(
                    cpu(get_verts_packed(_mesh)),
                    cpu(get_verts_packed(m2)),
                    rtol = 1e-5,
                    atol = 1e-5,
                ),
            )
        end
    end

    _voxels = zeros(Float32, 32, 32, 32, 2) |> gpu
    _voxels[1:15, 2:10, 18:32, :] .= 1

    _v = VoxelGrid(_voxels) |> gpu
    _m =
        load_trimesh(
            joinpath(@__DIR__, "../assets/teapot.obj"),
            joinpath(@__DIR__, "../assets/sphere.obj"),
        ) |> gpu
    _p = PointCloud(sample_points(_m, 1024)) |> gpu

    res = 28
    points = 512
    thresh = 0.9

    @testset "TriMeshToVoxelGrid" begin
        m = deepcopy(_m)
        t = TriMeshToVoxelGrid(res)
        v = t(m)
        @test v isa VoxelGrid{Float32}
        @test v.voxels isa CUDA.CuArray
        @test size(v.voxels) == (res, res, res, 2)
    end

    @testset "PointCloudToVoxelGrid" begin
        p = deepcopy(_p)
        t = PointCloudToVoxelGrid(res)
        v = t(p)
        @test v isa VoxelGrid{Float32}
        @test v.voxels isa CUDA.CuArray
        @test size(v.voxels) == (res, res, res, 2)
    end

    for algo in [:Exact, :MarchingCubes, :MarchingTetrahedra, :NaiveSurfaceNets]
        @testset "VoxelGridToTriMesh algo=$(algo)" begin
            v = deepcopy(_v)
            t = VoxelGridToTriMesh(thresh = thresh, algo = algo)
            m = t(v)
            @test m isa TriMesh{Float32,UInt32,CuArray}
        end
    end

    for algo in [:Exact, :MarchingCubes, :MarchingTetrahedra, :NaiveSurfaceNets]
        @testset "PointCloudToTriMesh algo=$(algo)" begin
            p = deepcopy(_p)
            t = PointCloudToTriMesh(res, algo = algo)
            m = t(p)
            @test m isa TriMesh{Float32,UInt32,CuArray}
        end
    end

    @testset "TriMeshToPointCloud" begin
        m = deepcopy(_m)
        t = TriMeshToPointCloud(points)
        p = t(m)
        @test p isa PointCloud{Float32}
        @test p.points isa CUDA.CuArray
        @test size(p.points) == (3, points, 2)
    end

    for algo in [:Exact, :MarchingCubes, :MarchingTetrahedra]#, :NaiveSurfaceNets]
        @testset "VoxelGridToPointCloud algo=$(algo)" begin
            v = deepcopy(_v)
            t = VoxelGridToPointCloud(points, thresh = thresh, algo = algo)
            p = t(v)
            @test p isa PointCloud{Float32}
            @test p.points isa CUDA.CuArray
            @test size(p.points) == (3, points, 2)
        end
    end
end # Transforms


text:
function tcm_createGrandAssortments(N)
	ass_ints = collect(0:(2^(N-1) - 1))
	M = length(ass_ints)
	assortments = zeros(M, N)
	for m in 1:M
		# @show bin(temp[m],N-1)
		assortments[m,1:(N-1)] = map(x -> parse(string(x)), [bin(ass_ints[m],N-1)...] )
	end

	assortments[:,N] = 1

	return assortments
end

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
module MPIBackendTests

include("mpiexec.jl")
run_mpi_driver(procs=4,file="driver_mpi_backend.jl")

end # module


text:
module PrettyTables

using Formatting
using Parameters
using Reexport
using Tables
using Markdown

@reexport using Crayons

import Base: Dict, ismalformed, isoverlong

################################################################################
#                                    Types
################################################################################

include("types.jl")
include("backends/text/types.jl")
include("backends/html/types.jl")
include("backends/latex/types.jl")

################################################################################
#                                  Includes
################################################################################

include("deprecations.jl")
include("files.jl")
include("helpers.jl")
include("misc.jl")
include("predefined_formatters.jl")
include("print.jl")
include("tables.jl")

# Backends
# ========

# Text backend
include("backends/text/predefined_formats.jl")
include("backends/text/predefined_highlighters.jl")
include("backends/text/print.jl")
include("backends/text/private.jl")

# HTML backend
include("backends/html/predefined_formats.jl")
include("backends/html/predefined_highlighters.jl")
include("backends/html/print.jl")
include("backends/html/private.jl")

# LaTeX backend
include("backends/latex/predefined_formats.jl")
include("backends/latex/private.jl")
include("backends/latex/print.jl")

end # module


text:
@testset "Find Tokens" begin
    a = raw"""some markdown then `code` and @@dname block @@"""

    tokens = F.find_tokens(a, F.MD_TOKENS, F.MD_1C_TOKENS)

    @test tokens[1].name == :CODE_SINGLE
    @test tokens[2].name == :CODE_SINGLE
    @test tokens[3].name == :DIV_OPEN
    @test tokens[3].ss == "@@dname"
    @test tokens[4].ss == "@@"
    @test tokens[5].name == :EOS
end

@testset "Find blocks" begin
    st = raw"""
        some markdown then `code` and
        @@dname block @@
        then maybe an escape
        ~~~
        escape block
        ~~~
        and done {target} done.
        """

    steps = explore_md_steps(st)
    blocks, tokens = steps[:ocblocks]

    # inline code block
    β = blocks[1]
    @test β.name == :CODE_INLINE
    @test β.ss == "`code`"

    # div block
    β = blocks[2]
    @test β.name == :DIV
    @test β.ss == "@@dname block @@"

    # escape block
    β = blocks[3]
    @test β.name == :ESCAPE
    @test β.ss == "~~~\nescape block\n~~~"

    # escape block
    β = blocks[4]
    @test β.name == :LXB
    @test β.ss == "{target}"
end

@testset "Unicode lx" begin
    st = raw"""
    Call me “$x$”, not $🍕$.
    """

    steps = explore_md_steps(st)
    blocks, _ = steps[:ocblocks]

    # first math block
    β = blocks[1]
    @test β.name == :MATH_A
    @test β.ss == "\$x\$"

    # second math block
    β = blocks[2]
    @test β.name == :MATH_A
    @test β.ss == "\$🍕\$"
end

@testset "Header blocks" begin
    st = raw"""
        # t1
        1
        ## t2
        2 ## trick
        ### t3
        3
        #### t4
        4
        ##### t5
        5
        ###### t6
        6
        """

    tokens, blocks = explore_md_steps(st)[:filter]

    @test blocks[1].name == :H1
    @test blocks[2].name == :H2
    @test blocks[3].name == :H3
    @test blocks[4].name == :H4
    @test blocks[5].name == :H5
    @test blocks[6].name == :H6

    set_curpath("index.md")

    h = """
        # t1
        1
        ## t2
        2
        ## t3 `blah` etc
        3
        ### t4
        4
        ### t2
        5
        ### t2
        6
        """ |> seval
    @test isapproxstr(h, """

t1

1

t2

2

t3 blah etc

3

t4

4

t2

5

t2

6

        """)

    # pathological issue 241
    h = raw"""
        ## example
        A
        ## example
        B
        ## example 2
        C
        """ |> seval
    @test  isapproxstr(h, """

example

A

example

B

example 2

C

        """)
end

@testset "Line skip" begin
    h = raw"""
        Hello \\ goodbye
        """ |> seval
    @test isapproxstr(h, """
Hello
 goodbye
""")
end

@testset "Header+lx" begin
    h = "# blah" |> fd2html_td
    @test h // """
blah
"""
    h = raw"""
        \newcommand{\foo}{foo}
        \newcommand{\header}{# hello}
        \foo
        \header
        """ |> fd2html_td
    @test h // """
foo
hello

"""
    h = raw"""
        \newcommand{\foo}{foo}
        \foo hello
        """ |> fd2html_td
    @test h // """
foo hello
"""
    h = raw"""
        \newcommand{\foo}{blah}
        # \foo hello
        """ |> fd2html_td
    @test h // """
blah hello
"""
    h = raw"""
        \newcommand{\foo}{foo}
        \newcommand{\header}[2]{!#1 \foo #2}
        \header{##}{hello}
        """ |> fd2html_td
    @test h // """
foo  hello
"""
end