text:
module KernelFunctions

export kernelmatrix, kernelmatrix!, kernelmatrix_diag, kernelmatrix_diag!
export duplicate, set! # Helpers

export Kernel, MOKernel
export ConstantKernel, WhiteKernel, EyeKernel, ZeroKernel, WienerKernel
export CosineKernel
export SqExponentialKernel, RBFKernel, GaussianKernel, SEKernel
export LaplacianKernel, ExponentialKernel, GammaExponentialKernel
export ExponentiatedKernel
export FBMKernel
export MaternKernel, Matern12Kernel, Matern32Kernel, Matern52Kernel
export LinearKernel, PolynomialKernel
export RationalKernel, RationalQuadraticKernel, GammaRationalKernel
export PiecewisePolynomialKernel
export PeriodicKernel, NeuralNetworkKernel
export KernelSum, KernelProduct, KernelTensorProduct
export TransformedKernel, ScaledKernel, NormalizedKernel
export GibbsKernel

export Transform,
    SelectTransform,
    ChainTransform,
    ScaleTransform,
    LinearTransform,
    ARDTransform,
    IdentityTransform,
    FunctionTransform,
    PeriodicTransform
export with_lengthscale

export NystromFact, nystrom

export gaborkernel
export spectral_mixture_kernel, spectral_mixture_product_kernel

export ColVecs, RowVecs

export MOInput, prepare_isotopic_multi_output_data, prepare_heterotopic_multi_output_data
export IndependentMOKernel,
    LatentFactorMOKernel, IntrinsicCoregionMOKernel, LinearMixingModelKernel

# Reexports
export tensor, ⊗, compose

using Compat
using ChainRulesCore: ChainRulesCore, Tangent, ZeroTangent, NoTangent
using ChainRulesCore: @thunk, InplaceableThunk
using CompositionsBase
using Distances
using FillArrays
using Functors
using LinearAlgebra
using Requires
using SpecialFunctions: loggamma, besselk, polygamma
using IrrationalConstants: logtwo, twoπ, invsqrt2
using LogExpFunctions: softplus
using StatsBase
using TensorCore
using ZygoteRules: ZygoteRules, AContext, literal_getproperty, literal_getfield

# Hack to work around Zygote type inference problems.
const Distances_pairwise = Distances.pairwise

abstract type Kernel end
abstract type SimpleKernel <: Kernel end

include("utils.jl")
include("distances/pairwise.jl")
include("distances/dotproduct.jl")
include("distances/delta.jl")
include("distances/sinus.jl")

include("transform/transform.jl")
include("transform/scaletransform.jl")
include("transform/ardtransform.jl")
include("transform/lineartransform.jl")
include("transform/functiontransform.jl")
include("transform/selecttransform.jl")
include("transform/chaintransform.jl")
include("transform/periodic_transform.jl")
include("kernels/transformedkernel.jl")
include("transform/with_lengthscale.jl")

include("basekernels/constant.jl")
include("basekernels/cosine.jl")
include("basekernels/exponential.jl")
include("basekernels/exponentiated.jl")
include("basekernels/fbm.jl")
include("basekernels/gabor.jl")
include("basekernels/matern.jl")
include("basekernels/nn.jl")
include("basekernels/periodic.jl")
include("basekernels/piecewisepolynomial.jl")
include("basekernels/polynomial.jl")
include("basekernels/rational.jl")
include("basekernels/sm.jl")
include("basekernels/wiener.jl")

include("kernels/gibbskernel.jl")
include("kernels/scaledkernel.jl")
include("kernels/normalizedkernel.jl")
include("matrix/kernelmatrix.jl")
include("kernels/kernelsum.jl")
include("kernels/kernelproduct.jl")
include("kernels/kerneltensorproduct.jl")
include("kernels/overloads.jl")
include("kernels/neuralkernelnetwork.jl")
include("approximations/nystrom.jl")
include("generic.jl")

include("mokernels/moinput.jl")
include("mokernels/mokernel.jl")
include("mokernels/independent.jl")
include("mokernels/slfm.jl")
include("mokernels/intrinsiccoregion.jl")
include("mokernels/lmm.jl")

include("chainrules.jl")
include("zygoterules.jl")

include("test_utils.jl")

function __init__()
    @require Kronecker = "2c470bb0-bcc8-11e8-3dad-c9649493f05e" begin
        include("matrix/kernelkroneckermat.jl")
    end
    @require PDMats = "90014a1f-27ba-587c-ab20-58faa44d9150" begin
        include("matrix/kernelpdmat.jl")
    end
end

end


text:
"""
Abstract type for Service Formulations (a.k.a Models)

# Example

import PowerSimulations
const PSI = PowerSimulations
struct MyServiceFormulation <: PSI.AbstractServiceFormulation
"""
abstract type AbstractServiceFormulation end
abstract type AbstractReservesFormulation <: AbstractServiceFormulation end

function _check_service_formulation(
    ::Type{D},
) where {D <: Union{AbstractServiceFormulation, PSY.Service}}
    if !isconcretetype(D)
        throw(
            ArgumentError(
                "The service model must contain only concrete types, $(D) is an Abstract Type",
            ),
        )
    end
end

"""
Establishes the model for a particular services specified by type. Uses the keyword argument
`use_service_name` to assign the model to a service with the same name as the name in the
template. Uses the keyword argument feedforward to enable passing values between operation
model at simulation time

# Arguments

-`::Type{D}`: Power System Service Type
-`::Type{B}`: Abstract Service Formulation

# Accepted Key Words

  - `feedforward::Array{<:AbstractAffectFeedforward}` : use to pass parameters between models
  - `use_service_name::Bool` : use the name as the name for the service

# Example

reserves = ServiceModel(PSY.VariableReserve{PSY.ReserveUp}, RangeReserve)
"""
mutable struct ServiceModel{D <: PSY.Service, B <: AbstractServiceFormulation}
    feedforwards::Vector{<:AbstractAffectFeedforward}
    service_name::String
    use_slacks::Bool
    duals::Vector{DataType}
    time_series_names::Dict{Type{<:TimeSeriesParameter}, String}
    attributes::Dict{String, Any}
    contributing_devices_map::Dict{Type{<:PSY.Component}, Vector{<:PSY.Component}}
    function ServiceModel(
        ::Type{D},
        ::Type{B},
        service_name::String;
        use_slacks=false,
        feedforwards=Vector{AbstractAffectFeedforward}(),
        duals=Vector{DataType}(),
        time_series_names=get_default_time_series_names(D, B),
        attributes=get_default_attributes(D, B),
        contributing_devices_map=Dict{Type{<:PSY.Component}, Vector{<:PSY.Component}}(),
    ) where {D <: PSY.Service, B <: AbstractServiceFormulation}
        _check_service_formulation(D)
        _check_service_formulation(B)
        new{D, B}(
            feedforwards,
            service_name,
            use_slacks,
            duals,
            time_series_names,
            attributes,
            contributing_devices_map,
        )
    end
end

get_component_type(
    ::ServiceModel{D, B},
) where {D <: PSY.Service, B <: AbstractServiceFormulation} = D
get_formulation(
    ::ServiceModel{D, B},
) where {D <: PSY.Service, B <: AbstractServiceFormulation} = B
get_feedforwards(m::ServiceModel) = m.feedforwards
get_service_name(m::ServiceModel) = m.service_name
get_use_slacks(m::ServiceModel) = m.use_slacks
get_duals(m::ServiceModel) = m.duals
get_time_series_names(m::ServiceModel) = m.time_series_names
get_attributes(m::ServiceModel) = m.attributes
get_attribute(m::ServiceModel, key::String) = get(m.attributes, key, nothing)
get_contributing_devices_map(m::ServiceModel) = m.contributing_devices_map
get_contributing_devices_map(m::ServiceModel, key) =
    get(m.contributing_devices_map, key, nothing)
get_contributing_devices(m::ServiceModel) =
    [z for x in values(m.contributing_devices_map) for z in x]
add_contributing_devices_map!(m::ServiceModel, key, value) =
    m.contributing_devices_map[key] = value

function ServiceModel(
    service_type::Type{D},
    formulation_type::Type{B};
    use_slacks=false,
    feedforwards=Vector{AbstractAffectFeedforward}(),
    duals=Vector{DataType}(),
    time_series_names=get_default_time_series_names(D, B),
    attributes=get_default_attributes(D, B),
) where {D <: PSY.Service, B <: AbstractServiceFormulation}
    # If more attributes are used later, move free form string to const and organize
    # attributes
    if !haskey(attributes, "aggregated_service_model")
        push!(attributes, "aggregated_service_model" => true)
    end
    return ServiceModel(
        service_type,
        formulation_type,
        NO_SERVICE_NAME_PROVIDED;
        use_slacks,
        feedforwards,
        duals,
        time_series_names,
        attributes,
    )
end

function _set_model!(dict::Dict, key::Tuple{String, Symbol}, model::ServiceModel)
    if haskey(dict, key)
        @warn "Overwriting $(key) existing model"
    end
    dict[key] = model
    return
end

function _set_model!(
    dict::Dict,
    model::ServiceModel{D, B},
) where {D <: PSY.Service, B <: AbstractServiceFormulation}
    _set_model!(dict, (get_service_name(model), Symbol(D)), model)
    return
end

ext: jl


text:
function format_option_name(name::String)
    return replace(name, "_" => " ") |> titlecase
end

format_option_name(name::Symbol) = format_option_name(string(name))

valuetype(::T) where {T <: GtkWidget} = Nothing
valuetype(::Union{GtkScale, GtkSpinButton}) = Real
valuetype(::GtkEntry) = String
valuetype(::GtkColorButton) = RGBA
valuetype(::Union{GtkSwitch, GtkCheckButton}) = Bool

abstract type AbstractOption{T} end

"""
        mutable struct Option{W, T} <: AbstractOption{W, T}

Represents an `option` object.

An option is a value of type `T` associated with a `GtkWidget`.

The option's value can be accessed with the empty bracket notation: `option[]`

The `option.set` function sets a new value for the option. The option's value can also be setted
with the empty bracket notation: `option[] = newvalue`

Each option type defines the `get` and `set` functions.
"""
mutable struct Option{T} <: AbstractOption{T}
    widget::GtkWidget
    type::Symbol
    value::T
    set::Function
    label::Maybe{Union{GtkLabel, Symbol}}
    function Option{T}(init::Function) where {T}
        self = new{T}()
        init(self)
        return self;
    end
end

function Base.show(io::IO, ::Option{T}) where {T}
    println(io, "Option($T)")
end

Base.getindex(self::Option) = self.value
Base.setindex!(self::Option, x::T) where {T} = self.set(x)

function onevent(callback::Function, event::SString, self::Option)
    onevent(callback, event, self.widget)
end

function onevent(callback::Function, event::SString, options::Vector{<:Option})
    [onevent(callback, event, opt.widget) for opt in options]
end

value(self::Option) = value(self.widget)
setvalue!(self::Option) = setvalue!(self.widget)

"""
A `controls` object contains a list of options `object` and
a `GtkGrid` containing each option's widget.
"""
mutable struct Controls
    _options::NamedTuple
    _grid::GtkGrid
end

add!(parent::GtkWidget, self::Controls) = add!(parent, self._grid)

function Base.getproperty(self::Controls, key::Symbol)
    if startswith(string(key), "_")
        return getfield(self, key)
    else
        return getfield(getfield(self, :_options), key)
    end
end

function Base.getindex(self::Controls, index::Union{Symbol, Int})
    return getindex(self._options, index).value
end

function Base.setindex!(self::Controls, index::Union{Symbol, Int}, x::T) where {T}
    getindex(self._options, index).set(x)
end

function Controls(options::NamedTuple)
    controls = map(collect(pairs(options))) do pair
        name, value = pair
        return name => create_option(value, name)
    end

    rows = Matrix{GridCell}(undef, length(options), 2)

    for (i, control) in pairs(last.(controls))
        label = getfield(control, :label)
        widget = getfield(control, :widget)
        if ismissing(label)
            rows[i, 1] = GridCell(widget, 1, 2)
            rows[i, 2] = ()
        elseif isnothing(label) || typeof(label) == Symbol
            label = string(isnothing(label) ? first(controls[i]) : label) * ":"
            rows[i, 1] = Label(length(label) == 2 ? label : format_option_name(label), @halign(:START))
            rows[i, 2] = widget
        else
            rows[i, 1] = label
            rows[i, 2] = widget
        end
    end

    grid = Grid(rows;
        @hexpand,
        @margin(10),
        @spacing(20)
    )

    return Controls((; zip(first.(controls), last.(controls))...), grid);
end

function Controls(; options...)
    keys = collect(pairs(options))
    return Controls((; zip(first.(keys), last.(keys))...))
end

function Base.string(controls::Controls)
    io = IOBuffer()
    traverse = (options, level) -> begin
        i = repeat("  ", level)
        for (name, option) in pairs(options)
            if option isa SectionOption
                println(io, string(name))
                traverse(getfield(option, :value)._options, level+1)
            else
                value = option[]
                value = value isa GtkWidget ? typeof(value) : value
                println(io, "$(i)$name: $value")
            end
        end
    end

    options = getfield(controls, :_options)
    traverse(options, 0)

    return String(take!(io))
end

function Base.show(io::IO, controls::Controls)
    println(io, "Controls")
    println(io, "  " * string(controls))
end

##############################################################################
################################## OPTIONS ###################################
##############################################################################

function create_option(self::Option, ::Symbol)
    return self;
end

function create_option(widget::W, name::Maybe{Symbol}) where {W <: GtkWidget}
    T = valuetype(widget)
    return Option{T}() do self
        self.widget = widget
        self.type = Symbol(string(W))
        self.label = name
        self.value = self.widget
        self.set = () -> nothing
    end
end

function create_option(button::GtkButton, ::Symbol)
    return Option{GtkButton}() do self
        self.widget = button
        self.label = missing
        self.type = :button
        self.value = button
        self.set = () -> nothing
    end
end

SectionOption = Option{Controls}

function create_option(options::NamedTuple, name::Maybe{Symbol})
    controls = Controls(options)
    grid = controls._grid
    return SectionOption() do self
        self.type = :section
        self.label = missing
        if name isa Symbol
            label = format_option_name(name)
            self.widget = Expander(() -> Frame(grid, margin_top=5), label, expanded=true)
        else
            self.widget = Frame(grid, margin_top=5)
        end
        self.value = controls
        self.set = () -> nothing
    end
end

function Base.getproperty(self::SectionOption, key::Symbol)
    key = string(key)
    if startswith(key, "_")
        return getfield(self, Symbol(key[2:end]))
    else
        return getproperty(getfield(self, :value), Symbol(key))
    end
end

function Base.iterate(self::SectionOption, i::Int = 1)
    options = getfield(self, :value)._options
    length(self) < i && return nothing
    return options[i], i + 1
end

Base.eltype(::SectionOption) = Option
Base.length(self::SectionOption) = length(getfield(self, :value)._options)
Base.size(self::SectionOption) = length(self)
Base.pairs(self::SectionOption) = pairs(getfield(self, :value)._options)

const InputOption = Option{AbstractString}

function create_option(v::AbstractString, name::Maybe{Symbol})::InputOption
    return InputOption() do self::InputOption
        self.type = :string
        self.widget = Entry(text = v, @hexpand)
        self.label = name
        self.value = v

        onevent(:changed, self.widget) do
            self.value = value(self.widget)
        end

        self.set = (text) -> begin
            self.value = text
            set!(self.widget, text = text)
        end
    end
end

const NumberOption = Option{Real}

function create_option(v::Real, name::Maybe{Symbol})::NumberOption
    range = -10 ≤ v ≤ 10 ? (-10:10) : (-2v:3v)
    return NumberOption() do self
        self.type = :number
        self.widget = SpinButton(range; init=v, @halign(:start))
        self.label = name
        self.value = value(self.widget)
        onevent(:value_changed, self.widget) do
            self.value = value(self.widget)
        end
        self.set = (v) -> (self.value = v; setvalue!(self.widget, v))
    end
end

function create_option((init, range)::Tuple{<:Real, AbstractRange}, name::Maybe{Symbol})::NumberOption
    return NumberOption() do self::NumberOption
        self.type = :number
        self.widget = SpinButton(range; init = init, @halign(:start))
        self.label = name
        self.value = value(self.widget)
        onevent(:value_changed, self.widget) do
            self.value = value(self.widget)
        end
        self.set = (v) -> (self.value = v; setvalue!(self.widget, v))
    end
end

const ColorOption = Option{RGBA}

function create_option(color::Colorant, name::Maybe{Symbol})
    return ColorOption() do self::ColorOption
        self.type = :color
        self.widget = ColorButton(color)
        self.label = name
        self.value = value(self.widget)
        onevent(:color_set, self.widget) do
            self.value = value(self.widget)
        end
        self.set = (v) -> (self.value = v; setvalue!(self.widget, v))
    end
end

function create_option(range::AbstractRange, name::Maybe{Symbol})
    return NumberOption() do self
        self.type = :range
        self.widget = Slider(range; margin_bottom = 16, @hexpand)
        self.label = name
        self.value = value(self.widget)
        onevent(:value_changed, self.widget) do
            self.value = value(self.widget)
        end
        self.set = (v) -> (self.value = v; setvalue!(self.widget, v))
    end
end

function create_option((range, init)::Tuple{AbstractRange, <:Real}, name::Maybe{Symbol})
    return NumberOption() do self
        self.type = :range
        self.widget = Slider(range; init=init, margin_bottom = 16, @hexpand)
        self.label = name
        self.value = value(self.widget)
        onevent(:value_changed, self.widget) do
            self.value = value(self.widget)
        end
        self.set = (v) -> (self.value = v; setvalue!(self.widget, v))
    end
end

const SwitchOption = Option{Bool}

function create_option(option::Bool, name::Maybe{Symbol})
    return SwitchOption() do self
        self.type = :switch
        self.widget = Switch(option, @halign(:start))
        self.label = name
        self.value = value(self.widget)
        onevent(:state_set, self.widget) do
            self.value = value(self.widget)
        end
        self.set = (v) -> (self.value = v; setvalue!(self.widget, v))
    end
end

const ComplexNOption = Option{Complex{<:Real}}

function create_option(x::Complex, name::Symbol)
    r, i = real(x), imag(x)
    return ComplexNOption() do self
        real_p = create_option(r, :real)
        imag_p = create_option(i, :imag)

        onevent(:value_changed, [real_p, imag_p]) do
            self.value = Complex(real_p.value, imag_p.value)
        end

        self.type = :complex_number

        self.label = missing
        label = Label(format_option_name(name), @halign(:START))

        self.widget = Grid(@spacing(10)) do
            [
                label → 3
                () Label("Real:", margin_left=10, @halign(:START)) real_p.widget
                () Label("Imag:", margin_left=10, @halign(:START)) imag_p.widget
            ]
        end

        self.value = x
        self.set = (y::Complex) -> begin
            real_p.set(real(y))
            imag_p.set(imag(y))
            self.value = y
        end
    end
end

const PointOption = Option{Point}

function create_option(point::Point, name::Symbol)
    return PointOption() do self
        x_p = create_option(point.x, :x)
        y_p = create_option(point.y, :y)

        onevent(:value_changed, [x_p, y_p]) do
            self.value = Point(value(x_p), value(y_p))
        end

        self.type = :point
        self.label = missing
        label = Label(format_option_name(name), @halign(:START))

        self.widget = Grid(@spacing(10)) do
            [
                label → 3
                () Label("x:", margin_left=10, @halign(:START)) x_p.widget
                () Label("y:", margin_left=10, @halign(:START)) y_p.widget
            ]
        end

        self.value = point
        self.set = (p::Point) -> begin
            x_p.set(p.x)
            y_p.set(p.y)
            self.value = p
        end
    end
end

macro options(ex)
    @assert Meta.isexpr(ex, :block)

    exprs = filter(ex.args) do x
        Meta.isexpr(x, :(=))
    end

    sections = map(first, getfield.(exprs, :args))

    quote
        begin
            global __OPTIONS__ = Controls($( Expr(:tuple, exprs...) ))
            $(Expr(:block,
                [
                    :( global $name = getproperty(__OPTIONS__, $(QuoteNode(name))) )
                    for name in sections
                ]...
            ))
            __OPTIONS__
        end
    end |> esc
end

addwidget(self::Controls) = (addwidget(self._grid); self)

struct NoLabel{T}
    value::T
    NoLabel(value::T) where{T} = new{T}(value)
end

macro nolabel(ex)
    return :( NoLabel($(esc(ex))) )
end

function create_option(x::NoLabel{T}, ::Symbol) where {T}
    return create_option(x.value, missing)
end


text:
using PyCall
# Change to local folder
cd(dirname(@__FILE__); # Thanks Dehann for neat fix for Atom
unshift!(PyVector(pyimport("sys")["path"]), "")
# A simple function that says hi from Julia
function juliaSayHi()
    println("[In Julia] Hi From Julia!");
end
# Let's initialize the Python module Python2Julia
pythonModule = pyimport("Python2Julia")
# And create a CallingJulia object
println("[In Julia] Creating the object CallingJulia...");
pythonClass = pythonModule[:CallingJulia](juliaSayHi) #I know, it's a Julia function, no casting... right?
# And then call a method in it
println("[In Julia] Okay calling the Python...");
pythonClass[:callMeBack]()

max_stars_repo_name: GearsAD/julia-examples

max_issues_repo_name: GearsAD/julia-examples

max_forks_repo_name: GearsAD/julia-examples


text:
#####
##### Periodic boundary conditions
#####

  fill_west_halo!(c, ::PBC, H::Int, N) = @views @. c.parent[1:H, :, :] = c.parent[N+1:N+H, :, :]
 fill_south_halo!(c, ::PBC, H::Int, N) = @views @. c.parent[:, 1:H, :] = c.parent[:, N+1:N+H, :]
fill_bottom_halo!(c, ::PBC, H::Int, N) = @views @. c.parent[:, :, 1:H] = c.parent[:, :, N+1:N+H]

 fill_east_halo!(c, ::PBC, H::Int, N) = @views @. c.parent[N+H+1:N+2H, :, :] = c.parent[1+H:2H, :, :]
fill_north_halo!(c, ::PBC, H::Int, N) = @views @. c.parent[:, N+H+1:N+2H, :] = c.parent[:, 1+H:2H, :]
  fill_top_halo!(c, ::PBC, H::Int, N) = @views @. c.parent[:, :, N+H+1:N+2H] = c.parent[:, :, 1+H:2H]

# Generate interface functions for periodic boundary conditions
sides = (:west, :east, :south, :north, :top, :bottom)
coords = (:x, :x, :y, :y, :z, :z)

for (x, side) in zip(coords, sides)
    name = Symbol(:fill_, side, :_halo!)
    H = Symbol(:H, x)
    N = Symbol(:N, x)
    @eval begin
        $name(c, bc::PBC, arch, dependencies, grid, args...; kwargs...) =
            $name(c, bc, grid.$(H), grid.$(N))
    end
end


text:
const gk_nodes = (
    (0.0,),
    (-1.732050807568877193e+00, 1.732050807568877193e+00),
    (-7.410953499945408529e-01, -2.861279576057058183e+00, -4.184956017672732287e+00, 7.410953499945408529e-01, 2.861279576057058183e+00, 4.184956017672732287e+00),
    (1.230423634027306035e+00, 2.596083115049202306e+00, 3.205333794499194422e+00, 5.187016039913656229e+00, 6.363394494336369611e+00, -1.230423634027306035e+00, -2.596083115049202306e+00, -3.205333794499194422e+00, -5.187016039913656229e+00, -6.363394494336369611e+00),
    (-3.035159417196289788e-01, -2.208370035755473193e+00, -3.673120807624038697e+00, -4.688944733396042786e+00, -5.738816857731674048e+00, -7.052048695931292244e+00, -7.809096669391978551e+00, -8.661390355138452790e+00, -9.691888484307325413e+00, 3.035159417196289788e-01, 2.208370035755473193e+00, 3.673120807624038697e+00, 4.688944733396042786e+00, 5.738816857731674048e+00, 7.052048695931292244e+00, 7.809096669391978551e+00, 8.661390355138452790e+00, 9.691888484307325413e+00),
    (-6.206215996851309757e-01, -9.041718401396522387e-01, -1.556920948898949275e+00, -1.874020592699235932e+00, -2.570161501011057670e+00, -3.588718867304420357e+00, -3.813668067407607332e+00, -4.519991606227620196e+00, -4.871869590277843720e+00, -5.474559779359854161e+00, -6.034481198100183796e+00, -6.707072145057108692e+00, -7.289858306075302607e+00, -7.460729234405580890e+00, -8.181394510092470540e+00, -8.612155515170002218e+00, -8.886347001304686799e+00, -9.295854667849322794e+00, -1.009182628500030354e+01, -1.049797509743559409e+01, -1.091154446366382835e+01, -1.133361676429119136e+01, -1.176537484480120277e+01, -1.220821525266299190e+01, -1.266385440024828846e+01, -1.313446784351190466e+01, -1.362290117407219192e+01, -1.413301728617947717e+01, -1.467031519464652867e+01, -1.524314486007864389e+01, -1.586543512793624977e+01, -1.656423516155702913e+01, -1.741041065963615253e+01, 6.206215996851309757e-01, 9.041718401396522387e-01, 1.556920948898949275e+00, 1.874020592699235932e+00, 2.570161501011057670e+00, 3.588718867304420357e+00, 3.813668067407607332e+00, 4.519991606227620196e+00, 4.871869590277843720e+00, 5.474559779359854161e+00, 6.034481198100183796e+00, 6.707072145057108692e+00, 7.289858306075302607e+00, 7.460729234405580890e+00, 8.181394510092470540e+00, 8.612155515170002218e+00, 8.886347001304686799e+00, 9.295854667849322794e+00, 1.009182628500030354e+01, 1.049797509743559409e+01, 1.091154446366382835e+01, 1.133361676429119136e+01, 1.176537484480120277e+01, 1.220821525266299190e+01, 1.266385440024828846e+01, 1.313446784351190466e+01, 1.362290117407219192e+01, 1.413301728617947717e+01, 1.467031519464652867e+01, 1.524314486007864389e+01, 1.586543512793624977e+01, 1.656423516155702913e+01, 1.741041065963615253e+01)
)
const gk_nodes_v = (
    [0.0],
    [-1.732050807568877193e+00, 1.732050807568877193e+00],
    [-7.410953499945408529e-01, -2.861279576057058183e+00, -4.184956017672732287e+00, 7.410953499945408529e-01, 2.861279576057058183e+00, 4.184956017672732287e+00],
    [1.230423634027306035e+00, 2.596083115049202306e+00, 3.205333794499194422e+00, 5.187016039913656229e+00, 6.363394494336369611e+00, -1.230423634027306035e+00, -2.596083115049202306e+00, -3.205333794499194422e+00, -5.187016039913656229e+00, -6.363394494336369611e+00],
    [-3.035159417196289788e-01, -2.208370035755473193e+00, -3.673120807624038697e+00, -4.688944733396042786e+00, -5.738816857731674048e+00, -7.052048695931292244e+00, -7.809096669391978551e+00, -8.661390355138452790e+00, -9.691888484307325413e+00, 3.035159417196289788e-01, 2.208370035755473193e+00, 3.673120807624038697e+00, 4.688944733396042786e+00, 5.738816857731674048e+00, 7.052048695931292244e+00, 7.809096669391978551e+00, 8.661390355138452790e+00, 9.691888484307325413e+00],
    [-6.206215996851309757e-01, -9.041718401396522387e-01, -1.556920948898949275e+00, -1.874020592699235932e+00, -2.570161501011057670e+00, -3.588718867304420357e+00, -3.813668067407607332e+00, -4.519991606227620196e+00, -4.871869590277843720e+00, -5.474559779359854161e+00, -6.034481198100183796e+00, -6.707072145057108692e+00, -7.289858306075302607e+00, -7.460729234405580890e+00, -8.181394510092470540e+00, -8.612155515170002218e+00, -8.886347001304686799e+00, -9.295854667849322794e+00, -1.009182628500030354e+01, -1.049797509743559409e+01, -1.091154446366382835e+01, -1.133361676429119136e+01, -1.176537484480120277e+01, -1.220821525266299190e+01, -1.266385440024828846e+01, -1.313446784351190466e+01, -1.362290117407219192e+01, -1.413301728617947717e+01, -1.467031519464652867e+01, -1.524314486007864389e+01, -1.586543512793624977e+01, -1.656423516155702913e+01, -1.741041065963615253e+01, 6.206215996851309757e-01, 9.041718401396522387e-01, 1.556920948898949275e+00, 1.874020592699235932e+00, 2.570161501011057670e+00, 3.588718867304420357e+00, 3.813668067407607332e+00, 4.519991606227620196e+00, 4.871869590277843720e+00, 5.474559779359854161e+00, 6.034481198100183796e+00, 6.707072145057108692e+00, 7.289858306075302607e+00, 7.460729234405580890e+00, 8.181394510092470540e+00, 8.612155515170002218e+00, 8.886347001304686799e+00, 9.295854667849322794e+00, 1.009182628500030354e+01, 1.049797509743559409e+01, 1.091154446366382835e+01, 1.133361676429119136e+01, 1.176537484480120277e+01, 1.220821525266299190e+01, 1.266385440024828846e+01, 1.313446784351190466e+01, 1.362290117407219192e+01, 1.413301728617947717e+01, 1.467031519464652867e+01, 1.524314486007864389e+01, 1.586543512793624977e+01, 1.656423516155702913e+01, 1.741041065963615253e+01]
)
const gk_nodes_0 = (0.0,)
const gk_nodes_1 = (-1.732050807568877193e+00, 1.732050807568877193e+00),
const gk_nodes_2 = (-7.410953499945408529e-01, -2.861279576057058183e+00, -4.184956017672732287e+00, 7.410953499945408529e-01, 2.861279576057058183e+00, 4.184956017672732287e+00)
const gk_nodes_3 = (1.230423634027306035e+00, 2.596083115049202306e+00, 3.205333794499194422e+00, 5.187016039913656229e+00, 6.363394494336369611e+00, -1.230423634027306035e+00, -2.596083115049202306e+00, -3.205333794499194422e+00, -5.187016039913656229e+00, -6.363394494336369611e+00)
const gk_nodes_4 =  (-3.035159417196289788e-01, -2.208370035755473193e+00, -3.673120807624038697e+00, -4.688944733396042786e+00, -5.738816857731674048e+00, -7.052048695931292244e+00, -7.809096669391978551e+00, -8.661390355138452790e+00, -9.691888484307325413e+00, 3.035159417196289788e-01, 2.208370035755473193e+00, 3.673120807624038697e+00, 4.688944733396042786e+00, 5.738816857731674048e+00, 7.052048695931292244e+00, 7.809096669391978551e+00, 8.661390355138452790e+00, 9.691888484307325413e+00)
const gk_nodes_5 = (-6.206215996851309757e-01, -9.041718401396522387e-01, -1.556920948898949275e+00, -1.874020592699235932e+00, -2.570161501011057670e+00, -3.588718867304420357e+00, -3.813668067407607332e+00, -4.519991606227620196e+00, -4.871869590277843720e+00, -5.474559779359854161e+00, -6.034481198100183796e+00, -6.707072145057108692e+00, -7.289858306075302607e+00, -7.460729234405580890e+00, -8.181394510092470540e+00, -8.612155515170002218e+00, -8.886347001304686799e+00, -9.295854667849322794e+00, -1.009182628500030354e+01, -1.049797509743559409e+01, -1.091154446366382835e+01, -1.133361676429119136e+01, -1.176537484480120277e+01, -1.220821525266299190e+01, -1.266385440024828846e+01, -1.313446784351190466e+01, -1.362290117407219192e+01, -1.413301728617947717e+01, -1.467031519464652867e+01, -1.524314486007864389e+01, -1.586543512793624977e+01, -1.656423516155702913e+01, -1.741041065963615253e+01, 6.206215996851309757e-01, 9.041718401396522387e-01, 1.556920948898949275e+00, 1.874020592699235932e+00, 2.570161501011057670e+00, 3.588718867304420357e+00, 3.813668067407607332e+00, 4.519991606227620196e+00, 4.871869590277843720e+00, 5.474559779359854161e+00, 6.034481198100183796e+00, 6.707072145057108692e+00, 7.289858306075302607e+00, 7.460729234405580890e+00, 8.181394510092470540e+00, 8.612155515170002218e+00, 8.886347001304686799e+00, 9.295854667849322794e+00, 1.009182628500030354e+01, 1.049797509743559409e+01, 1.091154446366382835e+01, 1.133361676429119136e+01, 1.176537484480120277e+01, 1.220821525266299190e+01, 1.266385440024828846e+01, 1.313446784351190466e+01, 1.362290117407219192e+01, 1.413301728617947717e+01, 1.467031519464652867e+01, 1.524314486007864389e+01, 1.586543512793624977e+01, 1.656423516155702913e+01, 1.741041065963615253e+01)

const gk_nodes_nonneg = (
    ((0.0,),),
    ( (0.0,), (1.732050807568877193e+00,) ),
    ( (0.0,), (1.732050807568877193e+00,), (7.410953499945408529e-01, 2.861279576057058183e+00, 4.184956017672732287e+00)),
    ( (0.0,), (1.732050807568877193e+00,), (7.410953499945408529e-01, 2.861279576057058183e+00, 4.184956017672732287e+00), (1.230423634027306035e+00,2.596083115049202306e+00, 3.205333794499194422e+00, 5.187016039913656229e+00, 6.363394494336369611e+00) ),
    ( (0.0,), (1.732050807568877193e+00,), (7.410953499945408529e-01, 2.861279576057058183e+00, 4.184956017672732287e+00), (1.230423634027306035e+00, 2.596083115049202306e+00, 3.205333794499194422e+00, 5.187016039913656229e+00, 6.363394494336369611e+00), (3.035159417196289788e-01, 2.208370035755473193e+00, 3.673120807624038697e+00, 4.688944733396042786e+00, 5.738816857731674048e+00, 7.052048695931292244e+00, 7.809096669391978551e+00, 8.661390355138452790e+00, 9.691888484307325413e+00) ),
    ( (0.0,), (1.732050807568877193e+00,), (7.410953499945408529e-01, 2.861279576057058183e+00, 4.184956017672732287e+00), (1.230423634027306035e+00, 2.596083115049202306e+00, 3.205333794499194422e+00, 5.187016039913656229e+00, 6.363394494336369611e+00), (3.035159417196289788e-01, 2.208370035755473193e+00, 3.673120807624038697e+00, 4.688944733396042786e+00, 5.738816857731674048e+00, 7.052048695931292244e+00, 7.809096669391978551e+00, 8.661390355138452790e+00, 9.691888484307325413e+00), (6.206215996851309757e-01, 9.041718401396522387e-01, 1.556920948898949275e+00, 1.874020592699235932e+00, 2.570161501011057670e+00, 3.588718867304420357e+00, 3.813668067407607332e+00, 4.519991606227620196e+00, 4.871869590277843720e+00, 5.474559779359854161e+00, 6.034481198100183796e+00, 6.707072145057108692e+00, 7.289858306075302607e+00, 7.460729234405580890e+00, 8.181394510092470540e+00, 8.612155515170002218e+00, 8.886347001304686799e+00, 9.295854667849322794e+00, 1.009182628500030354e+01, 1.049797509743559409e+01, 1.091154446366382835e+01, 1.133361676429119136e+01, 1.176537484480120277e+01, 1.220821525266299190e+01, 1.266385440024828846e+01, 1.313446784351190466e+01, 1.362290117407219192e+01, 1.413301728617947717e+01, 1.467031519464652867e+01, 1.524314486007864389e+01, 1.586543512793624977e+01, 1.656423516155702913e+01, 1.741041065963615253e+01) )
)

const gk_weights = (
    ((1.0,),),
    ((6.666666666666666297e-01,), (1.666666666666666574e-01,)),
    ((2.539682539682539542e-01,), (9.485094850948509737e-02,), (2.700743295779378661e-01, 7.996325470893532808e-03, 9.426945755651748365e-05)),
    ((3.034671998542058935e-01,), (6.409605468680758256e-02,), (2.083249916496088816e-01, -6.337224793373735440e-03, 6.012336945984782032e-05), (6.115173012524767471e-02,1.808523425479845181e-02, 2.884880436506751140e-03, 6.094808731468982961e-07, 8.629684602229885931e-10)),
    ((9.688245529284254809e-02,), (4.421164421898454711e-02,), (1.430993028968333969e-01, 1.768022258182954352e-03, 3.226518598373974471e-05), (9.372082806552459178e-02, 4.333498812272349072e-03, 9.858275829964838720e-04, 2.959075202307440677e-07, 4.225258439631110457e-10), (1.476557104026862410e-01, 1.551310987485935398e-02, 2.349403664659752112e-04, 3.309758709792034345e-06, 1.659544880938981831e-08, 4.566176367618685878e-12, 1.822427515491293625e-14, 1.877818931437289588e-17, 1.903035094013049694e-21)),
    ((1.205674705975654931e-01,), (-2.241690549232919737e-03,), (-2.510946060860437534e-02, 2.317853741494368004e-03, 2.157340473532454820e-05), (6.054609539583663547e-02, -6.868088867756604043e-03, 8.108079306253045517e-04, 1.756589052393765114e-07, 2.175702428714775840e-10), (1.166672226897644410e-01, 1.165794765237651055e-02, -2.555098045918444941e-04, 2.736249936842626933e-07, 7.699205480918628382e-09, 2.123779208924948428e-12, 8.335951137105458603e-15, -1.603802571689216247e-17, 6.351777619826335869e-22), (1.161449102169717779e-01, 9.049907887097373427e-02, 3.958048330358010514e-02, 2.349638855141306104e-02, 1.187429460595669506e-02, 4.283096239652469652e-04, 1.399993373051156139e-04, 4.675973952563834421e-06, 8.812581632544770710e-07, 3.318711099677051844e-08, 1.560543759860818455e-09, 2.360855272927444972e-11, 1.169869203766870029e-13, 1.013359032410814206e-13, 4.429742347393624813e-16, 3.262744522103358460e-17, 1.322870363778446040e-18, 2.717875933335900016e-20, 1.232134560467146984e-23, 1.914714214218525338e-25, 2.332204174318528461e-27, 2.179136932463778929e-29, 1.524177029773773434e-31, 7.750724758884266004e-34, 2.764556078556950881e-36, 6.610498069228468602e-39, 9.992242712355998473e-42, 8.823151988713996391e-45, 4.072624717633741158e-48, 8.321030089138647840e-52, 5.728650998340608745e-56, 7.912918315856256558e-61, 5.881010699300556648e-67))
)

const weighted_gk_weights = (
    ((1.0,),),
    ((6.666666666666666297000000000000000000000000000000000000000000000000000000000002e-01,), (7.469481783896772988457527699794061672980745700022560408596162118340808426721962e-01,7.469481783896772988457527699794061672980745700022560408596162118340808426721962e-01)),
    ((2.539682539682539541999999999999999999999999999999999999999999999999999999999988e-01,), (4.250924592461578472759876805552536329599586523523682709259908670256577684243761e-01,4.250924592461578472759876805552536329599586523523682709259908670256577684243761e-01), (3.554229094726574982860442760983532555588167824313428698590967717008450205251302e-01, 4.793555157593584816398270172093156025646331160551993334837656250436617254414600e-01, 5.990412180534271700286076322376124144529767305328254509252998705048447247649803e-01,
    3.554229094726574982860442760983532555588167824313428698590967717008450205251302e-01, 4.793555157593584816398270172093156025646331160551993334837656250436617254414600e-01, 5.990412180534271700286076322376124144529767305328254509252998705048447247649803e-01)),
    ((3.034671998542058935000000000000000000000000000000000000000000000000000000000000e-01,), (2.872585877416563872923859174001655426169576823366256035985979317280372371506416e-01,
    2.872585877416563872923859174001655426169576823366256035985979317280372371506416e-01,), (2.741596165903048231254842627399873640947342306275468152337277728975795964203473e-01, -3.798974504437236345476663821676787033819236760209767324667376204925070214866375e-01, 3.82057746042619577466460231832021988947777427472900800439360113662814069216201e-01,
    2.741596165903048231254842627399873640947342306275468152337277728975795964203473e-01, -3.798974504437236345476663821676787033819236760209767324667376204925070214866375e-01, 3.82057746042619577466460231832021988947777427472900800439360113662814069216201e-01), (1.303638405254942398659921882662298597171952334211712030622447379181678924224902e-01, 5.257993039121150066942942760063309508915527286203890571040318547131226910007951e-01, 4.910597559959024396827368462951747108311140147810245954105871604633544199013856e-01, 4.239708523478058208142833543104371604410325009662179294092721824359687679500878e-01, 5.356639749505990342664174794050651607839649596753828921013245685339949128066048e-01,
    1.303638405254942398659921882662298597171952334211712030622447379181678924224902e-01, 5.257993039121150066942942760063309508915527286203890571040318547131226910007951e-01, 4.910597559959024396827368462951747108311140147810245954105871604633544199013856e-01, 4.239708523478058208142833543104371604410325009662179294092721824359687679500878e-01, 5.356639749505990342664174794050651607839649596753828921013245685339949128066048e-01)),
    ((9.688245529284254808999999999999999999999999999999999999999999999999999999999973e-02,), (1.981428426778980984412600814819064066197916004754116602341340067537383921399099e-01,
    1.981428426778980984412600814819064066197916004754116602341340067537383921399099e-01), (1.883213804828653468614944070827636503374772062253660876775346574368894296123359e-01, 1.059875844886804440092869110403572114614088909440086983015607835246120812498014e-01, 2.050311608171923251432647743399691597188646613280832007288539163124739211851223e-01,
    1.883213804828653468614944070827636503374772062253660876775346574368894296123359e-01, 1.059875844886804440092869110403572114614088909440086983015607835246120812498014e-01, 2.050311608171923251432647743399691597188646613280832007288539163124739211851223e-01), (1.997949536150074469472153344857304638452646615078951601015156424405452101031627e-01, 1.259895573866964685133959071955945228524379013064007907876920512461750179612389e-01, 1.67806002021515926781812697325227273981706539769413320575134754468269761718468e-01, 2.058410183088985338488574359666944058810790080238993669350031543082753239694951e-01, 2.622713152670181245847792066189062454897386919633485046840126633035438008876432e-01,
    1.997949536150074469472153344857304638452646615078951601015156424405452101031627e-01, 1.259895573866964685133959071955945228524379013064007907876920512461750179612389e-01, 1.67806002021515926781812697325227273981706539769413320575134754468269761718468e-01, 2.058410183088985338488574359666944058810790080238993669350031543082753239694951e-01, 2.622713152670181245847792066189062454897386919633485046840126633035438008876432e-01), (1.546159416265305613521062647988422327207440056433022066888637894519247591069617e-01, 1.777067237741947016011107256772430707943478489463044630983584233106965784410551e-01, 1.998335313964808739470910767885214844575959156383317195911069335120796374817492e-01, 1.968065697283842595393871134022617467268891580336636978901510751590663220829677e-01, 2.352449695913756290871153743077223673253485830732344148566236444253501744805265e-01, 2.874663303616266215185713034517514646718100831157478554314080989203956121474342e-01, 3.182154869178219322525709717261600085800217046015508192285268999262191679309989e-01, 3.66412995642927566567209315391227998614780120255270692272877691761267033639734e-01, 4.749785056705039548294688635784742503358477008080817452603676938307273765655888e-01,
    1.546159416265305613521062647988422327207440056433022066888637894519247591069617e-01, 1.777067237741947016011107256772430707943478489463044630983584233106965784410551e-01, 1.998335313964808739470910767885214844575959156383317195911069335120796374817492e-01, 1.968065697283842595393871134022617467268891580336636978901510751590663220829677e-01, 2.352449695913756290871153743077223673253485830732344148566236444253501744805265e-01, 2.874663303616266215185713034517514646718100831157478554314080989203956121474342e-01, 3.182154869178219322525709717261600085800217046015508192285268999262191679309989e-01, 3.66412995642927566567209315391227998614780120255270692272877691761267033639734e-01, 4.749785056705039548294688635784742503358477008080817452603676938307273765655888e-01)),
    ((1.205674705975654931000000000000000000000000000000000000000000000000000000000000e-01,), (-1.004656003357730823806188974619091124793125834446191621452480233775848578618848e-02,
    -1.004656003357730823806188974619091124793125834446191621452480233775848578618848e-02), (-3.304452355300148100907701108660353984545851091544121345792423435861862467492072e-02, 1.389483181685245561998489162800461481863219504281205217919283409423287612744794e-01, 1.370895620403929221796390803646287110031864827723960976487722418310067161769682e-01,
    -3.304452355300148100907701108660353984545851091544121345792423435861862467492072e-02, 1.389483181685245561998489162800461481863219504281205217919283409423287612744794e-01, 1.370895620403929221796390803646287110031864827723960976487722418310067161769682e-01), (1.290727426429006555492847049521242122808175102340887965026895848184566932833196e-01, -1.996787155198069833761048469679109478999974584765022381562309378357435651854228e-01, 1.380144353762277285999381191666272523336755548897420894976987031710802154905806e-01, 1.221929334587518376259432748909909467881910101233360640314212238681512645094766e-01, 1.350507538796819284118108665412593848348812381302706974707395964723043592556429e-01,
    1.290727426429006555492847049521242122808175102340887965026895848184566932833196e-01, -1.996787155198069833761048469679109478999974584765022381562309378357435651854228e-01, 1.380144353762277285999381191666272523336755548897420894976987031710802154905806e-01, 1.221929334587518376259432748909909467881910101233360640314212238681512645094766e-01, 1.350507538796819284118108665412593848348812381302706974707395964723043592556429e-01), (1.221667109516808190370518250428476817502289488961063083653087292766837791614186e-01, 1.335448340111544981514326484249212091804964172890004698602494327928524979978424e-01, -2.173293049894328541785639712838913063596493364318502740867021633896889137893188e-01, 1.627042969616786323017137575123847206390897111941153829472217340886271988531726e-02, 1.091383173808271059912672611652228508086363209626270939980457402609529582966774e-01, 1.337037745667200228518061287391775756922632633663635424192783589137993003687799e-01, 1.455546916115390192433400169433867669456458997723005332002505712744662073949346e-01, -3.129450315333034711164409656696647940753668072869003756323156170457042397932826e-01, 1.585340097882490853220738371167806400656320914148613019992326744838319491407595e-01,
    1.221667109516808190370518250428476817502289488961063083653087292766837791614186e-01, 1.335448340111544981514326484249212091804964172890004698602494327928524979978424e-01, -2.173293049894328541785639712838913063596493364318502740867021633896889137893188e-01, 1.627042969616786323017137575123847206390897111941153829472217340886271988531726e-02, 1.091383173808271059912672611652228508086363209626270939980457402609529582966774e-01, 1.337037745667200228518061287391775756922632633663635424192783589137993003687799e-01, 1.455546916115390192433400169433867669456458997723005332002505712744662073949346e-01, -3.129450315333034711164409656696647940753668072869003756323156170457042397932826e-01, 1.585340097882490853220738371167806400656320914148613019992326744838319491407595e-01), (1.408117965428582459162876149363881074540291961667053616321683414171503557489225e-01, 1.361970903861409165299347684909556849651325954647563203911887203853041023300648e-01, 1.329984629599679201317532559224692811885529412841919573627476858474076436367604e-01, 1.360229092078236952036773310956155750965076532404155400226276895185758575773446e-01, 3.228671754698710762567279580670329963945941193375398234348914314055081946042006e-01, 2.681489553918453044734559581543139773799622567549983705451696642331003349397749e-01, 2.015252077912545915669213003253490099523789818885819528195164688838272053088035e-01, 1.277204963843742976731996322288040800440204600020807221200522741183918951669275e-01, 1.256369893314551374852865986062839874863648830088856658669781405776860179840158e-01, 1.069170615807775867674670213187129633032953515717362686527691924792778806061541e-01, 1.260911971045680313452531871444771489334082184216232741175732749569181962079643e-01, 1.384835564679941519175122395707968073610522851416296138819888353652825409237885e-01, 4.053063396124052977373168417958918070128745886215735357114089793458949085693095e-02, 1.237990902870524369339555228492741317324406532190547262207679352134549377006608e-01, 1.517665185116327857270968738247869921185266823756355447386381896991320724004838e-01, 4.161262608892393519996858911156575973478844323821317971560465194785734821058607e-01, 1.857885153653686170918007032119532731433290633576380885676252281072935041150899e-01, 1.579630413832698922610809900762769849144924553399148831499524839581697316463859e-01, 1.606977230566520625746424052702404009903917533249360598570248398470460477209748e-01, 1.634385213505341330257697809858487597950195971180970507490215809799994145417857e-01, 1.666128532912926033083987912253689356198430144454419623138038929938517981765681e-01, 1.702300841125100847403377929828536379058458801150613409786168681599088845609372e-01, 1.743552051527007763833944392826094663092892128050440505451002005909832494783034e-01, 1.790935510945458777310090095483319171925624763449518313998782327281702016680291e-01, 1.845971971113272278601583938297960255043302296508511695418342101046108124115428e-01, 1.910850124205492485686214821819739358069442477378959613913593635449865408945723e-01, 1.988813937429899161582019334591191093761050728102145147551721737166719001341179e-01, 2.084906246429884317899166651270953944098724445617473229600911586848007892152892e-01, 2.207503567962314258656209780836950928147267874812765663538672701189731196089008e-01, 2.371870598593791815084402714470599016010287742002505126151560513044627873269844e-01, 2.60991031806506170012377255229863125256172232871574431654511691260342019258654e-01, 3.005170538128573338790480965022348051757581084764165815972783299215065489942171e-01, 3.905212369293002235972355867990859074521287143810981639577764587251872598475516e-01,
    1.408117965428582459162876149363881074540291961667053616321683414171503557489225e-01, 1.361970903861409165299347684909556849651325954647563203911887203853041023300648e-01, 1.329984629599679201317532559224692811885529412841919573627476858474076436367604e-01, 1.360229092078236952036773310956155750965076532404155400226276895185758575773446e-01, 3.228671754698710762567279580670329963945941193375398234348914314055081946042006e-01, 2.681489553918453044734559581543139773799622567549983705451696642331003349397749e-01, 2.015252077912545915669213003253490099523789818885819528195164688838272053088035e-01, 1.277204963843742976731996322288040800440204600020807221200522741183918951669275e-01, 1.256369893314551374852865986062839874863648830088856658669781405776860179840158e-01, 1.069170615807775867674670213187129633032953515717362686527691924792778806061541e-01, 1.260911971045680313452531871444771489334082184216232741175732749569181962079643e-01, 1.384835564679941519175122395707968073610522851416296138819888353652825409237885e-01, 4.053063396124052977373168417958918070128745886215735357114089793458949085693095e-02, 1.237990902870524369339555228492741317324406532190547262207679352134549377006608e-01, 1.517665185116327857270968738247869921185266823756355447386381896991320724004838e-01, 4.161262608892393519996858911156575973478844323821317971560465194785734821058607e-01, 1.857885153653686170918007032119532731433290633576380885676252281072935041150899e-01, 1.579630413832698922610809900762769849144924553399148831499524839581697316463859e-01, 1.606977230566520625746424052702404009903917533249360598570248398470460477209748e-01, 1.634385213505341330257697809858487597950195971180970507490215809799994145417857e-01, 1.666128532912926033083987912253689356198430144454419623138038929938517981765681e-01, 1.702300841125100847403377929828536379058458801150613409786168681599088845609372e-01, 1.743552051527007763833944392826094663092892128050440505451002005909832494783034e-01, 1.790935510945458777310090095483319171925624763449518313998782327281702016680291e-01, 1.845971971113272278601583938297960255043302296508511695418342101046108124115428e-01, 1.910850124205492485686214821819739358069442477378959613913593635449865408945723e-01, 1.988813937429899161582019334591191093761050728102145147551721737166719001341179e-01, 2.084906246429884317899166651270953944098724445617473229600911586848007892152892e-01, 2.207503567962314258656209780836950928147267874812765663538672701189731196089008e-01, 2.371870598593791815084402714470599016010287742002505126151560513044627873269844e-01, 2.60991031806506170012377255229863125256172232871574431654511691260342019258654e-01, 3.005170538128573338790480965022348051757581084764165815972783299215065489942171e-01, 3.905212369293002235972355867990859074521287143810981639577764587251872598475516e-01))
)

const weighted_gk_weights_nonneg = (
    ((1.0,),),
    ((6.666666666666666297000000000000000000000000000000000000000000000000000000000002e-01,), (7.469481783896772988457527699794061672980745700022560408596162118340808426721962e-01,)),
    ((2.539682539682539541999999999999999999999999999999999999999999999999999999999988e-01,), (4.250924592461578472759876805552536329599586523523682709259908670256577684243761e-01,), (3.554229094726574982860442760983532555588167824313428698590967717008450205251302e-01, 4.793555157593584816398270172093156025646331160551993334837656250436617254414600e-01, 5.990412180534271700286076322376124144529767305328254509252998705048447247649803e-01)),
    ((3.034671998542058935000000000000000000000000000000000000000000000000000000000000e-01,), (2.872585877416563872923859174001655426169576823366256035985979317280372371506416e-01,), (2.741596165903048231254842627399873640947342306275468152337277728975795964203473e-01, -3.798974504437236345476663821676787033819236760209767324667376204925070214866375e-01, 3.82057746042619577466460231832021988947777427472900800439360113662814069216201e-01), (1.303638405254942398659921882662298597171952334211712030622447379181678924224902e-01, 5.257993039121150066942942760063309508915527286203890571040318547131226910007951e-01, 4.910597559959024396827368462951747108311140147810245954105871604633544199013856e-01, 4.239708523478058208142833543104371604410325009662179294092721824359687679500878e-01, 5.356639749505990342664174794050651607839649596753828921013245685339949128066048e-01)),
    ((9.688245529284254808999999999999999999999999999999999999999999999999999999999973e-02,), (1.981428426778980984412600814819064066197916004754116602341340067537383921399099e-01,), (1.883213804828653468614944070827636503374772062253660876775346574368894296123359e-01, 1.059875844886804440092869110403572114614088909440086983015607835246120812498014e-01, 2.050311608171923251432647743399691597188646613280832007288539163124739211851223e-01), (1.997949536150074469472153344857304638452646615078951601015156424405452101031627e-01, 1.259895573866964685133959071955945228524379013064007907876920512461750179612389e-01, 1.67806002021515926781812697325227273981706539769413320575134754468269761718468e-01, 2.058410183088985338488574359666944058810790080238993669350031543082753239694951e-01, 2.622713152670181245847792066189062454897386919633485046840126633035438008876432e-01), (1.546159416265305613521062647988422327207440056433022066888637894519247591069617e-01, 1.777067237741947016011107256772430707943478489463044630983584233106965784410551e-01, 1.998335313964808739470910767885214844575959156383317195911069335120796374817492e-01, 1.968065697283842595393871134022617467268891580336636978901510751590663220829677e-01, 2.352449695913756290871153743077223673253485830732344148566236444253501744805265e-01, 2.874663303616266215185713034517514646718100831157478554314080989203956121474342e-01, 3.182154869178219322525709717261600085800217046015508192285268999262191679309989e-01, 3.66412995642927566567209315391227998614780120255270692272877691761267033639734e-01, 4.749785056705039548294688635784742503358477008080817452603676938307273765655888e-01)),
    ((1.205674705975654931000000000000000000000000000000000000000000000000000000000000e-01,), (-1.004656003357730823806188974619091124793125834446191621452480233775848578618848e-02,), (-3.304452355300148100907701108660353984545851091544121345792423435861862467492072e-02, 1.389483181685245561998489162800461481863219504281205217919283409423287612744794e-01, 1.370895620403929221796390803646287110031864827723960976487722418310067161769682e-01), (1.290727426429006555492847049521242122808175102340887965026895848184566932833196e-01, -1.996787155198069833761048469679109478999974584765022381562309378357435651854228e-01, 1.380144353762277285999381191666272523336755548897420894976987031710802154905806e-01, 1.221929334587518376259432748909909467881910101233360640314212238681512645094766e-01, 1.350507538796819284118108665412593848348812381302706974707395964723043592556429e-01), (1.221667109516808190370518250428476817502289488961063083653087292766837791614186e-01, 1.335448340111544981514326484249212091804964172890004698602494327928524979978424e-01, -2.173293049894328541785639712838913063596493364318502740867021633896889137893188e-01, 1.627042969616786323017137575123847206390897111941153829472217340886271988531726e-02, 1.091383173808271059912672611652228508086363209626270939980457402609529582966774e-01, 1.337037745667200228518061287391775756922632633663635424192783589137993003687799e-01, 1.455546916115390192433400169433867669456458997723005332002505712744662073949346e-01, -3.129450315333034711164409656696647940753668072869003756323156170457042397932826e-01, 1.585340097882490853220738371167806400656320914148613019992326744838319491407595e-01), (1.408117965428582459162876149363881074540291961667053616321683414171503557489225e-01, 1.361970903861409165299347684909556849651325954647563203911887203853041023300648e-01, 1.329984629599679201317532559224692811885529412841919573627476858474076436367604e-01, 1.360229092078236952036773310956155750965076532404155400226276895185758575773446e-01, 3.228671754698710762567279580670329963945941193375398234348914314055081946042006e-01, 2.681489553918453044734559581543139773799622567549983705451696642331003349397749e-01, 2.015252077912545915669213003253490099523789818885819528195164688838272053088035e-01, 1.277204963843742976731996322288040800440204600020807221200522741183918951669275e-01, 1.256369893314551374852865986062839874863648830088856658669781405776860179840158e-01, 1.069170615807775867674670213187129633032953515717362686527691924792778806061541e-01, 1.260911971045680313452531871444771489334082184216232741175732749569181962079643e-01, 1.384835564679941519175122395707968073610522851416296138819888353652825409237885e-01, 4.053063396124052977373168417958918070128745886215735357114089793458949085693095e-02, 1.237990902870524369339555228492741317324406532190547262207679352134549377006608e-01, 1.517665185116327857270968738247869921185266823756355447386381896991320724004838e-01, 4.161262608892393519996858911156575973478844323821317971560465194785734821058607e-01, 1.857885153653686170918007032119532731433290633576380885676252281072935041150899e-01, 1.579630413832698922610809900762769849144924553399148831499524839581697316463859e-01, 1.606977230566520625746424052702404009903917533249360598570248398470460477209748e-01, 1.634385213505341330257697809858487597950195971180970507490215809799994145417857e-01, 1.666128532912926033083987912253689356198430144454419623138038929938517981765681e-01, 1.702300841125100847403377929828536379058458801150613409786168681599088845609372e-01, 1.743552051527007763833944392826094663092892128050440505451002005909832494783034e-01, 1.790935510945458777310090095483319171925624763449518313998782327281702016680291e-01, 1.845971971113272278601583938297960255043302296508511695418342101046108124115428e-01, 1.910850124205492485686214821819739358069442477378959613913593635449865408945723e-01, 1.988813937429899161582019334591191093761050728102145147551721737166719001341179e-01, 2.084906246429884317899166651270953944098724445617473229600911586848007892152892e-01, 2.207503567962314258656209780836950928147267874812765663538672701189731196089008e-01, 2.371870598593791815084402714470599016010287742002505126151560513044627873269844e-01, 2.60991031806506170012377255229863125256172232871574431654511691260342019258654e-01, 3.005170538128573338790480965022348051757581084764165815972783299215065489942171e-01, 3.905212369293002235972355867990859074521287143810981639577764587251872598475516e-01))
)
const rule_lengths = (1,2,6,10,18,66)
const rules_total = (1,3,9,19,37,103)
const path = "/home/chris/Documents/progwork/julia/hermite/rules_nw"

function create_filename(rule)
    file = path * "/rule_"
    for i ∈ 1:rule
        file *= string(rules_list[i]) * "_"
    end
    file *= "qr_0.csv"
    file
end

"""
Creates and outputs sorted symmetric nested rules
so that we
"""
function print_rules(rule)
    out = Vector{Matrix{String}}(uninitialized, rule)
    floats = Vector{Vector{Float64}}(uninitialized, rule)
    for i ∈ rule:-1:1
        file = create_filename(i)
        temp_nodes = round.(@view(readdlm( file, ',')[1,:]),10)
        non_negative_temp_nodes = temp_nodes .>= 0
        out[i] = readdlm( file, ',', String)[[1,3],non_negative_temp_nodes]
        floats[i] = temp_nodes[non_negative_temp_nodes]
        if i < rule
            fi = floats[i]
            fip1 = floats[i+1]
            fadditions = fip1[[ fip1[k] ∉ fi for k ∈ eachindex(fip1) ]]
            n_ip1 = length(fip1)
        end
        for j ∈ i+1:rule
            fj = floats[j]
            inds = 1:n_ip1
            new_inds = [ fj[k] ∈ fadditions for k ∈ 1:n_ip1 ]
            sortperm_new_inds = sortperm(fj[inds][new_inds])
    #        if i > 1
                sortperm_unsorted = new_inds .== false
    #            @show sum(sortperm_unsorted)
                ind_sort = vcat( inds[sortperm_unsorted], (inds[new_inds])[sortperm_new_inds], n_ip1+1:length(fj) )
     #       else
     #           ind_sort = vcat( inds[new_inds][sortperm_new_inds], n_ip1+1:length(fj) )
     #       end
            fjsorted = fj[ind_sort]
            # @show (i,j)
            # @show fj
            # @show ind_sort
            # @show fjsorted
            # @show (length(fj), length(ind_sort))
            # println("\n")
            floats[j] = fjsorted
            out[j] = out[j][:,ind_sort]
        end
    end
    out
end

function print_string_mat(x)
    reduce((a,b) -> a * "," * b, x)
end
print_weighted_weights(A) = print_weighted_weights(A[1,:], A[2,:])
function print_weighted_weights(nodes, weights)
    out = ""
    for i in eachindex(nodes)
        n = BigFloat(strip(nodes[i]))
        w = BigFloat(strip(weights[i]))
        out *= string(exp(n^2/2)*w) * ", "
    end
    out
end

#using Reduce, SpecialFunctions
#Reduce.Rational(false);

gen_diff(v, i) = v > 0 ? :( $(Symbol('`' + i, :_, v)) - $(Symbol('`' + i, :_, v-1)) ) : Symbol('`' + i, :_, v)
function tupGridd(x::NTuple{N,T}) where {N,T<:Integer}
    Expr(:call, :*, ntuple(i -> gen_diff(x[i], i), Val{N}())... )
end
@generated function max_degree_poly(::Val{N}, l::Int, T = Int) where N
    quote
        j_0 = l
        s_0 = 0
        ind = 0
        out = Vector{NTuple{N,T}}(undef, binomial($N+l,$N))
        @nloops $N i p -> begin
            0:j_{$N-p}
        end p -> begin
            s_{$N-p+1} = s_{$N-p} + i_p
            j_{$N-p+1} = l - s_{$N-p+1}
        end begin
            ind += 1
            out[ind] = @ntuple $N j -> T(i_{j})
        end
        out
    end
end
function weights(::Val{N}, l::Int) where N
    p1 = max_degree_poly(Val{N}(), l)
    s1 = process_weights_no_deriv(p1)
    rcall(s1, :expand)::Expr
end
function process_weights_no_deriv(x::Vector{NTuple{N,Int}}) where N
    if length(x) == 1
        return tupGridd(x[1])
    end
    expr = Expr(:call, :+, tupGridd(x[1]), tupGridd(x[2]) )
    for i in 3:length(x)
        push!(expr.args, tupGridd(x[i]) )
    end
    expr
end

function inds(i::I, j::I, m::NTuple{N,I}, mcourse::NTuple{N,I}) where {N,I<:Integer}
    distbase = mcourse[i]
    distcurrent =  j-1 + distbase
    distcurrent, cld(hermite_weights[distcurrent],2) + m[i] - cld(length(hermite_weights[distbase]),2)
end

function weight(offstep::NTuple{N}, mcp1::NTuple{N}, mcourse::NTuple{N}, mfine::NTuple{N}, ::Type{T} = Float64) where {N,T}
    out = one(T)
    for k in 1:N
        i_k = offstep[k]
        mcp1_k = mcp1[k]
        mf_k = mfine[k]
        if i_k == 0
            out *= weighted_gk_weights[mcp1_k][mcp1_k][mf_k]
        else
            out *= weighted_gk_weights[i_k+mcp1_k][mcp1_k][mf_k] -  weighted_gk_weights[i_k+mcourse[k]][mcp1_k][mf_k]
        end
    end
    out
end
@generated function calc_weights(l_remaining::I, mcourse::NTuple{N,I}, mfine::NTuple{N,I}, ::Type{T} = Float64) where {N,I<:Integer,T}
    quote
        j_0 = l_remaining
        s_0 = 0
        out = zero($T)
        mcp1 = @ntuple $N i -> 1 + mcourse[i]
        @nloops $N i p -> begin
            0:j_{$N-p}
        end p -> begin
            s_{$N-p+1} = s_{$N-p} + i_p
            j_{$N-p+1} = l_remaining - s_{$N-p+1}
        end begin
            out += weight( (@ntuple $N k -> i_k), mcp1, mcourse, mfine, T )
        end
        out
    end
end

@generated function calc_weights2(l_remaining::I, mcourse::NTuple{N,I}, mfine::NTuple{N,I}, ::Type{T} = Float64) where {N,I<:Integer,T}
    quote
        j_0 = l_remaining
        s_0 = 0
        out = Vector{$T}(undef, 0)
        mcp1 = @ntuple $N i -> 1 + mcourse[i]
        @nloops $N i p -> begin
            0:j_{$N-p}
        end p -> begin
            s_{$N-p+1} = s_{$N-p} + i_p
            j_{$N-p+1} = l_remaining - s_{$N-p+1}
        end begin
            push!(out, weight( (@ntuple $N k -> i_k), mcp1, mcourse, mfine, T ))
        end
        out
    end
end


text:
using DeterminantalPointProcesses
using Test
using Random, LinearAlgebra, IterTools
import Combinatorics: combinations

rng = MersenneTwister(42)

n = 5
k = 2
A = rand(rng, n, n)
L = Symmetric(A * A')
dpp = DPP(L)

@testset "Ensure correct pmf and logpmf computation" begin
    @testset "For DPP" begin
        # compute the true distribution
        true_pmf = Float64[]
        true_logpmf = Float64[]
        for z in subsets(1:n)
            push!(true_pmf, pmf(dpp, z))
            push!(true_logpmf, logpmf(dpp, z))
        end
        @test sum(true_pmf) ≈ 1.0
        @test all(true_pmf .<= 1.0)
        @test all(true_logpmf .<= 0.0)
    end

    @testset "For k-DPP" begin
        # compute the true distribution
        true_pmf = Float64[]
        true_logpmf = Float64[]
        for z in combinations(1:n, k)
            push!(true_pmf, pmf(dpp, z, k))
            push!(true_logpmf, logpmf(dpp, z, k))
        end
        @test sum(true_pmf) ≈ 1.0
        @test all(true_pmf .<= 1.0)
        @test all(true_logpmf .<= 0.0)
    end
end

@testset "Ensure correct sampling from DPP" begin
    # compute the true distribution
    all_subsets = []
    true_pmf = Float64[]
    for (i, z) in enumerate(subsets(1:n))
        push!(true_pmf, pmf(dpp, z))
        push!(all_subsets, (z, i))
    end
    global subset_to_idx = Dict(all_subsets)

    @testset "Exact sampling" begin
        nb_samples = 1000
        samples = rand(dpp, nb_samples)

        # compute the empirical distribution
        empirical_pmf = zeros(Float64, length(true_pmf))
        for z in samples
            empirical_pmf[subset_to_idx[z]] += 1
        end
        empirical_pmf ./= nb_samples

        # ensure that the empirical pmf is close to the true pmf
        total_variation = maximum(abs.(true_pmf - empirical_pmf))
        @test total_variation ≈ 0.0 atol=1e-1
    end

    @testset "MCMC sampling" begin
        nb_samples = 1000
        samples, state = randmcmc(dpp, nb_samples, return_final_state=true)

        # ensure that L_z_inv makes sense (i.e., noise did not accumulate)
        z, L_z_inv = state
        @test sum(L_z_inv[z, z] * dpp.L[z, z] - I) ≈ 0

        # compute the empirical distribution
        empirical_pmf = zeros(Float64, length(true_pmf))
        for z in samples
            empirical_pmf[subset_to_idx[z]] += 1
        end
        empirical_pmf ./= nb_samples

        # ensure that the empirical pmf is close to the true pmf
        total_variation = maximum(abs.(true_pmf - empirical_pmf))
        @test total_variation ≈ 0.0  atol=1e-1
    end
end

@testset "Ensure correct sampling from k-DPP" begin
    # compute the true distribution
    all_k_subsets = []
    true_pmf = Float64[]
    for (i, z) in enumerate(combinations(1:n, k))
        push!(true_pmf, pmf(dpp, z))
        push!(all_k_subsets, (z, i))
    end
    true_pmf ./= sum(true_pmf)
    k_subset_to_idx = Dict(all_k_subsets)

    @testset "Exact sampling" begin
        nb_samples = 10000
        samples = rand(dpp, nb_samples, k)

        # ensure that samples are of proper cardinality
        @test all(map(length, samples) .== k)

        # compute the empirical distribution
        empirical_pmf = zeros(Float64, length(true_pmf))
        for z in samples
            empirical_pmf[k_subset_to_idx[z]] += 1
        end
        empirical_pmf ./= nb_samples

        # ensure that the empirical pmf is close to the true pmf
        total_variation = maximum(abs.(true_pmf - empirical_pmf))
        @test total_variation ≈ 0.0 atol=1e-1
    end

    @testset "MCMC sampling" begin
        nb_samples = 1000
        samples, state = randmcmc(dpp, nb_samples, k, return_final_state=true)

        # ensure that L_z_inv makes sense (i.e., noise did not accumulate)
        z, L_z_inv = state
        @test sum(L_z_inv[z, z] * dpp.L[z, z] - I) ≈ 0 atol = 1e-1

        # ensure that samples are of proper cardinality
        @test all(map(length, samples) .== k)

        # compute the empirical distribution
        empirical_pmf = zeros(Float64, length(true_pmf))
        for z in samples
            empirical_pmf[k_subset_to_idx[z]] += 1
        end
        empirical_pmf ./= nb_samples

        # ensure that the empirical pmf is close to the true pmf
        total_variation = maximum(abs.(true_pmf - empirical_pmf))
        @test_broken total_variation ≈ 0.0; atol=1e-1
    end
end


text:
# ---
# title: 334. Increasing Triplet Subsequence
# id: problem334
# author: Indigo
# date: 2021-03-12
# difficulty: Medium
# categories:
# link: <https://leetcode.com/problems/increasing-triplet-subsequence/description/>
# hidden: true
# ---
#
# Given an unsorted array return whether an increasing subsequence of length 3
# exists or not in the array.
#
# Formally the function should:
#
# > Return true if there exists _i, j, k_
# >  such that _arr[i]_ < _arr[j]_ < _arr[k]_ given 0 ≤ _i_ < _j_ < _k_ ≤ _n_ -1
# > else return false.
#
# **Note:** Your algorithm should run in O( _n_ ) time complexity and O( _1_ )
# space complexity.
#
# **Example 1:**
#
#
#
#     Input: [1,2,3,4,5]
#     Output: true
#
#
# **Example 2:**
#
#
#
#     Input: [5,4,3,2,1]
#     Output: false
#
#
#
## @lc code=start
using LeetCode

function increasing_triplet(nums::Vector{Int})
    fst_min = scd_min = nums[1]
    len = length(nums)
    idx = 2
    while idx <= len
        (nums[idx] != fst_min) && break
        idx += 1
    end
    (idx >= len) && return false
    fst_min, scd_min = minmax(fst_min, nums[idx])
    for num in @view(nums[(idx + 1):end])
        (num > scd_min) && return true
        scd_min = num
        fst_min, scd_min = minmax(fst_min, scd_min)
    end
    return false
end
## @lc code=end


text:
## TBD, will be redone together with fixes for #1010

"""
    $SIGNATURES

Return a default factor type between two variables of types T1 and T2.

Notes
- Most likely used with deconvolution between target variables
"""
selectFactorType(Modl::Module, T1::Type{<:InferenceVariable}, T2::Type{<:InferenceVariable}) = getfield(Modl, Symbol(T1, T2))
selectFactorType(T1::Type{<:InferenceVariable}, T2::Type{<:InferenceVariable}) = selectFactorType(typeof(T1()).name.module, T1, T2)
selectFactorType(T1::Type{<:Position1}, T2::Type{<:Position1}) = LinearRelative{1}
selectFactorType(T1::Type{<:Position{N}}, T2::Type{<:Position{N}}) where N = LinearRelative{N}
selectFactorType(T1::InferenceVariable, T2::InferenceVariable) = selectFactorType(typeof(T1), typeof(T2))
selectFactorType(dfg::AbstractDFG, s1::Symbol, s2::Symbol) = selectFactorType( getVariableType(dfg, s1), getVariableType(dfg, s2) )

#


text:
# Generate completions.json
using LaTeX_Entities
const LE = LaTeX_Entities

open("completions.json", "w") do io
    println(io, "{")
    def = LE.default
    for nam in def.nam
        println(io, "  \", word, ""\": \"", LE.lookupname(def, nam), ""\",")
    end
    skip(io, -2)
    println(io)
    println(io, "}")
end


text:
"""
joptimise.jl

Wrapper to ipopt and snopt in julia
"""
module joptimise

using Ipopt
using FiniteDiff
using ForwardDiff
using ReverseDiff
using SparseArrays
#using SparseDiffTools
#using Zygote
#using DiffResults
#using Requires

# optimizers
include("minimize.jl")
include("cache.jl")
include("ipopt_wrap.jl")
include("snopt_wrap.jl")
include("snopt.jl")
include("example.jl")
include("initial_guess.jl")

# main call functions
export minimize
export snopta

# derivatives
export ForwardFD
export CentralFD
export ForwardAD
export ReverseAD
#export ComplexStep

# sparsity
export DensePattern
export SparsePattern

# initial guess generator
export random_initial_guess

# examples
export joptimise_rosenbrock

# hangling output files
export process_ipopt_out

end

max_stars_repo_name: Yuricst/joptimise

max_issues_repo_name: Yuricst/joptimise

max_forks_repo_name: Yuricst/joptimise


text:
# Usage: runmeta.jl [--nochecktimemem] SOLVERNAME TIMELIMIT MEMORYLIMIT DATAFOLDER INSTANCESET

# Output goes into directory "output". You must create this directory before running the script.

checktimemem = true
if ARGS[1] == "--nochecktimemem"
    checktimemem = false
    shift!(ARGS)
end

solvername = ARGS[1]
tlim = parse(Float64, ARGS[2])
mlim = parse(Int, ARGS[3])
datafolder = ARGS[4]
instfile = ARGS[5]

# Print info and all instances in the set to a META file for the solver
fdmeta = open("output/META.$solvername.$(split(basename(instfile),'.')[1]).txt", "w")

println(fdmeta, "#PKG STATUS#")
Pkg.status(fdmeta)

println(fdmeta, "#SOLVER# $solvername")
println(fdmeta, "#TIMELIMIT# $tlim")
println(fdmeta, "#MEMLIMIT# $mlim")

instancelist = readdlm(instfile)
println(fdmeta, "#INSTANCES#")
for instancename in instancelist
    println(fdmeta, instancename)
end
println(fdmeta)
flush(fdmeta)

# Run each instance one by one
# This only works on Linux because we check the memory use with Linux commands
for instancename in instancelist
    println(fdmeta, "\nstarting instance $instancename...")

    filename = "output/$solvername.$instancename.txt"

    # Try to start a process to run the current instance on
    # If this fails, it won't affect running future instances
    try
        process = spawn(pipeline(`$(Base.JULIA_HOME)/julia scripts/run.jl $solvername $tlim $datafolder $(instancename).cbf.gz`, stdout=filename, stderr=filename, append=true))

        t = time()

        if checktimemem
            sleep(30.0)

            pid = parse(Int, chomp(readline(open("mypid", "r"))))

            while process_running(process)
                if (time() - t) > (tlim + 60*5.0)
                    # Kill if time limit exceeded (some solvers don't respect time limits)
                    kill(process)
                    sleep(1.0)
                    println(fdmeta, "killed by time limit")
                    open(filename, "a") do fd
                        println(fd, "#STATUS# KilledTime")
                    end
                else
                    # Try to kill if memory limit exceeded (some solvers use too much memory and fail)
                    # If this try fails, process has already stopped
                    try
                        memuse = parse(Int, split(readstring(pipeline(`cat /proc/$pid/status`,`grep RSS`)))[2])
                        if memuse > mlim
                            kill(process)
                            sleep(1.0)
                            println(fdmeta, "killed by memory limit")
                            open(filename, "a") do fd
                                println(fd, "#STATUS# KilledMemory")
                            end
                        end
                    end
                end
                sleep(1.0)
            end
        else
            wait(process)
        end

        println(fdmeta, "...took $(time() - t) seconds")
    catch e
        println(fdmeta, "...process error: $e")
    end

    flush(fdmeta)
end

close(fdmeta)

max_stars_repo_name: chriscoey/PajaritoSupplement

max_issues_repo_name: chriscoey/PajaritoSupplement

max_forks_repo_name: chriscoey/PajaritoSupplement


text:
using MendelIHT
using SnpArrays
using DataFrames
using Distributions
using BenchmarkTools
using Random
using LinearAlgebra
using StatsFuns: logistic

function _benchmark_normal_response(
    n :: Int64,  # number of cases
    p :: Int64,  # number of predictors (SNPs)
    k :: Int64,  # number of true predictors per group
    debias :: Bool # whether to debias
)
	Random.seed!(1111)

	#construct snpmatrix, covariate files, and true model b
	x, maf = simulate_random_snparray(n, p)
	xbm = SnpBitMatrix{Float64}(x, model=ADDITIVE_MODEL, center=true, scale=true);
	z = ones(n, 1) # non-genetic covariates, just the intercept
	true_b = zeros(p)
	true_b[1:k] = randn(k)
	shuffle!(true_b)
	correct_position = findall(x -> x != 0, true_b)
	noise = rand(Normal(0, 0.1), n) # noise vectors from N(0, s)

	#simulate phenotypes (e.g. vector y) via: y = Xb + noise
	y = xbm * true_b + noise

	#benchmark the result and return
    b = @benchmarkable L0_normal_reg($x, $z, $y, 1, $k, debias=$debias) seconds=85000 samples=10

    #should also save the iteration number for this particular SnpBitMatrix
    iter = L0_normal_reg(x, z, y, 1, k).iter

    return run(b), iter
end

function _benchmark_logistic_response(
    n :: Int64,        # number of cases
    p :: Int64,        # number of predictors (SNPs)
    k :: Int64,        # number of true predictors per group
    debias :: Bool
)
	Random.seed!(1111)

	#construct snpmatrix, covariate files, and true model b
	x, maf = simulate_random_snparray(n, p)
	xbm = SnpBitMatrix{Float64}(x, model=ADDITIVE_MODEL, center=true, scale=true);
	z = ones(n, 1) # non-genetic covariates, just the intercept
	true_b = zeros(p)
	true_b[1:k] = randn(k)
	shuffle!(true_b)
	correct_position = findall(x -> x != 0, true_b)

	#simulate bernoulli data
	y_temp = xbm * true_b
	prob = logistic.(y_temp) #inverse logit link
	y = [rand(Bernoulli(x)) for x in prob]
	y = Float64.(y)

	#benchmark the result and return
    b = @benchmarkable L0_logistic_reg($x, $z, $y, 1, $k, glm = "logistic", debias=$debias) seconds=85000 samples=10

    #should also save the iteration number for this particular SnpBitMatrix
    iter = L0_logistic_reg(x, z, y, 1, k, glm = "logistic").iter

    return run(b), iter
end

function _benchmark_poisson_response(
    n :: Int64,        # number of cases
    p :: Int64,        # number of predictors (SNPs)
    k :: Int64,        # number of true predictors per group
    debias :: Bool
)
	Random.seed!(1111)

	#construct snpmatrix, covariate files, and true model b
	x, maf = simulate_random_snparray(n, p)
	xbm = SnpBitMatrix{Float64}(x, model=ADDITIVE_MODEL, center=true, scale=true);
	z = ones(n, 1) # non-genetic covariates, just the intercept
	true_b = zeros(p)
	true_b[1:k] = rand(Normal(0, 0.4), k)
	shuffle!(true_b)
	correct_position = findall(x -> x != 0, true_b)

	# Simulate poisson data
	y_temp = xbm * true_b
	λ = exp.(y_temp) #inverse log link
	y = [rand(Poisson(x)) for x in λ]
	y = Float64.(y)

	#benchmark the result and return
    b = @benchmarkable L0_poisson_reg($x, $z, $y, 1, $k, glm = "poisson", debias=$debias, convg=false, show_info=false, scale=false, init=false) seconds=85000 samples=10

    #should also save the iteration number for this particular SnpBitMatrix
    iter = L0_poisson_reg(x, z, y, 1, k, glm = "poisson", debias=debias, convg=false, show_info=false, scale=false, init=false).iter

    return run(b), iter
end

# arguments passed from command line
n = parse(Int64, ARGS[1])
p = 1000000
k = 10
debias = false
response = "logistic"

#do benchmarking
if response == "normal"
	b, iter = _benchmark_normal_response(n, p, k, debias)
elseif response == "logistic"
	b, iter = _benchmark_logistic_response(n, p, k, debias)
elseif response == "poisson"
	b, iter = _benchmark_poisson_response(n, p, k, debias)
else
	error("shouldn't have reached here")
end

#write result to corresponding file
if debias
	dir = response * "_results/"
else
	dir = response * "_results_nodebias/"
end
file = string(n) * "_by_" * string(p)
open(dir * file, "w") do f
	write(f, "time (seconds), memory (MB), iteration, number of samples\n")
	write(f, string(median(b.times)/1e9) * ", " * string(b.memory/1e6) * ", " * string(iter) * ", " * string(b.params.samples))
end


text:
module Orekit

import Dates
using Pkg.Artifacts

using JavaCall
using Reexport

function init()
    JavaCall.addClassPath(joinpath(artifact"jars", "orekit-artifacts-10.2", "*.jar"))
    JavaCall.init()
end

include(joinpath(@__DIR__, "..", "gen", "OrekitWrapper", "OrekitWrapper.jl"))
include(joinpath(@__DIR__, "..", "gen", "HipparchusWrapper", "HipparchusWrapper.jl"))

include("Time.jl")

@reexport using .Time

end # module


text:
module BasisFunctions

# This file lists dependencies, imports, exports and includes.

## Dependencies

using StaticArrays, BlockArrays, SparseArrays, FillArrays
using ToeplitzMatrices, LinearAlgebra, GenericLinearAlgebra
using FFTW
using DomainSets, DomainIntegrals
using CompositeTypes, CompositeTypes.Display

using QuadGK, Base.Cartesian
using RecipesBase

using Reexport

## Some specific functions we merely use

using Base: IteratorSize
using DSP: conv
using IterativeSolvers: lsqr, lsmr
using SpecialFunctions: gamma
using MacroTools: @forward

## Imports

import Base:
    +, *, /, ==, |, &, -, \, ^,
    <, <=, >, >=,
    ≈,
    ∘, ∘

import Base:
    promote, promote_rule, convert, promote_eltype, widen, convert,
    # array methods
    length, size, eachindex, iterate, firstindex, lastindex, range, collect,
    first, last, copyto!, tail,
    transpose, inv, hcat, vcat, hvcat,
    getindex, setindex!, eltype, @propagate_inbounds,
    IndexStyle, axes, axes1,
    broadcast, similar,
    checkbounds, checkbounds_indices, checkindex,
    zeros, ones, one, zero, fill!, rand,
    # math functions
    cos, sin, exp, log, sqrt,
    # numbers
    isreal, iseven, isodd, real, complex, conj, diff,
    # io
    show, string

import Base.Broadcast: broadcasted, DefaultArrayStyle, broadcast_shape

import LinearAlgebra:
    norm, pinv, normalize, cross, ×, dot, adjoint, mul!, rank,
    diag, isdiag, eigvals, issymmetric, svdvals
import SparseArrays: sparse
@deprecate sparse_matrix sparse

import BlockArrays.BlockVector
export BlockVector

import CompositeTypes:
    iscomposite, component, components, ncomponents

import DomainSets:
    domaintype, codomaintype, dimension,
    indomain, approx_indomain,
    # intervals
    leftendpoint, rightendpoint, endpoints,
    # maps
    matrix, vector,
    forward_map, inverse_map,
    applymap, jacobian,
    ScalarAffineMap,
    # composite types
    factors, factor, nfactors,
    # products
    ×,
    # utils
    prectype, numtype

import DomainIntegrals:
    integral, integrate,
    support,
    weightfun, weightfunction,
    unsafe_weightfun, unsafe_weightfunction,
    weight, unsafe_weight,
    points, weights,
    iscontinuous, isdiscrete,
    isnormalized, isuniform,
    jacobi_α, jacobi_β, laguerre_α
using DomainIntegrals: ProductWeight

export .., numtype, integral

@reexport using GridArrays
import GridArrays: subindices, resize, name,
    apply_map, mapping, covering,
    →, rescale

using GridArrays: SubGrid, MaskedGrid, IndexSubGrid

## Exports

# Re-exports
export component, components, ncomponents, iscomposite,
    factors, factor, nfactors,
    ChebyshevNodes, ChebyshevGrid, ChebyshevPoints, ChebyshevExtremae,
    Point,
    leftendpoint, rightendpoint, range,
    ×,
    points, weights, discrete_weight,
    support,
    Measure, Weight, DiscreteWeight,
    dimension

# from bases/dictionary/indexing.jl
export LinearIndex, NativeIndex,
    DefaultNativeIndex, DefaultIndexList,
    value

# from maps/partition.jl
export PiecewiseInterval, Partition,
    partition,
    split_interval

# from src/util/products.jl
export tensorproduct, ⊗
export ishomogeneous, basetype

# from GridArrays
export ProductGrid
export SubGrid, IndexSubGrid, subindices, supergrid, issubindex,
    similar_subgrid
export MappedGrid, map_grid, apply_map

# from spaces/measure.jl
export innerproduct,
    FourierWeight, ChebyshevTWeight, ChebyshevWeight, ChebyshevUWeight,
    LegendreWeight, JacobiWeight, OPSNodesMeasure, discretemeasure,
    MappedWeight, ProductWeight,
    isnormalized,
    mappedmeasure, productmeasure, submeasure, weight, lebesguemeasure,
    supermeasure, applymeasure

# from spaces/spaces.jl
export GenericFunctionSpace, space, MeasureSpace, FourierSpace, ChebyshevTSpace,
    ChebyshevSpace, L2

# from bases/dictionary/dictionary.jl
export Dictionary, Dictionary1d, Dictionary2d, Dictionary3d,
    interpolation_grid, left, right, domain, codomain,
    measure, hasmeasure,
    eval_expansion, eval_element, eval_element_derivative, eval_gradient,
    name,
    resize,
    ordering,
    native_index, linear_index, multilinear_index, native_size, linear_size, native_coefficients,
    isbasis, isframe, isorthogonal, isbiorthogonal, isorthonormal,
    in_support,
    dimensions, approx_length, extensionsize,
    hastransform, hasextension, hasderivative, hasantiderivative, hasinterpolationgrid,
    linearize_coefficients, delinearize_coefficients, linearize_coefficients!,
    delinearize_coefficients!,
    moment, norm

# from bases/dictionary/span.jl
export Span

# from bases/modifiers/subdicts.jl
export Subdictionary, DenseSubdict, SparseSubdict,
    subdict, superindices

# from bases/modifiers/tensorproduct_dict.jl
export TensorProductDict, ProductIndex,
    recursive_native_index

# from bases/modifiers/derived_dict.jl
export DerivedDict, superdict

# from bases/modifiers/paramdict.jl
export param_dict, ParamDict, image

#from bases/dictionary/expansions.jl
export Expansion, TensorProductExpansion,
    expansion, coefficients, dictionary, roots,
    random_expansion, differentiate, antidifferentiate,
    ∂x, ∂y, ∂z, ∫∂x, ∫∂y, ∫∂z, ∫, iscompatible

# from operator/operator.jl
export AbstractOperator, DictionaryOperator,
    src, dest, src_space, dest_space,
    apply!, apply, apply_multiple, apply_inplace!,
    matrix, diag, isdiag, isinplace

# from operator/composite_operator.jl
export CompositeOperator, compose

# from operator/special_operators.jl
export IdentityOperator, ScalingOperator, scalar, DiagonalOperator,
    ArrayOperator, FunctionOperator,
    MultiplicationOperator,
    IndexRestriction, IndexExtension,
    HorizontalBandedOperator, VerticalBandedOperator, CirculantOperator, Circulant

# from operator/solvers.jl
export QR_solver, SVD_solver, regularized_SVD_solver, operator, LSQR_solver, LSMR_solver

# from operator/generic_operators.jl
export GenericIdentityOperator

# from computations/transform.jl
export transform, transform_dict, transform_to_grid, transform_from_grid

# from bases/dictionary/gram.jl
export gramelement, gram, dual, mixedgram, gramdual

# from computations/evaluation.jl
export evaluation_matrix

# from computations/approximation.jl
export approximation, default_approximation, approximate,
    discrete_approximation, continuous_approximation, project,
    interpolation, default_interpolation, interpolation_matrix

# from operator/tensorproductoperator.jl
export TensorProductOperator

# from operator/block_operator.jl
export BlockOperator, block_row_operator, block_column_operator, composite_size

# from bases/modifiers/weighted_dict.jl
export WeightedDict, WeightedDict1d, WeightedDict2d, WeightedDict3d,
    weightfunction, weightfun_scaling_operator

# from bases/modifiers/composite_dict.jl
export tail

# from bases/modifiers/multiple_dict.jl
export MultiDict, multidict, ⊕

# from bases/modifiers/piecewise_dict.jl
export PiecewiseDict, dictionaries

# from bases/modifiers/vector_dict.jl
export VectorvaluedDict

# from bases/modifiers/operated_dict.jl
export OperatedDict

# from bases/dictionary/discrete_sets.jl
export DiscreteDictionary, DiscreteVectorDictionary, DiscreteArrayDictionary,
    isdiscrete

# from bases/dictionary/gridbasis.jl
export GridBasis,
    grid, gridbasis, weights

# from sampling/sampling_operator.jl
export GridSampling, ProjectionSampling, AnalysisOperator, SynthesisOperator,
    sample

# from sampling/quadrature.jl
export clenshaw_curtis, fejer_first_rule, fejer_second_rule,
    trapezoidal_rule, rectangular_rule

# from sampling/normalization.jl
export sampling_normalization

# from bases/fourier/fourier.jl
export Fourier,
    FastFourierTransform, InverseFastFourierTransform,
    FastFourierTransformFFTW, InverseFastFourierTransformFFTW,
    frequency2idx, idx2frequency

# from bases/fourier/(co)sineseries.jl
export CosineSeries, SineSeries

# from bases/poly/chebyshev.jl
export ChebyshevT, ChebyshevU,
    FastChebyshevTransform, InverseFastChebyshevTransform,
    FastChebyshevTransformFFTW, InverseFastChebyshevTransformFFTW

# from util/recipes.jl
export plotgrid, postprocess

# from bases/poly/orthopoly.jl and friends
export Legendre, Jacobi, Laguerre, Hermite,
    Monomials, RationalBasis, GenericOPS,
    recurrence_eval, recurrence_eval_derivative, monic_recurrence_eval,
    monic_recurrence_coefficients,
    symmetric_jacobi_matrix, roots, gauss_rule, sorted_gauss_rule, first_moment,
    leading_order_coefficient

# from specialOPS.jl
export HalfRangeChebyshevIkind, HalfRangeChebyshevIIkind, WaveOPS,
    diagonal, isdiagonal

## Includes

include("util/common.jl")
include("util/arrays/specialarrays.jl")
include("util/arrays/outerproductarrays.jl")

include("maps/partition.jl")

include("spaces/measure.jl")
include("spaces/discretemeasure.jl")
include("spaces/spaces.jl")
include("sampling/quadweights.jl")

include("bases/dictionary/indexing.jl")
include("bases/dictionary/dictionary.jl")
include("bases/dictionary/promotion.jl")
include("bases/dictionary/span.jl")
include("bases/dictionary/gram.jl")
include("bases/dictionary/duality.jl")
include("bases/dictionary/discrete_sets.jl")
include("bases/dictionary/gridbasis.jl")
include("bases/dictionary/basisfunction.jl")

include("operator/operator.jl")
include("operator/composite_operator.jl")

include("bases/modifiers/derived_dict.jl")
include("bases/modifiers/complexified_dict.jl")
include("bases/modifiers/tensorproduct_dict.jl")
include("bases/modifiers/mapped_dict.jl")
include("bases/modifiers/paramdict.jl")

include("operator/arrayoperator.jl")
include("operator/solvers.jl")
include("operator/special_operators.jl")
include("operator/tensorproductoperator.jl")
include("operator/block_operator.jl")
include("operator/arithmetics.jl")
include("operator/simplify.jl")
include("operator/orthogonality.jl")

include("operator/generic_operators.jl")

include("bases/dictionary/expansions.jl")

include("util/products.jl")

include("computations/generic_operators.jl")
include("computations/conversion.jl")

################################################################
# Generic dictionaries
################################################################

include("bases/modifiers/subdicts.jl")
include("bases/modifiers/composite_dict.jl")
include("bases/modifiers/multiple_dict.jl")
include("bases/modifiers/piecewise_dict.jl")
include("bases/modifiers/operated_dict.jl")
include("bases/modifiers/weighted_dict.jl")
include("bases/modifiers/vector_dict.jl")
include("bases/modifiers/logic.jl")

include("bases/dictionary/custom_dictionary.jl")

################################################################
# Sampling
################################################################

include("sampling/synthesis.jl")
include("sampling/sampling_operator.jl")
include("sampling/quadrature.jl")
include("sampling/normalization.jl")
include("sampling/interaction.jl")

################################################################
# Trigonometric sets: Fourier, cosines and sines
################################################################

include("bases/fourier/fouriertransforms.jl")
include("bases/fourier/fourier.jl")
include("bases/fourier/cosineseries.jl")
include("bases/fourier/sineseries.jl")

################################################################
# Polynomials: monomials and (classical) orthogonal polynomials
################################################################

include("bases/poly/polynomials.jl")
include("bases/poly/monomials.jl")
include("bases/poly/quadrature.jl")
include("bases/poly/orthopoly.jl")
include("bases/poly/chebyshev/chebyshev.jl")
include("bases/poly/legendre.jl")
include("bases/poly/jacobi.jl")
include("bases/poly/laguerre.jl")
include("bases/poly/hermite.jl")
include("bases/poly/generic_op.jl")
include("bases/poly/specialOPS.jl")
include("bases/poly/rational.jl")

include("util/display/recipes.jl")
include("util/display/pgfplots.jl")

include("test/Test.jl")

include("examples/pwconstants.jl")
end # module


text:
module ModJPEG

using JpegTurbo_jll

libjpeg_wrap_dir = joinpath(@__DIR__, "..", "..", "gen", "libturbojpeg")

using CEnum
include(joinpath(libjpeg_wrap_dir, "ctypes.jl"))
export Ctm, Ctime_t, Cclock_t
include(joinpath(libjpeg_wrap_dir, "libturbojpeg_common.jl"))
include(joinpath(libjpeg_wrap_dir, "libturbojpeg_api.jl"))

end # module


text:
mutable struct NoThrowTestSet <: Test.AbstractTestSet
    results::Vector
    NoThrowTestSet(desc) = new([])
end
Test.record(ts::NoThrowTestSet, t::Test.Result) = (push!(ts.results, t); t)
Test.finish(ts::NoThrowTestSet) = ts.results

max_stars_repo_name: vanillajonathan/julia

max_issues_repo_name: vanillajonathan/julia

max_forks_repo_name: vanillajonathan/julia


text:
export Scene
export scn
export scene_view

# this is the scene graph, ladies and gentlemen,
# which we can traverse and mutate however we want
# during iteration, and initialize however we want
# and destroy however we want...sorry, it took me
# a long time to come up with this design, and i'm
# a little bit psyched about it. :)
scene_view() = ecs.df[(ecs.df.type .<: [Renderable]) .& (ecs.df.hidden .== [false]), :]

mutable struct Scene <: ECSIterator end

const scn = Scene() # needs awake! and shutdown! for initialization/deinitialization

Base.length(s::Scene) = size(scene_view())[1]

awake!(s::Scene) = true
shutdown!(s::Scene) = false

listenFor(scn, TICK)

function handleMessage(s::Scene, m::TICK)
  # sort just once per tick rather than every time we iterate
  @debug "Scene tick"
  try
    sort!(ecs.df, [order(POSITION, rev=true, by=(pos)->pos.z)])
  catch
    handleException()
  end
end

function Base.iterate(s::Scene, state::ECSIteratorState=ECSIteratorState())
  # does reverse-z order for now, only
  # suitable for simple 2d drawing
  if state.index > length(s) return nothing end
  ent = scene_view()[!, ENT][state.index]
  state.index += 1
  return (ent, state)
end


text:
using Test
using LogicCircuits
using DataFrames: DataFrame

@testset "Structured logic nodes" begin

    vtree = PlainVtree(10, :balanced)
    f = fully_factorized_circuit(StructLogicCircuit, vtree)
    @test num_nodes(f) == 20+10+9*2+1
    @test num_edges(f) == 20+18+9+1
    @test length(and_nodes(f)) == 9
    @test length(or_nodes(f)) == 10+9+1

    @test respects_vtree(f)
    @test respects_vtree(f, PlainVtree(10, :balanced))
    @test !respects_vtree(f, PlainVtree(5, :balanced))
    @test !respects_vtree(f, PlainVtree(10, :rightlinear))
    @test !respects_vtree(f, PlainVtree(10, :leftlinear))

    @test variable(left_most_descendent(f)) == Var(1)
    @test variable(right_most_descendent(f)) == Var(10)
    @test ispositive(left_most_descendent(f))
    @test isnegative(right_most_descendent(f))

    @test istrue(compile(StructLogicCircuit,true))
    @test istrue(StructLogicCircuit(true))
    @test istrue(StructLogicCircuit(true) & StructLogicCircuit(true))
    @test isfalse(StructLogicCircuit(true) & StructLogicCircuit(false))
    @test isfalse(compile(StructLogicCircuit,false))
    @test isfalse(StructLogicCircuit(false))
    @test istrue(StructLogicCircuit(false) | StructLogicCircuit(true))
    @test isfalse(StructLogicCircuit(false) | StructLogicCircuit(false))
    @test !istrue(compile(StructLogicCircuit,false))
    @test !isfalse(compile(StructLogicCircuit,true))
    @test !istrue(compile(StructLogicCircuit,PlainVtree(Var(2)),Lit(2)))
    @test !isfalse(compile(StructLogicCircuit,PlainVtree(Var(2)),Lit(2)))
    @test !istrue(f)
    @test !isfalse(f)

    @test literal(vtree(Lit(-5))) == Lit(-5)
    @test literal((PlainStructLogicCircuit,vtree)(Lit(-5))) == Lit(-5)
    @test constant((PlainStructLogicCircuit,vtree)(false)) == false

    @test_throws Exception conjoin(StructLogicCircuit[])
    @test_throws Exception disjoin(StructLogicCircuit[])

    lit_map = canonical_literals(f)
    @test literal(lit_map[Lit(1)]) == Lit(1)
    @test literal(lit_map[Lit(-5)]) == Lit(-5)
    @test length(lit_map) == 20

    @test canonical_constants(f) == (nothing, nothing)

    @test isdecomposable(f)

    @test variables(f) == BitSet(1:10)
    @test variables_by_node(f)[f] == BitSet(1:10)

    @test num_variables(f) == 10
    @test issmooth(f)

    @test isone(sat_prob(f))
    @test model_count(f) == BigInt(2)^10

    @test f(DataFrame(BitArray([1 0 1 0 1 0 1 0 1 0;
                       1 1 1 1 1 1 1 1 1 1;
                       0 0 0 0 0 0 0 0 0 0;
                       0 1 1 0 1 0 0 1 0 1]))) == BitVector([1,1,1,1])

    plainf = PlainLogicCircuit(f)
    foreach(plainf) do n
        @test n isa PlainLogicCircuit
    end
    @test plainf !== f
    @test num_edges(plainf) == num_edges(f)
    @test num_nodes(plainf) == num_nodes(f)
    @test length(and_nodes(plainf)) == 9
    @test length(or_nodes(plainf)) == 10+9+1
    @test model_count(plainf) == BigInt(2)^10
    @test isempty(intersect(linearize(f),linearize(plainf)))

    ref = StructLogicCircuit(vtree,plainf)
    foreach(ref) do n
        @test n isa PlainStructLogicCircuit
    end
    @test plainf !== ref
    @test f !== ref
    @test f.vtree === ref.vtree
    @test num_edges(ref) == num_edges(f)
    @test num_nodes(ref) == num_nodes(f)
    @test length(and_nodes(ref)) == 9
    @test length(or_nodes(ref)) == 10+9+1
    @test model_count(ref) == BigInt(2)^10
    @test isempty(intersect(linearize(f),linearize(ref)))

    ref = StructLogicCircuit(vtree,f)
    foreach(ref) do n
        @test n isa PlainStructLogicCircuit
    end
    @test plainf !== ref
    @test f !== ref
    @test f.vtree === ref.vtree
    @test num_edges(ref) == num_edges(f)
    @test num_nodes(ref) == num_nodes(f)
    @test length(and_nodes(ref)) == 9
    @test length(or_nodes(ref)) == 10+9+1
    @test model_count(ref) == BigInt(2)^10
    @test isempty(intersect(linearize(f),linearize(ref)))

    mgr = SddMgr(7, :balanced)
    v = Dict([(i => compile(mgr, Lit(i))) for i=1:7])
    c = (v[1] | !v[2] | v[3]) &
        (v[2] | !v[7] | v[6]) &
        (v[3] | !v[4] | v[5]) &
        (v[1] | !v[4] | v[6])

    @test_throws Exception StructLogicCircuit(c)
    c2 = StructLogicCircuit(mgr, c)

    foreach(c2) do n
      @test n isa PlainStructLogicCircuit
    end
    @test num_edges(c2) == 147
    @test num_variables(c2) == 7

    c2 = propagate_constants(c2; remove_unary=true)
    foreach(c2) do n
      @test n isa PlainStructLogicCircuit
    end
    @test num_edges(c2) == 69
    @test num_variables(c2) == 7

end


text:
export Resource

Base.@kwdef struct Resource
    attributes::Attributes = Attributes()
    schema_url::String = ""
end