text:
module DataAugmentation

using ColorBlendModes
using CoordinateTransformations
using Distributions: Sampleable, Uniform, Categorical
using IndirectArrays: IndirectArray
using ImageDraw
using Images
using Images: Colorant, permuteddimsview
using ImageTransformations
using ImageTransformations: center, _center, box_extrapolation, warp!
using Interpolations
using MosaicViews: mosaicview
using OffsetArrays: OffsetArray
using LinearAlgebra: I
using Parameters
using Random
using Rotations
using Setfield
using StaticArrays
using Statistics
using Test: @test, @test_nowarn

include("./base.jl")
include("./wrapper.jl")
include("./buffered.jl")
include("./sequence.jl")
include("./items/arrayitem.jl")
include("./projective/base.jl")
include("./items/image.jl")
include("./items/table.jl")
include("./items/keypoints.jl")
include("./items/mask.jl")
include("./projective/compose.jl")
include("./projective/crop.jl")
include("./projective/affine.jl")
include("./projective/warp.jl")
include("./oneof.jl")
include("./preprocessing.jl")
include("./rowtransforms.jl")
include("./colortransforms.jl")
include("testing.jl")
include("./visualization.jl")

export Item,
    Transform,
    ArrayItem,
    MapElem,
    Identity,
    Sequence,
    Project,
    Image,
    TabularItem,
    Keypoints,
    Polygon,
    ToEltype,
    ImageToTensor,
    Normalize,
    NormalizeIntensity,
    MaskMulti,
    MaskBinary,
    BoundingBox,
    ScaleKeepAspect,
    ScaleRatio,
    itemdata,
    Crop,
    CenterCrop,
    RandomCrop,
    ScaleFixed,
    Rotate,
    RandomResizeCrop,
    CenterResizeCrop,
    Buffered,
    BufferedThreadsafe,
    OneHot,
    Zoom,
    OneOf,
    Maybe,
    apply,
    Reflect,
    WarpAffine,
    FlipX,
    FlipY,
    PinOrigin,
    AdjustBrightness,
    AdjustContrast,
    apply!,
    PadDivisible,
    ResizePadDivisible,
    onehot,
    showitems,
    showgrid,
    Bounds,
    getcategorypools

end # module


text:
mutable struct DirectMAJumpAggregation{T,S1,S2,F1,F2} <: AbstractJumpAggregator
    next_jump::T
    end_time::T
    cur_rates::Vector{T}
    sum_rate::T
    aggregator::DirectMA{S1,S2}
    rates::F1
    affects!::F2
    save_positions::Tuple{Bool,Bool}
end

@inline function (p::DirectMAJumpAggregation)(u,t,integrator) # condition
    p.next_jump==t
end

function (p::DirectMAJumpAggregation)(integrator) # affect!
    rng_val = rand() * p.sum_rate
    i       = searchsortedfirst(p.cur_rates, rng_val)
    @inbounds executerx!(integrator.u, p.aggregator.net_stoch[i])
    p.sum_rate,ttnj = time_to_next_jump_ma(integrator.u,integrator.p,integrator.t,p.aggregator,p.cur_rates)
    @fastmath p.next_jump = integrator.t + ttnj
    if p.next_jump < p.end_time
        add_tstop!(integrator,p.next_jump)
    end
    nothing
end

function (p::DirectMAJumpAggregation)(dj,u,t,integrator) # initialize
    sum_rate,next_jump = time_to_next_jump_ma(u,integrator.p,t,p.aggregator,p.cur_rates)
    p.sum_rate         = sum_rate
    p.next_jump        = t + next_jump
    if p.next_jump < p.end_time
        add_tstop!(integrator,p.next_jump)
    end
    nothing
end

@fastmath function time_to_next_jump_ma(u,p,t,aggregator::DirectMA,cur_rates)
    sum_rate  = zero(t)
    prev_rate = zero(t)
    new_rate  = zero(t)
    @inbounds for i in 1:length(aggregator.scaled_rates)
        new_rate     = evalrxrate(u, aggregator.scaled_rates[i], aggregator.reactant_stoch[i])
        sum_rate     = sum_rate + new_rate
        cur_rates[i] = new_rate + prev_rate
        prev_rate    = cur_rates[i]
    end

    # @inbounds sum_rate     = evalrxrate(u, aggregator.scaled_rates[1], aggregator.reactant_stoch[1])
    # @inbounds cur_rates[1] = sum_rate
    # @inbounds for i in 2:length(cur_rates)
    #     new_rate     = evalrxrate(u, aggregator.scaled_rates[i], aggregator.reactant_stoch[i])
    #     sum_rate    += new_rate
    #     cur_rates[i] = new_rate + cur_rates[i-1]
    # end

    sum_rate,randexp()/sum_rate
end

@inline function aggregate(aggregator::DirectMA,u,p,t,end_time,constant_jumps,save_positions)

    # handle constant jumps
    if constant_jumps != nothing
        if length(constant_jumps) < TUPLE_TO_FWRAPPER_CUTOFF
            rates,affects! = getRatesAffectsAsTuples(constant_jumps)
        else
            rates,affects! = getRatesAffectsAsFWrappers(u,p,t,constant_jumps)
        end
    else
        rates    = ()
        affects! = ()
    end

    # current jump rates, includes constant jumps and mass action jumps
    cur_rates = Vector{typeof(t)}(length(aggregator.scaled_rates))
    #cur_rates = Vector{typeof(t)}(length(aggregator.scaled_rates) + length(rates))

    # get first jump time and jump
    sum_rate,next_jump = time_to_next_jump_ma(u,p,t,aggregator,cur_rates)

    DirectMAJumpAggregation(next_jump, end_time, cur_rates, sum_rate, aggregator,
                            rates, affects!, save_positions)
end

DiscreteCallback(c::DirectMAJumpAggregation) = DiscreteCallback(c,c,initialize=c,save_positions=c.save_positions)

ext: jl

max_stars_repo_name: isaacsas/DiffEqJumpExtensions

max_issues_repo_name: isaacsas/DiffEqJumpExtensions

max_forks_repo_name: isaacsas/DiffEqJumpExtensions


text:
using LinearAlgebra, FastSolversForWeightedTV, AbstractLinearOperators, Test
include("test_utils.jl")

# Random input
T = Float64
n = (1024, 2048)

# AbstractLinearOperators
fw = x -> x[1:2:end,1:2:end]
function bw(y)
    x = zeros(T,n)
    x[1:2:end,1:2:end] .= y
    return x
end
A = linear_operator(T, n, (512, 1024), fw, bw)

# Misfit
y = randn(T, 512, 1024)
J = leastsquares_misfit(A, y)

# Gradient test
x = randn(T, n...)
test_grad(J, x; step=T(1e-5), rtol=T(1e-6))

max_stars_repo_name: grizzuti/FastSolversForWeightedTV

max_issues_repo_name: grizzuti/FastSolversForWeightedTV

max_forks_repo_name: grizzuti/FastSolversForWeightedTV


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/MortarContact2D.jl/blob/master/LICENSE

const MortarElements2D = Union{Seg2,Seg3}

mutable struct Mortar2D <: BoundaryProblem
    master_elements :: Vector{Element}
end

function Mortar2D()
    return Mortar2D([])
end

function FEMBase.add_elements!(::Problem{Mortar2D}, ::Union{Tuple, Vector})
    error("use `add_slave_elements!` and `add_master_elements!` to add " *
          "elements to the Mortar2D problem.")
end

function FEMBase.add_slave_elements!(problem::Problem{Mortar2D}, elements)
    for element in elements
        push!(problem.elements, element)
    end
end

function FEMBase.add_master_elements!(problem::Problem{Mortar2D}, elements)
    for element in elements
        push!(problem.properties.master_elements, element)
    end
end

function FEMBase.get_slave_elements(problem::Problem{Mortar2D})
    return problem.elements
end

function FEMBase.get_master_elements(problem::Problem{Mortar2D})
    return problem.properties.master_elements
end

function get_slave_dofs(problem::Problem{Mortar2D})
    dofs = Int64[]
    for element in get_slave_elements(problem)
        append!(dofs, get_gdofs(problem, element))
    end
    return sort(unique(dofs))
end

function get_master_dofs(problem::Problem{Mortar2D})
    dofs = Int64[]
    for element in get_master_elements(problem)
        append!(dofs, get_gdofs(problem, element))
    end
    return sort(unique(dofs))
end

function project_from_master_to_slave(slave_element::Element{E}, x2, time;
    tol=1.0e-9, max_iterations=5) where {E<:MortarElements2D}

    x1_ = slave_element("geometry", time)
    n1_ = slave_element("normal", time)
    cross2(a, b) = cross([a; 0.0], [b; 0.0])[3]
    x1(xi1) = interpolate(vec(get_basis(slave_element, [xi1], time)), x1_)
    dx1(xi1) = interpolate(vec(get_dbasis(slave_element, [xi1], time)), x1_)
    n1(xi1) = interpolate(vec(get_basis(slave_element, [xi1], time)), n1_)
    dn1(xi1) = interpolate(vec(get_dbasis(slave_element, [xi1], time)), n1_)
    R(xi1) = cross2(x1(xi1)-x2, n1(xi1))
    dR(xi1) = cross2(dx1(xi1), n1(xi1)) + cross2(x1(xi1)-x2, dn1(xi1))

    xi1 = 0.0
    dxi1 = 0.0
    for i=1:max_iterations
        dxi1 = -R(xi1)/dR(xi1)
        xi1 += dxi1
        if norm(dxi1) < tol
            return xi1
        end
    end

    len = norm(x1_[2] - x1_[1])
    midpnt = mean(x1_)
    dist = norm(midpnt - x2)
    distval = dist/len
    @info("Projection from the master element to the slave failed.")
    @info("Arguments:")
    @info("Time: $time")
    @info("Point to project to the slave element: (x2): $x2")
    @info("Slave element geometry (x1): $x1_")
    @info("Slave element normal direction (n1): $n1_")
    @info("Midpoint of slave element: $midpnt")
    @info("Length of slave element: $len")
    @info("Distance between midpoint of slave element and x2: $dist")
    @info("Distance/Lenght-ratio: $distval")
    @info("Number of iterations: $max_iterations")
    @info("Wanted convergence tolerance: $tol")
    @info("Achieved convergence tolerance: $(norm(dxi1))")
    error("Failed to project point to slave surface in $max_iterations.")
end

function project_from_slave_to_master(master_element::Element{E}, x1, n1, time;
    max_iterations=5, tol=1.0e-9) where {E<:MortarElements2D}
    x2_ = master_element("geometry", time)
    x2(xi2) = interpolate(vec(get_basis(master_element, [xi2], time)), x2_)
    dx2(xi2) = interpolate(vec(get_dbasis(master_element, [xi2], time)), x2_)
    cross2(a, b) = cross([a; 0], [b; 0])[3]
    R(xi2) = cross2(x2(xi2)-x1, n1)
    dR(xi2) = cross2(dx2(xi2), n1)
    xi2 = 0.0
    dxi2 = 0.0
    for i=1:max_iterations
        dxi2 = -R(xi2)/dR(xi2)
        xi2 += dxi2
        if norm(dxi2) < tol
            return xi2
        end
    end
    error("Failed to project point to master surface in $max_iterations iterations.")
end

function calculate_normals(elements::Vector{Element{Seg2}}, time; rotate_normals=false)

    normals = Dict{Int64, Vector{Float64}}()

    for element in elements
        X1, X2 = element("geometry", time)
        t1, t2 = (X2-X1)/norm(X2-X1)
        normal = [-t2, t1]
        for j in get_connectivity(element)
            normals[j] = get(normals, j, zeros(2)) + normal
        end
    end

    s = rotate_normals ? -1.0 : 1.0
    for j in keys(normals)
        normals[j] = s*normals[j]/norm(normals[j])
    end

    return normals
end

function FEMBase.assemble_elements!(problem::Problem{Mortar2D}, assembly::Assembly,
                                    elements::Vector{Element{Seg2}}, time::Float64)

    slave_elements = get_slave_elements(problem)

    props = problem.properties
    field_dim = get_unknown_field_dimension(problem)
    field_name = get_parent_field_name(problem)

    # 1. calculate nodal normals for slave element nodes j ∈ S
    normals = calculate_normals([slave_elements...], time)
    update!(slave_elements, "normal", time => normals)

    # 2. loop all slave elements
    for slave_element in slave_elements

        nsl = length(slave_element)
        X1 = slave_element("geometry", time)
        n1 = slave_element("normal", time)

        # 3. loop all master elements
        for master_element in get_master_elements(problem)

            nm = length(master_element)
            X2 = master_element("geometry", time)

            # 3.1 calculate segmentation
            xi1a = project_from_master_to_slave(slave_element, X2[1], time)
            xi1b = project_from_master_to_slave(slave_element, X2[2], time)
            xi1 = clamp.([xi1a; xi1b], -1.0, 1.0)
            l = 1/2*abs(xi1[2]-xi1[1])
            isapprox(l, 0.0) && continue # no contribution in this master element

            # 3.3. loop integration points of one integration segment and calculate
            # local mortar matrices
            De = zeros(nsl, nsl)
            Me = zeros(nsl, nm)
            fill!(De, 0.0)
            fill!(Me, 0.0)
            for ip in get_integration_points(slave_element, 2)
                detJ = slave_element(ip, time, Val{:detJ})
                w = ip.weight*detJ*l
                xi = ip.coords[1]
                xi_s = dot([1/2*(1-xi); 1/2*(1+xi)], xi1)
                N1 = vec(get_basis(slave_element, xi_s, time))
                Phi = N1
                # project gauss point from slave element to master element in direction n_s
                X_s = interpolate(N1, X1) # coordinate in gauss point
                n_s = interpolate(N1, n1) # normal direction in gauss point
                xi_m = project_from_slave_to_master(master_element, X_s, n_s, time)
                N2 = vec(get_basis(master_element, xi_m, time))
                X_m = interpolate(N2, X2)
                De += w*Phi*N1'
                Me += w*Phi*N2'
            end

            sdofs = get_gdofs(problem, slave_element)
            mdofs = get_gdofs(problem, master_element)

            # add contribution to contact virtual work and constraint matrix
            for i=1:field_dim
                lsdofs = sdofs[i:field_dim:end]
                lmdofs = mdofs[i:field_dim:end]
                add!(problem.assembly.C1, lsdofs, lsdofs, De)
                add!(problem.assembly.C1, lsdofs, lmdofs, -Me)
                add!(problem.assembly.C2, lsdofs, lsdofs, De)
                add!(problem.assembly.C2, lsdofs, lmdofs, -Me)
            end

        end # master elements done

    end # slave elements done, contact virtual work ready

    return nothing

end

function get_mortar_matrix_D(problem::Problem{Mortar2D})
    s = get_slave_dofs(problem)
    C2 = sparse(problem.assembly.C2)
    return sparse(problem.assembly.C2)[s,s]
end

function get_mortar_matrix_M(problem::Problem{Mortar2D})
    m = get_master_dofs(problem)
    s = get_slave_dofs(problem)
    C2 = sparse(problem.assembly.C2)
    return -C2[s,m]
end

function get_mortar_matrix_P(problem::Problem{Mortar2D})
    m = get_master_dofs(problem)
    s = get_slave_dofs(problem)
    C2 = sparse(problem.assembly.C2)
    D_ = C2[s,s]
    M_ = -C2[s,m]
    P = cholesky(1/2*(D_ + D_')) \ M_
    return P
end

""" Eliminate mesh tie constraints from matrices K, M, f. """
function FEMBase.eliminate_boundary_conditions!(problem::Problem{Mortar2D}, K, M, f)

    m = get_master_dofs(problem)
    s = get_slave_dofs(problem)
    P = get_mortar_matrix_P(problem)
    ndim = size(K, 1)
    Id = ones(ndim)
    Id[s] .= 0.0
    Q = sparse(Diagonal(Id))
    Q[m,s] .+= P'
    K[:,:] .= Q*K*Q'
    M[:,:] .= Q*M*Q'
    f[:] .= Q*f

    return true
end


text:
using SamplePkg
using Test

@testset "SamplePkg.jl" begin
    # Write your tests here.
end

max_stars_repo_name: pbudzyns/JuliaSamplePkg

max_issues_repo_name: pbudzyns/JuliaSamplePkg

max_forks_repo_name: pbudzyns/JuliaSamplePkg


text:
using NNlib: logsoftmax, logσ

# Cost functions

mse(ŷ, y) = sum((ŷ .- y).^2)/length(y)

function crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)
  @fix -sum(y .* log.(ŷ) .* weight) / size(y, 2)
end

@deprecate logloss(x, y) crossentropy(x, y)

function logitcrossentropy(logŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)
  return -sum(y .* logsoftmax(logŷ) .* weight) / size(y, 2)
end

"""
    binarycrossentropy(ŷ, y)

Return `-y*log(ŷ) - (1-y)*log(1-ŷ)`.

    julia> binarycrossentropy.(σ.([-1.1491, 0.8619, 0.3127]), [1, 1, 0.])
    3-element Array{Float64,1}:
    1.4244
    0.352317
    0.86167
"""
binarycrossentropy(ŷ, y) = -y*log(ŷ) - (1 - y)*log(1 - ŷ)

"""
    logitbinarycrossentropy(logŷ, y)

`logitbinarycrossentropy(logŷ, y)` is mathematically equivalent to `binarycrossentropy(σ(logŷ), y)`
but it is more numerically stable.

    julia> logitbinarycrossentropy.([-1.1491, 0.8619, 0.3127], [1, 1, 0.])
    3-element Array{Float64,1}:
     1.4244
     0.352317
     0.86167
"""
logitbinarycrossentropy(logŷ, y) = (1 - y)*logŷ - logσ(logŷ)

"""
    normalise(x::AbstractVecOrMat)

Normalise each column of `x` to mean 0 and standard deviation 1.
"""
function normalise(x::AbstractVecOrMat)
  μ′ = mean(x, 1)
  σ′ = std(x, 1, mean = μ′)
  return (x .- μ′) ./ σ′
end


text:
"""
    GDALCreateColorTable(GDALPaletteInterp eInterp) -> GDALColorTableH
Construct a new color table.
"""
function createcolortable(arg1::GDALPaletteInterp)
    checknull(ccall((:GDALCreateColorTable,libgdal),Ptr{GDALColorTableH},(GDALPaletteInterp,),arg1))
end

"""
    GDALDestroyColorTable(GDALColorTableH hTable) -> void
Destroys a color table.
"""
function destroycolortable(arg1::Ptr{GDALColorTableH})
    ccall((:GDALDestroyColorTable,libgdal),Void,(Ptr{GDALColorTableH},),arg1)
end

"""
    GDALCloneColorTable(GDALColorTableH hTable) -> GDALColorTableH
Make a copy of a color table.
"""
function clonecolortable(arg1::Ptr{GDALColorTableH})
    checknull(ccall((:GDALCloneColorTable,libgdal),Ptr{GDALColorTableH},(Ptr{GDALColorTableH},),arg1))
end

"""
    GDALGetPaletteInterpretation(GDALColorTableH hTable) -> GDALPaletteInterp
Fetch palette interpretation.
"""
function getpaletteinterpretation(arg1::Ptr{GDALColorTableH})
    ccall((:GDALGetPaletteInterpretation,libgdal),GDALPaletteInterp,(Ptr{GDALColorTableH},),arg1)
end

"""
    GDALGetColorEntryCount(GDALColorTableH hTable) -> int
Get number of color entries in table.
"""
function getcolorentrycount(arg1::Ptr{GDALColorTableH})
    ccall((:GDALGetColorEntryCount,libgdal),Cint,(Ptr{GDALColorTableH},),arg1)
end

"""
    GDALGetColorEntry(GDALColorTableH hTable,
                      int i) -> const GDALColorEntry *
Fetch a color entry from table.
"""
function getcolorentry(arg1::Ptr{GDALColorTableH},arg2::Integer)
    ccall((:GDALGetColorEntry,libgdal),Ptr{GDALColorEntry},(Ptr{GDALColorTableH},Cint),arg1,arg2)
end

"""
    GDALGetColorEntryAsRGB(GDALColorTableH hTable,
                           int i,
                           GDALColorEntry * poEntry) -> int
Fetch a table entry in RGB format.
"""
function getcolorentryasrgb(arg1::Ptr{GDALColorTableH},arg2::Integer,arg3)
    ccall((:GDALGetColorEntryAsRGB,libgdal),Cint,(Ptr{GDALColorTableH},Cint,Ptr{GDALColorEntry}),arg1,arg2,arg3)
end

"""
    GDALSetColorEntry(GDALColorTableH hTable,
                      int i,
                      const GDALColorEntry * poEntry) -> void
Set entry in color table.
"""
function setcolorentry(arg1::Ptr{GDALColorTableH},arg2::Integer,arg3)
    ccall((:GDALSetColorEntry,libgdal),Void,(Ptr{GDALColorTableH},Cint,Ptr{GDALColorEntry}),arg1,arg2,arg3)
end

"""
    GDALCreateColorRamp(GDALColorTableH hTable,
                        int nStartIndex,
                        const GDALColorEntry * psStartColor,
                        int nEndIndex,
                        const GDALColorEntry * psEndColor) -> void
Create color ramp.
"""
function createcolorramp(hTable::Ptr{GDALColorTableH},nStartIndex::Integer,psStartColor,nEndIndex::Integer,psEndColor)
    ccall((:GDALCreateColorRamp,libgdal),Void,(Ptr{GDALColorTableH},Cint,Ptr{GDALColorEntry},Cint,Ptr{GDALColorEntry}),hTable,nStartIndex,psStartColor,nEndIndex,psEndColor)
end

"""
    GDALCreateRasterAttributeTable(void) -> GDALRasterAttributeTableH
Construct empty table.
"""
function createrasterattributetable()
    checknull(ccall((:GDALCreateRasterAttributeTable,libgdal),Ptr{GDALRasterAttributeTableH},()))
end

"""
    GDALDestroyRasterAttributeTable(GDALRasterAttributeTableH) -> void
Destroys a RAT.
"""
function destroyrasterattributetable(arg1::Ptr{GDALRasterAttributeTableH})
    ccall((:GDALDestroyRasterAttributeTable,libgdal),Void,(Ptr{GDALRasterAttributeTableH},),arg1)
end

"""
    GDALRATGetColumnCount(GDALRasterAttributeTableH) -> int
Fetch table column count.
"""
function ratgetcolumncount(arg1::Ptr{GDALRasterAttributeTableH})
    ccall((:GDALRATGetColumnCount,libgdal),Cint,(Ptr{GDALRasterAttributeTableH},),arg1)
end

"""
    GDALRATGetNameOfCol(GDALRasterAttributeTableH,
                        int) -> const char *
Fetch name of indicated column.
"""
function ratgetnameofcol(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer)
    bytestring(ccall((:GDALRATGetNameOfCol,libgdal),Cstring,(Ptr{GDALRasterAttributeTableH},Cint),arg1,arg2))
end

"""
    GDALRATGetUsageOfCol(GDALRasterAttributeTableH,
                         int) -> GDALRATFieldUsage
Fetch column usage value.
"""
function ratgetusageofcol(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer)
    ccall((:GDALRATGetUsageOfCol,libgdal),GDALRATFieldUsage,(Ptr{GDALRasterAttributeTableH},Cint),arg1,arg2)
end

"""
    GDALRATGetTypeOfCol(GDALRasterAttributeTableH,
                        int) -> GDALRATFieldType
Fetch column type.
"""
function ratgettypeofcol(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer)
    ccall((:GDALRATGetTypeOfCol,libgdal),GDALRATFieldType,(Ptr{GDALRasterAttributeTableH},Cint),arg1,arg2)
end

"""
    GDALRATGetColOfUsage(GDALRasterAttributeTableH,
                         GDALRATFieldUsage) -> int
Fetch column index for given usage.
"""
function ratgetcolofusage(arg1::Ptr{GDALRasterAttributeTableH},arg2::GDALRATFieldUsage)
    ccall((:GDALRATGetColOfUsage,libgdal),Cint,(Ptr{GDALRasterAttributeTableH},GDALRATFieldUsage),arg1,arg2)
end

"""
    GDALRATGetRowCount(GDALRasterAttributeTableH) -> int
Fetch row count.
"""
function ratgetrowcount(arg1::Ptr{GDALRasterAttributeTableH})
    ccall((:GDALRATGetRowCount,libgdal),Cint,(Ptr{GDALRasterAttributeTableH},),arg1)
end

"""
    GDALRATGetValueAsString(GDALRasterAttributeTableH,
                            int,
                            int) -> const char *
Fetch field value as a string.
"""
function ratgetvalueasstring(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer,arg3::Integer)
    bytestring(ccall((:GDALRATGetValueAsString,libgdal),Cstring,(Ptr{GDALRasterAttributeTableH},Cint,Cint),arg1,arg2,arg3))
end

"""
    GDALRATGetValueAsInt(GDALRasterAttributeTableH,
                         int,
                         int) -> int
Fetch field value as a integer.
"""
function ratgetvalueasint(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer,arg3::Integer)
    ccall((:GDALRATGetValueAsInt,libgdal),Cint,(Ptr{GDALRasterAttributeTableH},Cint,Cint),arg1,arg2,arg3)
end

"""
    GDALRATGetValueAsDouble(GDALRasterAttributeTableH,
                            int,
                            int) -> double
Fetch field value as a double.
"""
function ratgetvalueasdouble(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer,arg3::Integer)
    ccall((:GDALRATGetValueAsDouble,libgdal),Cdouble,(Ptr{GDALRasterAttributeTableH},Cint,Cint),arg1,arg2,arg3)
end

"""
    GDALRATSetValueAsString(GDALRasterAttributeTableH,
                            int,
                            int,
                            const char *) -> void
Set field value from string.
"""
function ratsetvalueasstring(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer,arg3::Integer,arg4)
    ccall((:GDALRATSetValueAsString,libgdal),Void,(Ptr{GDALRasterAttributeTableH},Cint,Cint,Cstring),arg1,arg2,arg3,arg4)
end

"""
    GDALRATSetValueAsInt(GDALRasterAttributeTableH,
                         int,
                         int,
                         int) -> void
Set field value from integer.
"""
function ratsetvalueasint(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer,arg3::Integer,arg4::Integer)
    ccall((:GDALRATSetValueAsInt,libgdal),Void,(Ptr{GDALRasterAttributeTableH},Cint,Cint,Cint),arg1,arg2,arg3,arg4)
end

"""
    GDALRATSetValueAsDouble(GDALRasterAttributeTableH,
                            int,
                            int,
                            double) -> void
Set field value from double.
"""
function ratsetvalueasdouble(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer,arg3::Integer,arg4::Real)
    ccall((:GDALRATSetValueAsDouble,libgdal),Void,(Ptr{GDALRasterAttributeTableH},Cint,Cint,Cdouble),arg1,arg2,arg3,arg4)
end

"""
    GDALRATChangesAreWrittenToFile(GDALRasterAttributeTableH hRAT) -> int
Determine whether changes made to this RAT are reflected directly in the dataset.
"""
function ratchangesarewrittentofile(hRAT::Ptr{GDALRasterAttributeTableH})
    ccall((:GDALRATChangesAreWrittenToFile,libgdal),Cint,(Ptr{GDALRasterAttributeTableH},),hRAT)
end

"""
    GDALRATValuesIOAsDouble(GDALRasterAttributeTableH hRAT,
                            GDALRWFlag eRWFlag,
                            int iField,
                            int iStartRow,
                            int iLength,
                            double * pdfData) -> CPLErr
Read or Write a block of doubles to/from the Attribute Table.
"""
function ratvaluesioasdouble(hRAT::Ptr{GDALRasterAttributeTableH},eRWFlag::GDALRWFlag,iField::Integer,iStartRow::Integer,iLength::Integer,pdfData)
    ccall((:GDALRATValuesIOAsDouble,libgdal),CPLErr,(Ptr{GDALRasterAttributeTableH},GDALRWFlag,Cint,Cint,Cint,Ptr{Cdouble}),hRAT,eRWFlag,iField,iStartRow,iLength,pdfData)
end

"""
    GDALRATValuesIOAsInteger(GDALRasterAttributeTableH hRAT,
                             GDALRWFlag eRWFlag,
                             int iField,
                             int iStartRow,
                             int iLength,
                             int * pnData) -> CPLErr
Read or Write a block of ints to/from the Attribute Table.
"""
function ratvaluesioasinteger(hRAT::Ptr{GDALRasterAttributeTableH},eRWFlag::GDALRWFlag,iField::Integer,iStartRow::Integer,iLength::Integer,pnData)
    ccall((:GDALRATValuesIOAsInteger,libgdal),CPLErr,(Ptr{GDALRasterAttributeTableH},GDALRWFlag,Cint,Cint,Cint,Ptr{Cint}),hRAT,eRWFlag,iField,iStartRow,iLength,pnData)
end

"""
    GDALRATValuesIOAsString(GDALRasterAttributeTableH hRAT,
                            GDALRWFlag eRWFlag,
                            int iField,
                            int iStartRow,
                            int iLength,
                            char ** papszStrList) -> CPLErr
Read or Write a block of strings to/from the Attribute Table.
"""
function ratvaluesioasstring(hRAT::Ptr{GDALRasterAttributeTableH},eRWFlag::GDALRWFlag,iField::Integer,iStartRow::Integer,iLength::Integer,papszStrList)
    ccall((:GDALRATValuesIOAsString,libgdal),CPLErr,(Ptr{GDALRasterAttributeTableH},GDALRWFlag,Cint,Cint,Cint,Ptr{Cstring}),hRAT,eRWFlag,iField,iStartRow,iLength,papszStrList)
end

"""
    GDALRATSetRowCount(GDALRasterAttributeTableH,
                       int) -> void
Set row count.
"""
function ratsetrowcount(arg1::Ptr{GDALRasterAttributeTableH},arg2::Integer)
    ccall((:GDALRATSetRowCount,libgdal),Void,(Ptr{GDALRasterAttributeTableH},Cint),arg1,arg2)
end

"""
    GDALRATCreateColumn(GDALRasterAttributeTableH,
                        const char *,
                        GDALRATFieldType,
                        GDALRATFieldUsage) -> CPLErr
Create new column.
"""
function ratcreatecolumn(arg1::Ptr{GDALRasterAttributeTableH},arg2,arg3::GDALRATFieldType,arg4::GDALRATFieldUsage)
    ccall((:GDALRATCreateColumn,libgdal),CPLErr,(Ptr{GDALRasterAttributeTableH},Cstring,GDALRATFieldType,GDALRATFieldUsage),arg1,arg2,arg3,arg4)
end

"""
    GDALRATSetLinearBinning(GDALRasterAttributeTableH,
                            double,
                            double) -> CPLErr
Set linear binning information.
"""
function ratsetlinearbinning(arg1::Ptr{GDALRasterAttributeTableH},arg2::Real,arg3::Real)
    ccall((:GDALRATSetLinearBinning,libgdal),CPLErr,(Ptr{GDALRasterAttributeTableH},Cdouble,Cdouble),arg1,arg2,arg3)
end

"""
    GDALRATGetLinearBinning(GDALRasterAttributeTableH,
                            double *,
                            double *) -> int
Get linear binning information.
"""
function ratgetlinearbinning(arg1::Ptr{GDALRasterAttributeTableH},arg2,arg3)
    ccall((:GDALRATGetLinearBinning,libgdal),Cint,(Ptr{GDALRasterAttributeTableH},Ptr{Cdouble},Ptr{Cdouble}),arg1,arg2,arg3)
end

"""
    GDALRATInitializeFromColorTable(GDALRasterAttributeTableH,
                                    GDALColorTableH) -> CPLErr
Initialize from color table.
"""
function ratinitializefromcolortable(arg1::Ptr{GDALRasterAttributeTableH},arg2::Ptr{GDALColorTableH})
    ccall((:GDALRATInitializeFromColorTable,libgdal),CPLErr,(Ptr{GDALRasterAttributeTableH},Ptr{GDALColorTableH}),arg1,arg2)
end

"""
    GDALRATTranslateToColorTable(GDALRasterAttributeTableH,
                                 int nEntryCount) -> GDALColorTableH
Translate to a color table.
"""
function rattranslatetocolortable(arg1::Ptr{GDALRasterAttributeTableH},nEntryCount::Integer)
    checknull(ccall((:GDALRATTranslateToColorTable,libgdal),Ptr{GDALColorTableH},(Ptr{GDALRasterAttributeTableH},Cint),arg1,nEntryCount))
end

"""
    GDALRATDumpReadable(GDALRasterAttributeTableH,
                        FILE *) -> void
Dump RAT in readable form.
"""
function ratdumpreadable(arg1::Ptr{GDALRasterAttributeTableH},arg2)
    ccall((:GDALRATDumpReadable,libgdal),Void,(Ptr{GDALRasterAttributeTableH},Ptr{FILE}),arg1,arg2)
end

"""
    GDALRATClone(GDALRasterAttributeTableH) -> GDALRasterAttributeTableH
Copy Raster Attribute Table.
"""
function ratclone(arg1::Ptr{GDALRasterAttributeTableH})
    checknull(ccall((:GDALRATClone,libgdal),Ptr{GDALRasterAttributeTableH},(Ptr{GDALRasterAttributeTableH},),arg1))
end

"""
    GDALRATSerializeJSON(GDALRasterAttributeTableH) -> void *
Serialize Raster Attribute Table in Json format.
"""
function ratserializejson(arg1::Ptr{GDALRasterAttributeTableH})
    ccall((:GDALRATSerializeJSON,libgdal),Ptr{Void},(Ptr{GDALRasterAttributeTableH},),arg1)
end

"""
    GDALRATGetRowOfValue(GDALRasterAttributeTableH,
                         double) -> int
Get row for pixel value.
"""
function ratgetrowofvalue(arg1::Ptr{GDALRasterAttributeTableH},arg2::Real)
    ccall((:GDALRATGetRowOfValue,libgdal),Cint,(Ptr{GDALRasterAttributeTableH},Cdouble),arg1,arg2)
end

"""
    GDALSetCacheMax(int nNewSizeInBytes) -> void
Set maximum cache memory.
### Parameters
* **nNewSizeInBytes**: the maximum number of bytes for caching.
"""
function setcachemax(nBytes::Integer)
    ccall((:GDALSetCacheMax,libgdal),Void,(Cint,),nBytes)
end

"""
    GDALGetCacheMax() -> int
Get maximum cache memory.
### Returns
maximum in bytes.
"""
function getcachemax()
    ccall((:GDALGetCacheMax,libgdal),Cint,())
end

"""
    GDALGetCacheUsed() -> int
Get cache memory used.
### Returns
the number of bytes of memory currently in use by the GDALRasterBlock memory caching.
"""
function getcacheused()
    ccall((:GDALGetCacheUsed,libgdal),Cint,())
end

"""
    GDALSetCacheMax64(GIntBig nNewSizeInBytes) -> void
Set maximum cache memory.
### Parameters
* **nNewSizeInBytes**: the maximum number of bytes for caching.
"""
function setcachemax64(nBytes::GIntBig)
    ccall((:GDALSetCacheMax64,libgdal),Void,(GIntBig,),nBytes)
end

"""
    GDALGetCacheMax64() -> GIntBig
Get maximum cache memory.
### Returns
maximum in bytes.
"""
function getcachemax64()
    ccall((:GDALGetCacheMax64,libgdal),GIntBig,())
end

"""
    GDALGetCacheUsed64() -> GIntBig
Get cache memory used.
### Returns
the number of bytes of memory currently in use by the GDALRasterBlock memory caching.
"""
function getcacheused64()
    ccall((:GDALGetCacheUsed64,libgdal),GIntBig,())
end

"""
    GDALFlushCacheBlock() -> int
Try to flush one cached raster block.
### Returns
TRUE if one block was flushed, FALSE if there are no cached blocks or if they are currently locked.
"""
function flushcacheblock()
    ccall((:GDALFlushCacheBlock,libgdal),Cint,())
end

"""
    GDALDatasetGetVirtualMem(GDALDatasetH hDS,
                             GDALRWFlag eRWFlag,
                             int nXOff,
                             int nYOff,
                             int nXSize,
                             int nYSize,
                             int nBufXSize,
                             int nBufYSize,
                             GDALDataType eBufType,
                             int nBandCount,
                             int * panBandMap,
                             int nPixelSpace,
                             GIntBig nLineSpace,
                             GIntBig nBandSpace,
                             size_t nCacheSize,
                             size_t nPageSizeHint,
                             int bSingleThreadUsage,
                             char ** papszOptions) -> CPLVirtualMem *
Create a CPLVirtualMem object from a GDAL dataset object.
### Parameters
* **hDS**: Dataset object
* **eRWFlag**: Either GF_Read to read a region of data, or GF_Write to write a region of data.
* **nXOff**: The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.
* **nYOff**: The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.
* **nXSize**: The width of the region of the band to be accessed in pixels.
* **nYSize**: The height of the region of the band to be accessed in lines.
* **nBufXSize**: the width of the buffer image into which the desired region is to be read, or from which it is to be written.
* **nBufYSize**: the height of the buffer image into which the desired region is to be read, or from which it is to be written.
* **eBufType**: the type of the pixel values in the data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed.
* **nBandCount**: the number of bands being read or written.
* **panBandMap**: the list of nBandCount band numbers being read/written. Note band numbers are 1 based. This may be NULL to select the first nBandCount bands.
* **nPixelSpace**: The byte offset from the start of one pixel value in the buffer to the start of the next pixel value within a scanline. If defaulted (0) the size of the datatype eBufType is used.
* **nLineSpace**: The byte offset from the start of one scanline in the buffer to the start of the next. If defaulted (0) the size of the datatype eBufType * nBufXSize is used.
* **nBandSpace**: the byte offset from the start of one bands data to the start of the next. If defaulted (0) the value will be nLineSpace * nBufYSize implying band sequential organization of the data buffer.
* **nCacheSize**: size in bytes of the maximum memory that will be really allocated (must ideally fit into RAM)
* **nPageSizeHint**: hint for the page size. Must be a multiple of the system page size, returned by CPLGetPageSize(). Minimum value is generally 4096. Might be set to 0 to let the function determine a default page size.
* **bSingleThreadUsage**: set to TRUE if there will be no concurrent threads that will access the virtual memory mapping. This can optimize performance a bit. If set to FALSE, CPLVirtualMemDeclareThread() must be called.
* **papszOptions**: NULL terminated list of options. Unused for now.
### Returns
a virtual memory object that must be freed by CPLVirtualMemFree(), or NULL in case of failure.
"""
function datasetgetvirtualmem{T <: GDALDatasetH}(hDS::Ptr{T},eRWFlag::GDALRWFlag,nXOff::Integer,nYOff::Integer,nXSize::Integer,nYSize::Integer,nBufXSize::Integer,nBufYSize::Integer,eBufType::GDALDataType,nBandCount::Integer,panBandMap,nPixelSpace::Integer,nLineSpace::GIntBig,nBandSpace::GIntBig,nCacheSize::Csize_t,nPageSizeHint::Csize_t,bSingleThreadUsage::Integer,papszOptions)
    ccall((:GDALDatasetGetVirtualMem,libgdal),Ptr{CPLVirtualMem},(Ptr{GDALDatasetH},GDALRWFlag,Cint,Cint,Cint,Cint,Cint,Cint,GDALDataType,Cint,Ptr{Cint},Cint,GIntBig,GIntBig,Csize_t,Csize_t,Cint,Ptr{Cstring}),hDS,eRWFlag,nXOff,nYOff,nXSize,nYSize,nBufXSize,nBufYSize,eBufType,nBandCount,panBandMap,nPixelSpace,nLineSpace,nBandSpace,nCacheSize,nPageSizeHint,bSingleThreadUsage,papszOptions)
end

"""
    GDALRasterBandGetVirtualMem(GDALRasterBandH hBand,
                                GDALRWFlag eRWFlag,
                                int nXOff,
                                int nYOff,
                                int nXSize,
                                int nYSize,
                                int nBufXSize,
                                int nBufYSize,
                                GDALDataType eBufType,
                                int nPixelSpace,
                                GIntBig nLineSpace,
                                size_t nCacheSize,
                                size_t nPageSizeHint,
                                int bSingleThreadUsage,
                                char ** papszOptions) -> CPLVirtualMem *
Create a CPLVirtualMem object from a GDAL raster band object.
### Parameters
* **hBand**: Rasterband object
* **eRWFlag**: Either GF_Read to read a region of data, or GF_Write to write a region of data.
* **nXOff**: The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.
* **nYOff**: The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.
* **nXSize**: The width of the region of the band to be accessed in pixels.
* **nYSize**: The height of the region of the band to be accessed in lines.
* **nBufXSize**: the width of the buffer image into which the desired region is to be read, or from which it is to be written.
* **nBufYSize**: the height of the buffer image into which the desired region is to be read, or from which it is to be written.
* **eBufType**: the type of the pixel values in the data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed.
* **nPixelSpace**: The byte offset from the start of one pixel value in the buffer to the start of the next pixel value within a scanline. If defaulted (0) the size of the datatype eBufType is used.
* **nLineSpace**: The byte offset from the start of one scanline in the buffer to the start of the next. If defaulted (0) the size of the datatype eBufType * nBufXSize is used.
* **nCacheSize**: size in bytes of the maximum memory that will be really allocated (must ideally fit into RAM)
* **nPageSizeHint**: hint for the page size. Must be a multiple of the system page size, returned by CPLGetPageSize(). Minimum value is generally 4096. Might be set to 0 to let the function determine a default page size.
* **bSingleThreadUsage**: set to TRUE if there will be no concurrent threads that will access the virtual memory mapping. This can optimize performance a bit. If set to FALSE, CPLVirtualMemDeclareThread() must be called.
* **papszOptions**: NULL terminated list of options. Unused for now.
### Returns
a virtual memory object that must be freed by CPLVirtualMemFree(), or NULL in case of failure.
"""
function rasterbandgetvirtualmem{T <: GDALRasterBandH}(hBand::Ptr{T},eRWFlag::GDALRWFlag,nXOff::Integer,nYOff::Integer,nXSize::Integer,nYSize::Integer,nBufXSize::Integer,nBufYSize::Integer,eBufType::GDALDataType,nPixelSpace::Integer,nLineSpace::GIntBig,nCacheSize::Csize_t,nPageSizeHint::Csize_t,bSingleThreadUsage::Integer,papszOptions)
    ccall((:GDALRasterBandGetVirtualMem,libgdal),Ptr{CPLVirtualMem},(Ptr{GDALRasterBandH},GDALRWFlag,Cint,Cint,Cint,Cint,Cint,Cint,GDALDataType,Cint,GIntBig,Csize_t,Csize_t,Cint,Ptr{Cstring}),hBand,eRWFlag,nXOff,nYOff,nXSize,nYSize,nBufXSize,nBufYSize,eBufType,nPixelSpace,nLineSpace,nCacheSize,nPageSizeHint,bSingleThreadUsage,papszOptions)
end

"""
    GDALGetVirtualMemAuto(GDALRasterBandH hBand,
                          GDALRWFlag eRWFlag,
                          int * pnPixelSpace,
                          GIntBig * pnLineSpace,
                          char ** papszOptions) -> CPLVirtualMem *
Create a CPLVirtualMem object from a GDAL raster band object.
"""
function getvirtualmemauto{T <: GDALRasterBandH}(hBand::Ptr{T},eRWFlag::GDALRWFlag,pnPixelSpace,pnLineSpace,papszOptions)
    ccall((:GDALGetVirtualMemAuto,libgdal),Ptr{CPLVirtualMem},(Ptr{GDALRasterBandH},GDALRWFlag,Ptr{Cint},Ptr{GIntBig},Ptr{Cstring}),hBand,eRWFlag,pnPixelSpace,pnLineSpace,papszOptions)
end

"""
    GDALDatasetGetTiledVirtualMem(GDALDatasetH hDS,
                                  GDALRWFlag eRWFlag,
                                  int nXOff,
                                  int nYOff,
                                  int nXSize,
                                  int nYSize,
                                  int nTileXSize,
                                  int nTileYSize,
                                  GDALDataType eBufType,
                                  int nBandCount,
                                  int * panBandMap,
                                  GDALTileOrganization eTileOrganization,
                                  size_t nCacheSize,
                                  int bSingleThreadUsage,
                                  char ** papszOptions) -> CPLVirtualMem *
Create a CPLVirtualMem object from a GDAL dataset object, with tiling organization.
### Parameters
* **hDS**: Dataset object
* **eRWFlag**: Either GF_Read to read a region of data, or GF_Write to write a region of data.
* **nXOff**: The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.
* **nYOff**: The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.
* **nXSize**: The width of the region of the band to be accessed in pixels.
* **nYSize**: The height of the region of the band to be accessed in lines.
* **nTileXSize**: the width of the tiles.
* **nTileYSize**: the height of the tiles.
* **eBufType**: the type of the pixel values in the data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed.
* **nBandCount**: the number of bands being read or written.
* **panBandMap**: the list of nBandCount band numbers being read/written. Note band numbers are 1 based. This may be NULL to select the first nBandCount bands.
* **eTileOrganization**: tile organization.
* **nCacheSize**: size in bytes of the maximum memory that will be really allocated (must ideally fit into RAM)
* **bSingleThreadUsage**: set to TRUE if there will be no concurrent threads that will access the virtual memory mapping. This can optimize performance a bit. If set to FALSE, CPLVirtualMemDeclareThread() must be called.
* **papszOptions**: NULL terminated list of options. Unused for now.
### Returns
a virtual memory object that must be freed by CPLVirtualMemFree(), or NULL in case of failure.
"""
function datasetgettiledvirtualmem{T <: GDALDatasetH}(hDS::Ptr{T},eRWFlag::GDALRWFlag,nXOff::Integer,nYOff::Integer,nXSize::Integer,nYSize::Integer,nTileXSize::Integer,nTileYSize::Integer,eBufType::GDALDataType,nBandCount::Integer,panBandMap,eTileOrganization::GDALTileOrganization,nCacheSize::Csize_t,bSingleThreadUsage::Integer,papszOptions)
    ccall((:GDALDatasetGetTiledVirtualMem,libgdal),Ptr{CPLVirtualMem},(Ptr{GDALDatasetH},GDALRWFlag,Cint,Cint,Cint,Cint,Cint,Cint,GDALDataType,Cint,Ptr{Cint},GDALTileOrganization,Csize_t,Cint,Ptr{Cstring}),hDS,eRWFlag,nXOff,nYOff,nXSize,nYSize,nTileXSize,nTileYSize,eBufType,nBandCount,panBandMap,eTileOrganization,nCacheSize,bSingleThreadUsage,papszOptions)
end

"""
    GDALRasterBandGetTiledVirtualMem(GDALRasterBandH hBand,
                                     GDALRWFlag eRWFlag,
                                     int nXOff,
                                     int nYOff,
                                     int nXSize,
                                     int nYSize,
                                     int nTileXSize,
                                     int nTileYSize,
                                     GDALDataType eBufType,
                                     size_t nCacheSize,
                                     int bSingleThreadUsage,
                                     char ** papszOptions) -> CPLVirtualMem *
Create a CPLVirtualMem object from a GDAL rasterband object, with tiling organization.
### Parameters
* **hBand**: Rasterband object
* **eRWFlag**: Either GF_Read to read a region of data, or GF_Write to write a region of data.
* **nXOff**: The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.
* **nYOff**: The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.
* **nXSize**: The width of the region of the band to be accessed in pixels.
* **nYSize**: The height of the region of the band to be accessed in lines.
* **nTileXSize**: the width of the tiles.
* **nTileYSize**: the height of the tiles.
* **eBufType**: the type of the pixel values in the data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed.
* **nCacheSize**: size in bytes of the maximum memory that will be really allocated (must ideally fit into RAM)
* **bSingleThreadUsage**: set to TRUE if there will be no concurrent threads that will access the virtual memory mapping. This can optimize performance a bit. If set to FALSE, CPLVirtualMemDeclareThread() must be called.
* **papszOptions**: NULL terminated list of options. Unused for now.
### Returns
a virtual memory object that must be freed by CPLVirtualMemFree(), or NULL in case of failure.
"""
function rasterbandgettiledvirtualmem{T <: GDALRasterBandH}(hBand::Ptr{T},eRWFlag::GDALRWFlag,nXOff::Integer,nYOff::Integer,nXSize::Integer,nYSize::Integer,nTileXSize::Integer,nTileYSize::Integer,eBufType::GDALDataType,nCacheSize::Csize_t,bSingleThreadUsage::Integer,papszOptions)
    ccall((:GDALRasterBandGetTiledVirtualMem,libgdal),Ptr{CPLVirtualMem},(Ptr{GDALRasterBandH},GDALRWFlag,Cint,Cint,Cint,Cint,Cint,Cint,GDALDataType,Csize_t,Cint,Ptr{Cstring}),hBand,eRWFlag,nXOff,nYOff,nXSize,nYSize,nTileXSize,nTileYSize,eBufType,nCacheSize,bSingleThreadUsage,papszOptions)
end

"""
    GDALCreatePansharpenedVRT(const char * pszXML,
                              GDALRasterBandH hPanchroBand,
                              int nInputSpectralBands,
                              GDALRasterBandH * pahInputSpectralBands) -> GDALDatasetH
Create a virtual pansharpened dataset.
### Parameters
* **pszXML**: Pansharpened VRT XML where <SpectralBand> elements have no explicit SourceFilename and SourceBand. The spectral bands in the XML will be assigned the successive values of the pahInputSpectralBands array. Must not be NULL.
* **hPanchroBand**: Panchromatic band. Must not be NULL.
* **nInputSpectralBands**: Number of input spectral bands. Must be greater than zero.
* **pahInputSpectralBands**: Array of nInputSpectralBands spectral bands.
### Returns
NULL on failure, or a new virtual dataset handle on success to be closed with GDALClose().
"""
function createpansharpenedvrt{T <: GDALRasterBandH}(pszXML,hPanchroBand::Ptr{T},nInputSpectralBands::Integer,pahInputSpectralBands)
    checknull(ccall((:GDALCreatePansharpenedVRT,libgdal),Ptr{GDALDatasetH},(Cstring,Ptr{GDALRasterBandH},Cint,Ptr{GDALRasterBandH}),pszXML,hPanchroBand,nInputSpectralBands,pahInputSpectralBands))
end


text:
module Core

export
    Dynamics,
    controlcallback,
    configuration_renormalizer,
    zero_control!,
    RealtimeRateLimiter

using DocStringExtensions
@template (FUNCTIONS, METHODS, MACROS) =
    """
    $(SIGNATURES)
    $(DOCSTRING)
    """

@template (TYPES,) =
    """
    $(TYPEDEF)
    $(DOCSTRING)
    """

using Compat
using DiffEqBase:
    ODEProblem, DiscreteCallback, u_modified!, CallbackSet
using DiffEqCallbacks:
    PeriodicCallback
using RigidBodyDynamics:
    Mechanism,
    MechanismState, DynamicsResult,
    StateCache, DynamicsResultCache, SegmentedVectorCache,
    JointID,
    velocity, configuration,
    num_positions, num_velocities, num_additional_states,
    set_configuration!, normalize_configuration!,
    configuration_derivative!, dynamics!,
    ranges

import DiffEqDiffTools
import ForwardDiff

"""
A 'zero' controller, i.e. one that sets all control torques to zero at all times.
"""
zero_control!(τ::AbstractVector, t, state) = τ .= 0

struct Dynamics{M, JointCollection, C, P}
    statecache::StateCache{M, JointCollection}
    τcache::SegmentedVectorCache{JointID, Base.OneTo{JointID}}
    resultcache::DynamicsResultCache{M}
    control!::C
    setparams!::P
end

"""
Create a `Dynamics` object, representing either the passive or closed-loop dynamics of a `RigidBodyDynamics.Mechanism`.

The `control!` argument is a callable with the signature `control!(τ, t, state)`, where `τ` is the
torque vector to be set in the body of `control!`, `t` is the current time, and `state` is a `MechanismState` object.
By default, `control!` is [`zero_control!`](@ref) (resulting in the passive dynamics).

The `setparams!` keyword argument is a callable with the signature `setparams!(state, p)` where `state` is a
`MechanismState` and `p` is a vector of parameters, as used in OrdinaryDiffEq.jl.
"""
function Dynamics(mechanism::Mechanism, control! = zero_control!; setparams! = (state, p) -> nothing)
    vranges = let state = MechanismState(mechanism) # just to get velocity ranges; TODO: consider adding method that creates this from a Mechanism
        ranges(velocity(state))
    end
    Dynamics(StateCache(mechanism), SegmentedVectorCache(vranges), DynamicsResultCache(mechanism), control!, setparams!)
end

Base.@pure cachevartype(::Type{<:MechanismState{<:Any, <:Any, C}}) where {C} = C

function (dynamics::Dynamics)(ẋ::AbstractVector, x::AbstractVector{X}, p, t::T) where {X, T}
    state = dynamics.statecache[X]
    C = cachevartype(typeof(state))
    Tau = promote_type(T, C)
    τ = dynamics.τcache[Tau]
    result = dynamics.resultcache[Tau]
    Compat.copyto!(state, x)
    dynamics.setparams!(state, p)
    dynamics.control!(τ, t, state)
    dynamics!(result, state, τ)
    Compat.copyto!(ẋ, result)
    ẋ
end

# Disable ForwardDiff tag mechanism to work around https://github.com/JuliaDiff/ForwardDiff.jl/issues/267
# The Tag type becomes too complicated due to the TypeSortedCollection type parameter, resulting in inference issues
ForwardDiff.Tag(::DiffEqDiffTools.TimeGradientWrapper{<:Dynamics}, ::Type{V}) where {V} = nothing
ForwardDiff.Tag(::DiffEqDiffTools.UJacobianWrapper{<:Dynamics}, ::Type{V}) where {V} = nothing
ForwardDiff.Tag(::DiffEqDiffTools.TimeDerivativeWrapper{<:Dynamics}, ::Type{V}) where {V} = nothing
ForwardDiff.Tag(::DiffEqDiffTools.UDerivativeWrapper{<:Dynamics}, ::Type{V}) where {V} = nothing
ForwardDiff.Tag(::DiffEqDiffTools.ParamJacobianWrapper{<:Dynamics}, ::Type{V}) where {V} = nothing

"""
Can be used to create a callback associated with a given controller.
"""
controlcallback(control!::Any) = nothing

"""
Create a `DiffEqBase.ODEProblem` associated with the dynamics of a `RigidBodyDynamics.Mechanism`.

The initial state `x0` can be either a [`RigidBodyDynamics.MechanismState`]
(http://JuliaRobotics.github.io/RigidBodyDynamics.jl/stable/mechanismstate.html#RigidBodyDynamics.MechanismState)),
or an `AbstractVector` containing the initial state represented as `[q; v; s]`, where `q` is the configuration vector,
`v` is the velocity vector, and `s` is the vector of additional states.

The `callback` keyword argument can be used to pass in additional [DifferentialEquations.jl callbacks]
(http://docs.juliadiffeq.org/stable/features/callback_functions.html#Using-Callbacks-1).
"""
function ODEProblem(dynamics::Dynamics, x0::Union{AbstractVector, MechanismState}, tspan, p = nothing;
        callback = nothing, kwargs...)
    callbacks = CallbackSet(controlcallback(dynamics.control!), callback)
    ODEProblem{true}(dynamics, Vector(x0), tspan, p; callback = callbacks, kwargs...)
end

Base.@deprecate(ODEProblem(state::MechanismState, tspan, control! = zero_control!; callback = nothing),
    ODEProblem(Dynamics(state.mechanism, control!), state, tspan; callback = callback)
)

"""
`configuration_renormalizer` can be used to create a callback that projects the configuration
of a mechanism's state onto the configuration manifold. This may be necessary for mechanism's
with e.g. quaternion-parameterized orientations as part of their joint configuration vectors,
as numerical integration can cause the configuration to drift away from the unit norm constraints.

The callback is implemented as a [`DiffEqCallbacks.DiscreteCallback`]
(http://docs.juliadiffeq.org/stable/features/callback_functions.html#DiscreteCallback-1)
By default, it is called at every integrator time step.
"""
function configuration_renormalizer(state::MechanismState, condition = (u, t, integrator) -> true)
    renormalize = let state = state # https://github.com/JuliaLang/julia/issues/15276
        function (integrator)
            q = view(integrator.u, 1 : num_positions(state)) # TODO: allocates
            set_configuration!(state, q)
            normalize_configuration!(state)
            Compat.copyto!(q, configuration(state))
            u_modified!(integrator, true)
        end
    end
    DiscreteCallback(condition, renormalize; save_positions = (false, false))
end

# TODO: move to DiffEqCallbacks:
mutable struct RealtimeRateLimiterState{T}
    simtime0::T
    walltime0::Float64
    reset::Bool
    RealtimeRateLimiterState{T}() where {T} = new{T}(zero(T), 0.0, true)
end

"""
    RealtimeRateLimiter(; max_rate = 1., poll_interval = 1 / 30; save_positions = (false, false))

A `DiscreteCallback` that limits the rate of integration so that integration time `t`
increases at a rate no higher than `max_rate` compared to wall time.

A `RealtimeRateLimiter` can be used, for example, if you want to simulate a physical system
including its timing characteristics. Specific use cases may include realtime animation
and user interaction during the simulation.

The `poll_interval` keyword argument can be used to control how often the integration is
stopped to check whether to sleep (and for how long). Specifically, this operation happens
every `poll_interval / max_rate` *in terms of integration time*, which corresponds to approximately
every `poll_interval` seconds *wall time* if `max_rate` is actually achieved.
"""
function RealtimeRateLimiter(; max_rate = 1., poll_interval = 1 / 60, save_positions = (false, false), reset_interval = 1.0)
    T = promote_type(typeof(max_rate), typeof(poll_interval))
    state = RealtimeRateLimiterState{T}()
    limit_rate = let state = state, max_rate = max_rate, poll_interval = poll_interval # https://github.com/JuliaLang/julia/issues/15276
        function (integrator)
            simtime = integrator.t
            if state.reset
                state.simtime0 = simtime
                state.walltime0 = time()
                state.reset = false
            else
                Δsimtime = simtime - state.simtime0
                minΔwalltime = Δsimtime / max_rate
                Δwalltime = time() - state.walltime0
                sleeptime = minΔwalltime - Δwalltime
                if sleeptime > 1e-3 # minimum time for `sleep` function
                    sleep(sleeptime)
                end
                if Δwalltime > reset_interval
                    # Reset every once in a while. If we don't do this, a slowdown in simulation
                    # rate at some point will cause the maximum rate to not be enforced until the
                    # simulation catches up. Don't do this too often to get more accurate results
                    # (drift doesn't accumulate as quickly).
                    state.simtime0 = simtime
                    state.walltime0 = time()
                end
            end
            u_modified!(integrator, false)
        end
    end
    initialize = let state = state
        (c, u, t, integrator) -> (state.reset = true)
    end
    PeriodicCallback(limit_rate, poll_interval / max_rate; initialize = initialize, save_positions = save_positions)
end

end # module


text:
#!/usr/bin/env julia

using RDatasets, Gadfly, Compat

tests = [
    ("points",                                6inch, 3inch),
    ("colored_points",                        6inch, 3inch),
    ("function_plots",                        6inch, 3inch),
    ("function_explicit_colors",              6inch, 3inch),
    ("function_layers",                       6inch, 3inch),
    ("multicolumn_colorkey",                  6inch, 2inch),
    ("vstack",                                6inch, 6inch),
    ("hstack",                                6inch, 3inch),
    ("colorful_hist",                         6inch, 3inch),
    ("discrete_histogram",                    6inch, 3inch),
    ("discrete_bar",                          6inch, 3inch),
    ("discrete_bar_horizontal",               6inch, 3inch),
    ("stacked_discrete_histogram",            6inch, 3inch),
    ("stacked_discrete_histogram_horizontal", 6inch, 3inch),
    ("stacked_continuous_histogram",          6inch, 3inch),
    ("dodged_discrete_histogram",             6inch, 3inch),
    ("dodged_discrete_histogram_horizontal",  6inch, 3inch),
    ("array_aesthetics",                      6inch, 3inch),
    ("subplot_grid",                          10inch, 10inch),
    ("subplot_grid_free_axis",                10inch, 10inch),
    ("subplot_grid_histogram",                10inch, 3inch),
    ("subplot_layers",                        8inch, 6inch),
    ("labels",                                6inch, 6inch),
    ("percent",                               6inch, 6inch),
    ("timeseries_day",                        6inch, 3inch),
    ("timeseries_month",                      6inch, 3inch),
    ("timeseries_year_1",                     6inch, 3inch),
    ("timeseries_year_2",                     6inch, 3inch),
    ("timeseries_year_3",                     6inch, 3inch),
    ("timeseries_colorful",                   6inch, 3inch),
    ("date_bar",                              6inch, 3inch),
    ("custom_themes",                         6inch, 3inch),
    ("issue98",                               6inch, 3inch),
    ("issue82",                               6inch, 3inch),
    ("histogram2d",                           6inch, 3inch),
    ("rectbin",                               6inch, 3inch),
    ("density",                               6inch, 3inch),
    ("colorful_density",                      6inch, 3inch),
    ("explicit_colorkey_title",               6inch, 3inch),
    ("explicit_subplot_titles",               6inch, 3inch),
    ("subplot_grid_smooth",                   6inch, 8inch),
    ("smooth_lm",                             6inch, 8inch),
    ("colored_smooth_lm",                     6inch, 8inch),
    ("histogram_errorbar",                    6inch, 3inch),
    ("issue106",                              6inch, 3inch),
    ("continuous_color_scale_range",          6inch, 3inch),
    ("continuous_scale_range",                6inch, 3inch),
    ("log10_scale_range",                     6inch, 3inch),
    ("histogram_explicit_bins",               6inch, 3inch),
    ("histogram2d_explicit_bins",             6inch, 3inch),
    ("explicit_number_format",                6inch, 3inch),
    ("explicit_xy_ticks",                     6inch, 3inch),
    ("boxplot",                               6inch, 3inch),
    ("subplot_categorical_bar",               6inch, 3inch),
    ("errorbar",                              6inch, 3inch),
    ("issue120",                              6inch, 3inch),
    ("histogram2d_discrete",                  6inch, 3inch),
    ("layer_themes",                          6inch, 3inch),
    ("layer_guide",                           6inch, 3inch),
    ("discrete_color_manual",                 6inch, 3inch),
    ("ordered_line",                          6inch, 3inch),
    ("nan_skipping",                          6inch, 3inch),
    ("hexbin",                                6inch, 3inch),
    ("spy",                                   6inch, 3inch),
    ("issue177",                              6inch, 3inch),
    ("ribbon",                                6inch, 3inch),
    ("colored_ribbon",                        6inch, 3inch),
    ("layer_leak",                            6inch, 3inch),
    ("hline_vline",                           6inch, 3inch),
    ("grid_strokedash",                       6inch, 3inch),
    ("aspect_ratio",                          6inch, 3inch),
    ("contour_function",                      6inch, 3inch),
    ("contour_matrix",                        6inch, 3inch),
    ("stat_qq",                               6inch, 16inch),
    ("line_histogram",                        6inch, 3inch),
    ("layer_data",                            6inch, 3inch),
    ("multi_geom_layer",                      6inch, 3inch),
    ("raster",                                6inch, 3inch),
    ("single_boxplot",                        6inch, 3inch),
    ("subplot_scales",                        6inch, 3inch),
    ("issue509",                              6inch, 3inch),
    ("layer_order",                           6inch, 3inch),
    ("single_datetime",                       6inch, 3inch),
    ("layered_subplots",                      6inch, 6inch),
    ("subplot_layer_data",                    6inch, 6inch),
    ("static_label_layout",                   6inch, 16inch),
    ("subplot_grid_free_y_1",                 30cm,  10cm),
    ("subplot_grid_free_y_2",                 10cm,  30cm),
    ("violin",                                6inch, 3inch),
    ("single_violin",                         6inch, 3inch),
    ("polygon",                               6inch, 3inch),
    ("jitter",                                6inch, 3inch),
    ("stat_binmean",                          6inch, 12inch),
]

backends = @compat Dict{String, Function}(
    "svg" => (name, width, height) -> SVG("output/$(name).svg", width, height),
    "svgjs" => (name, width, height) -> SVGJS("output/$(name).js.svg", width, height, jsmode=:linkabs),
    "png" => (name, width, height) -> PNG("output/$(name).png", width, height),
    #"ps"  => (name, width, height) -> PS("output/$(name).ps",   width, height),
    #"pdf" => (name, width, height) -> PDF("output/$(name).pdf", width, height)
    "pgf" => (name, width, height) -> PGF("output/$(name).tex", width, height)
)

function run_tests(output_filename)
    testdir = Pkg.dir("Gadfly", "test")
    whitelist = Set()
    if !isempty(ARGS)
        union!(whitelist, ARGS)
    else
        union!(whitelist, [name for (name, width, height) in tests])
    end

    for (name, width, height) in tests
        if !in(name, whitelist)
            continue
        end

        for (backend_name, backend) in backends
            println(STDERR, "Rendering $(name) on $(backend_name) backend.")
            try
                p = evalfile(joinpath(testdir, "$(name).jl"))
                draw(backend(name, width, height), p)
            catch
                println(STDERR, "FAILED!")
                rethrow()
            end
        end
    end

    output = open(output_filename, "w")
    print(output,
        """
        <!DOCTYPE html>

        <meta charset="utf-8" />

            <title>Gadfly Test Plots</title>

        """)

    for (name, width, height) in tests
        if !in(name, whitelist)
            continue
        end

        println(output, "
", name, "
")
        print(output, """
<object type="image/svg+xml" data="$(name).js.svg"></object>
""")
        print(output, """""")
        print(output, """\n""")
    end

    print(output,
        """

        """)

    close(output)
end

run_tests("output/test.html")


text:
module TypesTests

using TensorValues
using Test
using StaticArrays

# Constructors (MultiValue)

a = MArray{Tuple{3,2}}((1,2,3,4,5,6))
v = MultiValue(a)
@test isa(v,MultiValue{Tuple{3,2},Int})
@test v.array.data === a.data

a = SArray{Tuple{3,2}}((1,2,3,4,5,6))

v = MultiValue(a)
@test isa(v,MultiValue{Tuple{3,2},Int})
@test v.array === a

v = MultiValue{Tuple{3,2}}((1,2,3,4,5,6))
@test isa(v,MultiValue{Tuple{3,2},Int})
@test v.array == a

v = MultiValue{Tuple{3,2}}(1,2,3,4,5,6)
@test isa(v,MultiValue{Tuple{3,2},Int})
@test v.array == a

v = MultiValue{Tuple{3,2},Float64}((1,2,3,4,5,6))
@test isa(v,MultiValue{Tuple{3,2},Float64})
@test v.array == a

v = MultiValue{Tuple{3,2},Float64}(1,2,3,4,5,6)
@test isa(v,MultiValue{Tuple{3,2},Float64})
@test v.array == a

a = SVector(1)
v = MultiValue{Tuple{1}}((1,))
@test isa(v,MultiValue{Tuple{1},Int})
@test v.array == a

v = MultiValue{Tuple{1}}(1)
@test isa(v,MultiValue{Tuple{1},Int})
@test v.array == a

a = SMatrix{1,1}(1)
v = MultiValue{Tuple{1,1}}(1)
@test isa(v,MultiValue{Tuple{1,1},Int})
@test v.array == a

a = SVector{0,Int}()
v = MultiValue{Tuple{0},Int}(())
@test isa(v,MultiValue{Tuple{0},Int})
@test v.array == a

a = SMatrix{0,0,Int}()
v = MultiValue{Tuple{0,0},Int}()
@test isa(v,MultiValue{Tuple{0,0},Int})
@test v.array == a

# Constructors (TensorValue)

a = SMatrix{2,2}(1,2,3,4)
t = TensorValue(a)
@test isa(t,TensorValue{2,Int})
@test t.array == [1 3;2 4]

a = MMatrix{2,2}(1,2,3,4)
t = TensorValue(a)
@test isa(t,TensorValue{2,Int})
@test t.array == [1 3;2 4]

t = TensorValue{2}((1,2,3,4))
@test isa(t,TensorValue{2,Int})
@test t.array == [1 3;2 4]

t = TensorValue{2,Float64}((1,2,3,4))
@test isa(t,TensorValue{2,Float64})
@test t.array == [1 3;2 4]

t = TensorValue{2}(1,2,3,4)
@test isa(t,TensorValue{2,Int})
@test t.array == [1 3;2 4]

t = TensorValue{2,Float64}(1,2,3,4)
@test isa(t,TensorValue{2,Float64})
@test t.array == [1 3;2 4]

t = TensorValue(1,2,3,4)
@test isa(t,TensorValue{2,Int})
@test t.array == [1 3;2 4]

t = TensorValue((1,2,3,4))
@test isa(t,TensorValue{2,Int})
@test t.array == [1 3;2 4]

t = TensorValue{0,Int}()
@test isa(t,TensorValue{0,Int})
@test t.array == zeros(0,0)

t = TensorValue{1}(10)
@test isa(t,TensorValue{1,Int})
@test t.array == 10*ones(1,1)

t = TensorValue{1}((10,))
@test isa(t,TensorValue{1,Int})
@test t.array == 10*ones(1,1)

t = TensorValue{1,Float64}(10)
@test isa(t,TensorValue{1,Float64})
@test t.array == 10*ones(1,1)

t = TensorValue{1,Float64}((10,))
@test isa(t,TensorValue{1,Float64})
@test t.array == 10*ones(1,1)

# Constructors (VectorValue)

a = SVector(1)
g = VectorValue(a)
@test isa(g,VectorValue{1,Int})
@test g.array == [1,]

a = SVector(1,2,3,4)
g = VectorValue(a)
@test isa(g,VectorValue{4,Int})
@test g.array == [1,2,3,4]

a = MVector(1,2,3,4)
g = VectorValue(a)
@test isa(g,VectorValue{4,Int})
@test g.array == [1,2,3,4]

g = VectorValue{4}((1,2,3,4))
@test isa(g,VectorValue{4,Int})
@test g.array == [1,2,3,4]

g = VectorValue{1}((1,))
@test isa(g,VectorValue{1,Int})
@test g.array == [1,]

g = VectorValue{0,Int}(())
@test isa(g,VectorValue{0,Int})
@test g.array == []

g = VectorValue{4}(1,2,3,4)
@test isa(g,VectorValue{4,Int})
@test g.array == [1,2,3,4]

g = VectorValue{1}(1)
@test isa(g,VectorValue{1,Int})
@test g.array == [1,]

g = VectorValue{1,Float64}(1)
@test isa(g,VectorValue{1,Float64})
@test g.array == [1,]

g = VectorValue{1,Float64}((1,))
@test isa(g,VectorValue{1,Float64})
@test g.array == [1,]

g = VectorValue{0,Int}()
@test isa(g,VectorValue{0,Int})
@test g.array == []

g = VectorValue{4,Float64}((1,2,3,4))
@test isa(g,VectorValue{4,Float64})
@test g.array == [1,2,3,4]

g = VectorValue{4}(1,2,3,4)
@test isa(g,VectorValue{4,Int})
@test g.array == [1,2,3,4]

g = VectorValue{4,Float64}(1,2,3,4)
@test isa(g,VectorValue{4,Float64})
@test g.array == [1,2,3,4]

g = VectorValue(1,2,3,4)
@test isa(g,VectorValue{4,Int})
@test g.array == [1,2,3,4]

g = VectorValue((1,2,3,4))
@test isa(g,VectorValue{4,Int})
@test g.array == [1,2,3,4]

g = VectorValue(1)
@test isa(g,VectorValue{1,Int})
@test g.array == [1,]

# Initializers

z = zero(MultiValue{Tuple{3,2},Int,2,6})
@test isa(z,MultiValue{Tuple{3,2},Int,2,6})
@test z.array == zeros(Int,(3,2))
s = zero(z)
@test s.array == zeros(Int,(3,2))

z = zero(TensorValue{3,Int,9})
@test isa(z,TensorValue{3,Int,9})
@test z.array == zeros(Int,(3,3))

z = zero(VectorValue{3,Int})
@test isa(z,VectorValue{3,Int})
@test z.array == zeros(Int,3)

z = one(TensorValue{3,Int,9})
@test isa(z,TensorValue{3,Int,9})
@test z.array == [1 0 0; 0 1 0; 0 0 1]
s = one(z)
@test s.array == [1 0 0; 0 1 0; 0 0 1]

# Conversions

a = @SVector ones(Int,3)
b = convert(VectorValue{3,Int},a)
@test isa(b,VectorValue{3,Int})

a = ones(Int,3)
b = convert(VectorValue{3,Int},a)
@test isa(b,VectorValue{3,Int})

a = ones(Int,1)
b = convert(VectorValue{1,Int},a)
@test isa(b,VectorValue{1,Int})

a = (1,2,2,1,3,2)
V = MultiValue{Tuple{3,2},Int,2,6}
b = convert(V,a)
@test isa(b,V)
b = V[a,a,a,]
@test isa(b,Vector{V})

# Misc operations on the type itself

V = VectorValue{3,Int}
@test length(V) == 3
@test size(V) == (3,)

V = VectorValue{3}
@test length(V) == 3
@test size(V) == (3,)

# Custom type printing

v = MultiValue{Tuple{3,2},Float64}(1,2,3,4,5,6)
s = "(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)"
@test string(v) == s

# Misc

M = mutable(VectorValue{3,Int})
@test M == MVector{3,Int}
m = zero(M)
v = VectorValue(m)
@test isa(v,VectorValue{3,Int})

end # module TypesTests


text:
using QuadGK, SpecialFunctions

g(x) = x^(0.5-1) * MathConstants.e^-x
quadgk(g,0,Inf)[1], sqrt(pi), gamma(1/2),  factorial(1/2-1)

max_stars_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_issues_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_forks_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook


text:
using MacroTools
using Match
using Parameters
using Parameters
using AxisArrays
using Unitful

export cohere, component, mask, ncomponents, components, component_means,
  windowing, map_windowing

abstract type CoherenceMethod end
struct CParams{M,P}
  cort::P
  ncomponents::Int
  skipframes::Int
  window::typeof(1.0s)
  delta::typeof(1.0s)
  method::M
end

const Coherence = MetaArray{<:AxisArray,<:CParams}
const CParamLike = Union{CParams,Coherence}

CorticalSpecrtralTemporalResponses.Δt(as::CParamLike) = as.delta

function Base.show(io::IO,::MIME"text/plain",x::Coherence)
  if !get(io, :compact, false)
    println(io,"Coherence Components")
    describe_axes(io,x)
  else
    println(io,string(duration(x))," Coherence Components")
  end
end

ncomponents(x::CParams) = x.ncomponents
ncomponents(x::AbstractArray) = size(x,axisdim(x,Axis{:component}))
components(x::CParams) = 1:ncomponents(x)
components(x::AbstractArray) = axisvalues(AxisArrays.axes(x,Axis{:component}))[1]
component(x::AbstractArray,n) = x[Axis{:component}(n)]

CorticalSpecrtralTemporalResponses.hastimes(x::Coherence) = HasTimes()

function component_means(C)
  mdims = filter(x -> x != axisdim(C,Axis{:component}),1:ndims(C))
  vec(mean(C,dims=mdims))
end

CorticalSpecrtralTemporalResponses.frame_length(params::CParams,x) =
  max(1,floor(Int,params.delta / Δt(x)))

function CParams(x;ncomponents=1,window=1000ms,
                 delta=10ms,method=:nmf,skipframes=0,method_kwds...)
  method = CoherenceMethod(Val{method},method_kwds)

  CParams(getmeta(x), ncomponents, skipframes,
          convert(typeof(1.0s),asseconds(window)), convert(typeof(1.0s),asseconds(delta)), method)
end

windowing(x,params::CParams) =
  windowing(x,length=params.window,step=params.delta)
windowlen(params::CParams,x) = round(Int,params.window/Δt(x))

function nunits(params::CParams,x)
  mapreduce(*,AxisArrays.axes(x)) do ax
    isa(ax,Axis{:time}) || isa(ax,Axis{:rate}) ? 1 : length(ax)
  end
end

cohere(x::MetaUnion{AxisArray};progressbar=true,params...) =
  cohere(x,CParams(x;params...),progressbar)

function cohere_progress(progressbar,x,params)
  if progressbar
    windows = windowing(x,params)
    Progress(length(windows),desc="Temporal Coherence Analysis: ")
  end
end

function cohere(x::MetaUnion{AxisArray},params::CParams,
                progressbar=true,
                progress = cohere_progress(progressbar,x,params))
  @assert axisdim(x,Axis{:time}) == 1
  @assert axisdim(x,Axis{:rate}) == 2
  @assert axisdim(x,Axis{:scale}) == 3
  @assert axisdim(x,Axis{:freq}) == 4
  @assert ndims(x) == 4

  # if we already have components, just wrap up the values with
  # parameters (since we've already computed components)
  if :component in axisnames(x)
    return MetaArray(params,x)
  end

  windows = windowing(x,params)

  K = ncomponents(params)
  C_data = zeros(eltype(params.method,x),length(windows),size(x)[3:end]...,K)
  C = AxisArray(C_data,
                AxisArrays.axes(windows,Axis{:time}),
                AxisArrays.axes(x)[3:end]...,
                Axis{:component}(1:K))

  with_method(params.method,K) do extract
    for (i,w_inds) in enumerate(windows)
      skipped = w_inds[1:1+params.skipframes:end]
      # axis array can't handle skipped indices, so we assume
      # the right dimensionality
      components = extract(x[skipped,:,:,:])
      C[i,Base.axes(components)...] = components

      next!(progress)
    end
  end

  MetaArray(params,C)
end

max_stars_repo_name: JuliaTagBot/AuditoryBistabilityLE

max_issues_repo_name: JuliaTagBot/AuditoryBistabilityLE

max_forks_repo_name: JuliaTagBot/AuditoryBistabilityLE


text:
function distances(resids::Array{Float64,1}, fitteds::Array{Float64})::Array{Float64,2}
    n = length(resids)
    d = zeros(Float64, n, n)
    @inbounds for i in 1:n
        for j in i:n
            if i != j
                p1 = [resids[i], fitteds[i]]
                p2 = [resids[j], fitteds[j]]
                d[i, j] = sqrt(sum((p1 .- p2).^2.0))
                d[j, i] = d[i, j]
            end
        end
    end
    return d
end

function majona(cluster::Hclust)::Float64
    heights = cluster.heights
    return mean(heights) + 1.25 * std(heights)
end

"""

    smr98(setting)

Perform the Sebert, Monthomery and Rollier (1998) algorithm for the given regression setting.

# Arguments
- `setting::RegressionSetting`: RegressionSetting object with a formula and dataset.

# Examples
```julia-repl
julia> reg0001 = createRegressionSetting(@formula(calls ~ year), phones);
julia> smr98(reg0001)
10-element Array{Int64,1}:
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
```

# References
Sebert, David M., Douglas C. Montgomery, and Dwayne A. Rollier. "A clustering algorithm for
identifying multiple outliers in linear regression." Computational statistics & data analysis
27.4 (1998): 461-484.
"""
function smr98(setting::RegressionSetting)
    X, y = @extractRegressionSetting setting
    return smr98(X, y)
end

"""

    smr98(X, y)

Perform the Sebert, Monthomery and Rollier (1998) algorithm for the given regression setting.

# Arguments
- `X::Array{Float64, 2}`: Desing matrix of the linear regression model.
- `y::Array{Float64, 1}`: Response vector of the linear regression model.

# References
Sebert, David M., Douglas C. Montgomery, and Dwayne A. Rollier. "A clustering algorithm for
identifying multiple outliers in linear regression." Computational statistics & data analysis
27.4 (1998): 461-484.
"""

function smr98(X::Array{Float64,2}, y::Array{Float64,1})
    olsreg = ols(X, y)
    stdres = standardize(ZScoreTransform, residuals(olsreg), dims=1)
    stdfit = standardize(ZScoreTransform, predict(olsreg), dims=1)
    n, p = size(X)
    d = distances(stdres, stdfit)
    h = floor((n + p - 1) / 2)
    hcl = hclust(d, linkage=:single)
    majonacrit = majona(hcl)
    clustermappings = cutree(hcl, h=majonacrit)
    uniquemappings = unique(clustermappings)
    for clustid in uniquemappings
        cnt = count(x -> x == clustid, clustermappings)
        if cnt >= h
            return filter(i -> clustermappings[i] != clustid, 1:n)
        end
    end
    return []
end

max_stars_repo_name: angeris/LinRegOutliers

max_issues_repo_name: angeris/LinRegOutliers

max_forks_repo_name: angeris/LinRegOutliers


text:
# VARTYPE = DFGVariableSummary
# FACTYPE = DFGFactorSummary

dfg = LightDFG{NoSolverParams, VARTYPE, FACTYPE}()
DistributedFactorGraphs.DFGVariableSummary(label::Symbol) = DFGVariableSummary(label, DistributedFactorGraphs.now(localzone()), Set{Symbol}(), Dict{Symbol, MeanMaxPPE}(), :Pose2, Dict{Symbol,AbstractDataEntry}())
DistributedFactorGraphs.DFGFactorSummary(label::Symbol) = DFGFactorSummary(label, DistributedFactorGraphs.now(localzone()), Set{Symbol}(), Symbol[])

DistributedFactorGraphs.DFGVariableSummary(label::Symbol, ::VariableNodeData{T}) where T = DFGVariableSummary(label, DistributedFactorGraphs.now(localzone()), Set{Symbol}(), Dict{Symbol, MeanMaxPPE}(), Symbol(T), Dict{Symbol,AbstractDataEntry}())
DistributedFactorGraphs.SkeletonDFGVariable(label::Symbol, args...) = SkeletonDFGVariable(label)

dfg = LightDFG{NoSolverParams, VARTYPE, FACTYPE}()
v1 = VARTYPE(:a)
v2 = VARTYPE(:b)
v3 = VARTYPE(:c)
f0 = FACTYPE(:af1)
f1 = FACTYPE(:abf1)
f2 = FACTYPE(:bcf1)
append!(f2._variableOrderSymbols, [:b,:c])

union!(v1.tags, [:VARIABLE, :POSE])
union!(v2.tags, [:VARIABLE, :LANDMARK])
union!(f1.tags, [:FACTOR])

@testset "Variables and Factors CRUD and SET" begin
    VariablesandFactorsCRUD_SET!(dfg,v1,v2,v3,f0,f1,f2)
end

# Gets
@testset "Gets, Sets, and Accessors" begin
    global dfg,v1,v2,f1

    @test getLabel(v1) == v1.label
    @test getTags(v1) == v1.tags

    @test getLabel(f1) == f1.label
    @test getTags(f1) == f1.tags

    if VARTYPE == DFGVariableSummary
        @test getTimestamp(v1) == v1.timestamp
        @test getVariablePPEDict(v1) == v1.ppeDict
        @test_throws KeyError getVariablePPE(v1, :notfound)
        @test getVariableTypeName(v1) == :Pose2

        # FACTYPE == DFGFactorSummary
        testTimestamp = now(localzone())
        v1ts = setTimestamp(v1, testTimestamp)
        @test getTimestamp(v1ts) == testTimestamp
        #follow with updateVariable!(fg, v1ts)
        # setTimestamp!(v1, testTimestamp) not implemented, we can do an setTimestamp() updateVariable!() for a setTimestamp!(dfg, v1, testTimestamp)
        @test_throws MethodError setTimestamp!(v1, testTimestamp)

        f1ts = setTimestamp(f1, testTimestamp)
        @test !(f1ts === f1)
        @test getTimestamp(f1ts) == testTimestamp
        @test_throws MethodError setTimestamp!(v1, testTimestamp)
    end

end

@testset "Updating Nodes" begin
    VARTYPE == DFGVariableSummary && PPETestBlock!(dfg, v1)
end

@testset "Adjacency Matrices" begin
    fg = LightDFG{NoSolverParams, VARTYPE, FACTYPE}()
    addVariable!(fg, VARTYPE(:a))
    addVariable!(fg, VARTYPE(:b))
    addFactor!(fg,  [:a,:b], FACTYPE(:abf1))
    addVariable!(fg, VARTYPE(:orphan))

    AdjacencyMatricesTestBlock(fg)
end

@testset "Getting Neighbors" begin
    GettingNeighbors(LightDFG{NoSolverParams, VARTYPE, FACTYPE}, VARTYPE=VARTYPE, FACTYPE=FACTYPE)
end

@testset "Building Subgraphs" begin
    BuildingSubgraphs(LightDFG{NoSolverParams, VARTYPE, FACTYPE}, VARTYPE=VARTYPE, FACTYPE=FACTYPE)
end

@testset "Producing Dot Files" begin
    ProducingDotFiles(LightDFG{NoSolverParams, VARTYPE, FACTYPE}, VARTYPE=VARTYPE, FACTYPE=FACTYPE)
end

@testset "Connectivity Test" begin
     ConnectivityTest(LightDFG{NoSolverParams, VARTYPE, FACTYPE}, VARTYPE=VARTYPE, FACTYPE=FACTYPE)
end


text:
function show(io::IO, x::ULogarithmic)
  print(io, "exp(")
  show(io, x.log)
  print(io, ")")
end

function show(io::IO, x::Logarithmic)
  x.signbit && print(io, "-")
  show(io, x.abs)
end

function show(io::IO, x::CLogarithmic)
	print(io, "exp(")
	show(io, log(x))
	print(io, ")")
end

write(io::IO, x::ULogarithmic) = write(io, x.log)
write(io::IO, x::Logarithmic) = write(io, x.abs, x.signbit)
write(io::IO, x::CLogarithmic) = write(io, x.abs, x.angle)

read(io::IO, ::Type{ULogarithmic{T}}) where {T} = uexp(T, read(io, T))
read(io::IO, ::Type{Logarithmic{T}}) where {T} = Logarithmic{T}(read(io, ULogarithmic{T}), read(io, Bool))
read(io::IO, ::Type{CLogarithmic{T}}) where {T} = CLogarithmic{T}(read(io, ULogarithmic{T}), read(io, T))


text:
function new_spectral_element_phs(Nel,Npol,a,b)
	dx = (b-a)/Nel
	ph = discrete_phs(Npol,0.,dx);
	zi = ph.disc_data.flow.xi;
	wi = ph.disc_data.flow.wi;
	zvec = zeros(length(zi)*Nel)
	wvec = zeros(length(wi)*Nel)

	phfull = ph
	neworder = (Nel-1)*Npol*2 + collect(1:Npol)
	for e = 2:Nel
		phfull = PortHamiltonian.coupled_gyrator(phfull,[2],ph,[1],1)
		for ii = (Nel-e)*Npol*2 + collect(1:Npol)
			push!(neworder,ii)
		end
	end
	neworder = [neworder;neworder+Npol]
	phfull.J = phfull.J[neworder,neworder]
	phfull.B = phfull.B[neworder,:]
	return phfull

end

function new_spectral_element_phs_golo(Nel,alfa,a,b)
	dx = (b-a)/Nel
	ph = Phs([0 -1/alfa;1/alfa 0], [1/alfa 0;0. -1/alfa], [0 -(1-alfa)/alfa;-(alfa-1)/alfa 0], eye(2)/dx)
	Npol = 1
	phfull = ph
	neworder = (Nel-1)*Npol*2 + collect(1:Npol)
	for e = 2:Nel
		phfull = PortHamiltonian.coupled_gyrator(phfull,[2],ph,[1],1)
		for ii = (Nel-e)*Npol*2 + collect(1:Npol)
			push!(neworder,ii)
		end
	end
	neworder = [neworder;neworder+Npol]
	phfull.J = phfull.J[neworder,neworder]
	phfull.B = phfull.B[neworder,:]
	return phfull

end

function new_block_spectral_element_phs(Nel,Npol,a,b)
	dx = (b-a)/Nel
	ph = discrete_phs(Npol,0.,dx);
	zi = ph.disc_data.flow.xi;
	wi = ph.disc_data.flow.wi;
	zvec = zeros(length(zi)*Nel)
	wvec = zeros(length(wi)*Nel)
	blockph = Phs([0 -1;1 0], [1 0;0. -1], zeros(2,2), eye(2)*1e5)

	phfull = ph
	neworder = (Nel-1)*Npol*2 + collect(1:Npol)
	for e = 2:Nel
		phfull = PortHamiltonian.coupled_gyrator(phfull,[2],blockph,[1],1)
		phfull = PortHamiltonian.coupled_gyrator(phfull,[2],ph,[1],1)
		for ii = (Nel-e)*Npol*2 + collect(1:Npol)
			push!(neworder,ii)
		end
	end
	#neworder = [neworder;neworder+Npol]
	#phfull.J = phfull.J[neworder,neworder]
	#phfull.B = phfull.B[neworder,:]
	return phfull

end

type spectral_element_phs
	phs::Phs

	function spectral_element_phs(Nel,Npol,a,b)
	# creates a "spectral element" phs model for
	# first order derivative PHS
	# Npol: is the polynomial approximation order
	# Nel: is the number of elements
	# (a,b): is the domain interval

	# to do:
	# * matrices B and D
	# * create a Hamiltonian/grad method or something like that
		this = new();
		dx = (b-a)/Nel;
		xpoints = linspace(a,b,Nel+1);
		ph = discrete_phs(Npol,0.,dx);
		zi = ph.disc_data.flow.xi;
		wi = ph.disc_data.flow.wi;
		zvec = zeros(length(zi)*Nel)
		wvec = zeros(length(wi)*Nel)
		J = zeros(2*length(wi)*Nel, 2*length(wi)*Nel)
		alpha1_index = Array(Int, length(wi)*Nel,1)
		alpha2_index = Array(Int, length(wi)*Nel,1)

		for e = 1:Nel
			ze = zi + xpoints[e]
			zvec[1+length(zi)*(e-1):length(zi)*e] = ze;
			println(wi, 1+length(zi)*(e-1):length(zi)*e)
			wvec[1+length(zi)*(e-1):length(zi)*e] = wi;
			J[1+2*length(zi)*(e-1):2*length(zi)*e,1+2*length(zi)*(e-1):2*length(zi)*e] = ph.J;
			for ei = (e+1):Nel
				J[1+2*length(zi)*(e-1):2*length(zi)*e,1+2*length(zi)*(ei-1):2*length(zi)*(ei)] = -(-ph.D[2,1])^(ei-e+1)*ph.B[:,1]*ph.B[:,2]';
			end
			for ei = 1:(e-1)
				J[1+2*length(zi)*(e-1):2*length(zi)*e,1+2*length(zi)*(ei-1):2*length(zi)*(ei)] = (ph.D[1,2])^(ei-e+1)*ph.B[:,2]*ph.B[:,1]';
			end
			alpha1_index[1+length(zi)*(e-1):length(zi)*e] = [(1:length(zi))+length(zi)*2*(e-1)];
			alpha2_index[1+length(zi)*(e-1):length(zi)*e] = (1:length(zi))+length(zi)*(2*e-1);
		end

		a = alpha1_index;
		b = alpha2_index;
		Jn = J[[a[:];b[:]],[a[:];b[:]]]
		Qn = sparse(diagm(wvec[:],0));
		Qn = blkdiag(Qn,Qn);
		return Jn,Qn,a,b,ph.D
	end
end

max_stars_repo_name: flavioluiz/PortHamiltonian

max_issues_repo_name: flavioluiz/PortHamiltonian

max_forks_repo_name: flavioluiz/PortHamiltonian


text:
export NLoptSolver
immutable NLoptSolver <: SolverInterface.AbstractMathProgSolver
    algorithm::Symbol
    stopval::Real
    ftol_rel::Real
    ftol_abs::Real
    xtol_rel::Real
    xtol_abs
    constrtol_abs::Real
    maxeval::Integer
    maxtime::Real
    initial_step
    population::Integer
    seed
    vector_storage::Integer
end

function NLoptSolver(;algorithm::Symbol=:none, stopval::Real=NaN,
    ftol_rel::Real=1e-7, ftol_abs::Real=NaN, xtol_rel::Real=1e-7,
    xtol_abs=nothing, constrtol_abs=1e-7,
    maxeval::Integer=0, maxtime::Real=0, initial_step=nothing,
    population::Integer=0, seed=nothing, vector_storage::Integer=0)
    if algorithm == :none
        error("Must specify an algorithm for NLoptSolver")
    end
    return NLoptSolver(algorithm, stopval, ftol_rel, ftol_abs, xtol_rel,
        xtol_abs, constrtol_abs, maxeval, maxtime, initial_step, population, seed,
        vector_storage)
end

type NLoptMathProgModel <: SolverInterface.AbstractNonlinearModel
    algorithm::Symbol
    opt # can't create Opt object on construction because it needs problem dimensions
    x::Vector{Float64}
    objval::Float64
    status::Symbol
    # options...
    stopval::Real
    ftol_rel::Real
    ftol_abs::Real
    xtol_rel::Real
    xtol_abs
    constrtol_abs::Real
    maxeval::Integer
    maxtime::Real
    initial_step
    population::Integer
    seed
    vector_storage::Integer
end

SolverInterface.NonlinearModel(s::NLoptSolver) = NLoptMathProgModel(s.algorithm, nothing, Float64[], NaN, :NotSolved, s.stopval, s.ftol_rel, s.ftol_abs, s.xtol_rel, s.xtol_abs, s.constrtol_abs, s.maxeval, s.maxtime, s.initial_step, s.population, s.seed, s.vector_storage)

function SolverInterface.loadproblem!(m::NLoptMathProgModel, numVar::Integer, numConstr::Integer, x_l, x_u, g_lb, g_ub, sense::Symbol, d::SolverInterface.AbstractNLPEvaluator)

    (sense == :Min || sense == :Max) || error("Unrecognized sense $sense")
    m.opt = Opt(m.algorithm, numVar)

    # load parameters
    stopval!(m.opt, m.stopval)
    if !isnan(m.ftol_rel)
        ftol_rel!(m.opt, m.ftol_rel)
    end
    if !isnan(m.ftol_abs)
        ftol_abs!(m.opt, m.ftol_abs)
    end
    if !isnan(m.xtol_rel)
        xtol_rel!(m.opt, m.xtol_rel)
    end
    if m.xtol_abs != nothing
        xtol_abs!(m.opt, m.xtol_abs)
    end
    maxeval!(m.opt, m.maxeval)
    maxtime!(m.opt, m.maxtime)
    if m.initial_step != nothing
        initial_step!(m.opt, m.initial_step)
    end
    population!(m.opt, m.population)
    if isa(m.seed, Integer)
        NLopt.srand(m.seed)
    end
    vector_storage!(m.opt, m.vector_storage)

    lower_bounds!(m.opt, x_l)
    upper_bounds!(m.opt, x_u)

    eqidx = find(g_lb .== g_ub) # indices of equalities
    ineqidx = find(g_lb .!= g_ub)

    # map from eqidx/ineqidx to index in equalities/inequalities
    constrmap = Array(Int,numConstr)
    for i in 1:length(eqidx)
        constrmap[eqidx[i]] = i
    end
    ineqcounter = 1
    for i in 1:length(ineqidx)
        k = ineqidx[i]
        constrmap[k] = ineqcounter
        if isinf(g_lb[k]) || isinf(g_ub[k])
            ineqcounter += 1
        else # constraint has bounds on both sides, keep room for it
            ineqcounter += 2
        end
    end
    numineq = ineqcounter-1
    numeq = length(eqidx)

    isderivativefree = string(m.algorithm)[2] == 'N'
    if isderivativefree
        requested_features = Symbol[]
    else
        requested_features = [:Grad, :Jac]
    end

    SolverInterface.initialize(d, requested_features)

    function f(x::Vector, grad::Vector)
        if length(grad) > 0
            SolverInterface.eval_grad_f(d, grad, x)
        end
        return SolverInterface.eval_f(d, x)
    end
    if sense == :Min
        min_objective!(m.opt, f)
    else
        max_objective!(m.opt, f)
    end

    Jac_I,Jac_J = SolverInterface.jac_structure(d)
    Jac_val = zeros(length(Jac_I))
    g_vec = zeros(numConstr)

    # somewhat inefficient because we evaluate g and the constraints
    # once for equalities and once for inequalities

    function g_eq(result::Vector, x::Vector, jac::Matrix)
        if length(jac) > 0
            fill!(jac, 0.0)
            SolverInterface.eval_jac_g(d, Jac_val, x)
            for k in 1:length(Jac_val)
                row = Jac_I[k]
                if g_lb[row] == g_ub[row]
                    jac[Jac_J[k],constrmap[row]] += Jac_val[k]
                end
            end
        end
        SolverInterface.eval_g(d, g_vec, x)
        for (ctr,idx) in enumerate(eqidx)
            result[ctr] = g_vec[idx] - g_ub[idx]
        end
    end

    equality_constraint!(m.opt, g_eq, fill(m.constrtol_abs,numeq))

    # inequalities need to be massaged a bit
    # f(x) <= u   =>  f(x) - u <= 0
    # f(x) >= l   =>  l - f(x) <= 0

    function g_ineq(result::Vector, x::Vector, jac::Matrix)
        if length(jac) > 0
            fill!(jac, 0.0)
            SolverInterface.eval_jac_g(d, Jac_val, x)
            for k in 1:length(Jac_val)
                row = Jac_I[k]
                g_lb[row] == g_ub[row] && continue
                if isinf(g_lb[row]) # upper bound
                    jac[Jac_J[k],constrmap[row]] += Jac_val[k]
                elseif isinf(g_ub[row]) # lower bound
                    jac[Jac_J[k],constrmap[row]] -= Jac_val[k]
                else
                    # boxed
                    jac[Jac_J[k],constrmap[row]] += Jac_val[k]
                    jac[Jac_J[k],constrmap[row]+1] -= Jac_val[k]
                end
            end
        end
        SolverInterface.eval_g(d, g_vec, x)
        for row in 1:numConstr
            g_lb[row] == g_ub[row] && continue
            if isinf(g_lb[row])
                result[constrmap[row]] = g_vec[row] - g_ub[row]
            elseif isinf(g_ub[row])
                result[constrmap[row]] = g_lb[row] - g_vec[row]
            else
                result[constrmap[row]] = g_vec[row] - g_ub[row]
                result[constrmap[row]+1] = g_lb[row] - g_vec[row]
            end
        end
    end

    inequality_constraint!(m.opt, g_ineq, fill(m.constrtol_abs, numineq))
end

function SolverInterface.setwarmstart!(m::NLoptMathProgModel,x)
    m.x = copy(float(x))
end

function SolverInterface.optimize!(m::NLoptMathProgModel)
    isa(m.opt, Opt) || error("Must load problem before solving")
    (optf,optx,ret) = optimize!(m.opt, m.x)
    m.objval = optf
    m.status = ret
end

function SolverInterface.status(m::NLoptMathProgModel)
    if m.status == :SUCCESS || m.status == :FTOL_REACHED || m.status == :XTOL_REACHED
        return :Optimal
    elseif m.status == :ROUNDOFF_LIMITED
        return :Suboptimal
    elseif m.status in (:STOPVAL_REACHED,:MAXEVAL_REACHED,:MAXTIME_REACHED)
        return :UserLimit
    else
        error("Unknown status $(m.status)")
    end
end

SolverInterface.getsolution(m::NLoptMathProgModel) = m.x
SolverInterface.getobjval(m::NLoptMathProgModel) = m.objval


text:
"""
    znlsolve(args...; kwargs...)

It is a Zygote-compatible version of `nlsolve(args...; kwargs...)`.

See:
https://github.com/JuliaNLSolvers/NLsolve.jl/issues/205#issuecomment-524764679
"""
znlsolve(args...; converged=nothing, adlinsolve=nothing, kwargs...) =
    NLsolve.nlsolve(args...; kwargs...)

@adjoint znlsolve(
    f,
    j,
    x0;
    converged = NLsolve.converged,
    adlinsolve = LinSolvePinvFallback(eltype(x0)),
    kwargs...,
) =
    let result = znlsolve(f, j, x0; kwargs...)
        converged(result) ||
            throw(NLsolveNotConvergedError(f, j, x0, kwargs, result))
        result, function(vresult)
            # This backpropagator returns (- v' (df/dx)⁻¹ (df/dp))'
            v = vresult[].zero
            x = result.zero
            J = j(x)
            _, back = pullback(f -> f(x), f)
            \ = adlinsolve
            return (back(-(J' \ v))[1], nothing, nothing)
        end
    end

struct NLsolveNotConvergedError <: Exception
    f
    j
    x0
    kwargs
    result
end

function Base.showerror(io::IO, err::NLsolveNotConvergedError)
    println(io, "NLsolveNotConvergedError")
    show(io, "text/plain", err.result)
end

"""
    nlsolveargs(err::NLsolveNotConvergedError) -> (args, kwargs)

Return arguments such that `nsolve(args...; kwargs...)` would reproduce
the same result.
"""
nlsolveargs(err::NLsolveNotConvergedError) =
    ((err.f, err.j, err.x0), err.kwargs)

struct LinSolvePinvFallback{T <: Real}
    det_threshold::T
    pinv_atol::T
    pinv_rtol::T
end

LinSolvePinvFallback(
    T::Type = Float64;
    det_threshold = sqrt(eps(T)),
    pinv_atol = zero(T),
    pinv_rtol = sqrt(eps(T)),
) = LinSolvePinvFallback{T}(
    det_threshold,
    pinv_atol,
    pinv_rtol,
)

function (linsolve::LinSolvePinvFallback)(A, B)
    F = lu(A)
    if abs(det(F)) > linsolve.det_threshold
        return F \ B
    end
    return pinv(A; atol=linsolve.pinv_atol, rtol=linsolve.pinv_rtol) * B
end


text:
module MTKHelpers

using ModelingToolkit, DifferentialEquations
using StaticArrays, LabelledArrays
using Requires: @require
using NamedArrays
#using Infiltrator

export symbol, statesyms, parsyms, strip_namespace, embed_system, cm2inch

export ProblemParSetter, count_states, count_par, count_paropt,
    paroptsyms, statesyms, parsyms,
    update_statepar, get_paropt, get_paropt_labeled, label_paropt, label_par, label_state

export smoothstep

export pdf_figure, series_sol!

export getlast

# extending
import Base: merge

function __init__()
    @require CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" include("requires_cairommakie.jl")
  end

include("util.jl")
include("problemparsetter.jl")
include("smoothstep.jl")
include("solution.jl")

end

max_stars_repo_name: bgctw/MTKHelpers

max_issues_repo_name: bgctw/MTKHelpers

max_forks_repo_name: bgctw/MTKHelpers


text:
abstract type AbstractMetaNexus{T} <: AbstractNexus{T} end

function show(io::IO, g::AbstractMetaNexus{T}) where {T}
    dir = is_directed(g) ? "directed" : "undirected"
    print(io, "{$(nn(g)),$(na(g))} $dir $T metagraph")
end

# FORWARD DARI INTERFACE.JL
@forward AbstractMetaNexus.core eltype

@forward AbstractMetaNexus.core nn
@forward AbstractMetaNexus.core na
@forward AbstractMetaNexus.core fadj
@forward AbstractMetaNexus.core nodes

has_node(g::AbstractMetaNexus{T}, n::T) where {T} = has_node(g.core, n)
has_arc(g::AbstractMetaNexus{T}, u::T, v::T, key::Int) where {T} =
    has_arc(g.core, u, v, key)

# FORWARD DARI GRAPH.JL & DIGRAPH.JL
add_arc!(g::AbstractMetaNexus, x...) = add_arc!(g.core, x...)
rem_arc!(g::AbstractMetaNexus, x...) = begin
    rem_arc!(g.core, x...)
    clean_attribs!(g)
end

add_node!(g::AbstractMetaNexus, x...) = add_node!(g.core, x...)
rem_node!(g::AbstractMetaNexus, x...) = begin
    rem_node!(g.core, x...)
    clean_attribs!(g)
end

# FORWARD DARI ARC.JL
arcs(g::AbstractMetaNexus, x...) = arcs(g.core, x...)

add_arc!(g::AbstractMetaNexus{T}, a::Arc{T}) where {T} = add_arc!(g.core, a)
rem_arc!(g::AbstractMetaNexus{T}, a::Arc{T}) where {T} = begin
    rem_arc!(g.core, a)
    clean_attribs!(g)
end

has_arc(g::AbstractMetaNexus{T}, a::Arc{T}) where {T} = has_arc(g.core, a)

function clean_attribs!(g::AbstractMetaNexus)
    for n in keys(g.nprops)
        n in nodes(g) || clear_props!(g, n)
    end # get all nodes in nprops not in nodes
    for a in keys(g.aprops)
        a in arcs(g) || clear_props!(g, a)
    end # get all arcs in aprops not in arcs
end

"""
    props(g, n)
    props(g, a)
    props(g, s, t, key)

Return a dictionary of all metadata from node `n`, or arc `a`
(optionally referenced by source node `s` and target node `t`).
"""
props(g::AbstractMetaNexus{T}, n::T) where {T} = get(Dict{Symbol,Any}, g.nprops, n)
props(g::AbstractMetaNexus{T}, a::Arc{T}) where {T} = get(Dict{Symbol,Any}, g.aprops, a)
props(g::AbstractMetaNexus{T}, u::T, v::T, key::Int) where {T} = props(g, Arc(u, v, key))
# props for arc is not dependent on directedness krn di graph ada u--v dan v--u
# yg perlu dipastikan adalah atribut u--v dan v--u di graph selalu sama

"""
    get_prop(g, n, prop)
    get_prop(g, a, prop)
    get_prop(g, s, t, key, prop)

Return the property `prop` defined for node `n`, or arc `a`
(optionally referenced by source node `s` and target node `t`).
"""
get_prop(g::AbstractMetaNexus{T}, n::T, prop::Symbol) where {T} = props(g, n)[prop]
get_prop(g::AbstractMetaNexus{T}, a::Arc{T}, prop::Symbol) where {T} = props(g, a)[prop]
get_prop(g::AbstractMetaNexus{T}, u::T, v::T, key::Int, prop::Symbol) where {T} =
    props(g, Arc(u, v, key))[prop]

"""
    has_prop(g, n, prop)
    has_prop(g, a, prop)
    has_prop(g, s, t, key, prop)

Return true if the property `prop` is defined for node `n`, or
arc `a` (optionally referenced by source node `s` and target node `t`).
"""
has_prop(g::AbstractMetaNexus{T}, n::T, prop::Symbol) where {T} =
    haskey(props(g, n), prop)
has_prop(g::AbstractMetaNexus{T}, a::Arc{T}, prop::Symbol) where {T} =
    haskey(props(g, a), prop)
has_prop(g::AbstractMetaNexus{T}, u::T, v::T, key::Int, prop::Symbol) where {T} =
    haskey(props(g, Arc(u, v, key)), prop)

_hasdict(g::AbstractMetaNexus{T}, n::T) where {T} = haskey(g.nprops, n)
_hasdict(g::AbstractMetaNexus{T}, a::Arc{T}) where {T} = haskey(g.aprops, a)

"""
    set_props!(g, n, dict)
    set_props!(g, a, dict)
    set_props!(g, s, t, key, dict)

Bulk set (merge) properties contained in `dict` with node `n`, or
arc `a` (optionally referenced by source node `s` and target node `t`).
"""
function set_props!(g::AbstractMetaNexus{T}, n::T, d::Dict) where {T}
    if has_node(g, n)
        !_hasdict(g, n) ? g.nprops[n] = d : merge!(g.nprops[n], d)
        return true
    else
        return false
    end
end
# set_props! on arcs is dependent on directedness
# why? mirip dengan add_arc, buat graph harus ada proses bikin u--v dan v--u sekaligus

set_prop!(g::AbstractMetaNexus{T}, n::T, prop::Symbol, val) where {T} =
    set_props!(g, n, Dict(prop => val))
set_prop!(g::AbstractMetaNexus{T}, a::Arc{T}, prop::Symbol, val) where {T} =
    set_props!(g, a, Dict(prop => val))
set_prop!(g::AbstractMetaNexus{T}, u::T, v::T, key::Int, prop::Symbol, val) where {T} =
    set_prop!(g, Arc(u, v, key), prop, val)

"""
    rem_prop!(g, n, prop)
    rem_prop!(g, a, prop)
    rem_prop!(g, s, t, prop)

Remove property `prop` from node `n`, or arc `a`
(optionally referenced by source node `s` and target node `t`).
"""
rem_prop!(g::AbstractMetaNexus{T}, n::T, prop::Symbol) where {T} =
    delete!(g.nprops[n], prop)
rem_prop!(g::AbstractMetaNexus{T}, u::T, v::T, key::Int, prop::Symbol) where {T} =
    rem_prop!(g, Arc(u, v, key), prop)
# rem_prop! on arcs is dependent on directedness
# why? mirip dengan rem_arc, buat graph harus ada proses hapus u--v dan v--u sekaligus

clear_props!(g::AbstractMetaNexus{T}, n::T) where {T} =
    _hasdict(g, n) && delete!(g.nprops, n)
clear_props!(g::AbstractMetaNexus{T}, u::T, v::T, key::Int) where {T} =
    clear_props!(g, Arc(u, v, key))
# clear_props! on arcs is dependent on directedness
# why? mirip dengan rem_arc, buat graph harus ada proses hapus u--v dan v--u sekaligus

filter_arcs(g::AbstractMetaNexus, fn::Function) =
    Iterators.filter(a -> fn(g, a), arcs(g))
filter_arcs(g::AbstractMetaNexus, prop::Symbol) =
    filter_arcs(g, (g, a) -> has_prop(g, a, prop))
filter_arcs(g::AbstractMetaNexus, prop::Symbol, val) =
    filter_arcs(g, (g, a) -> has_prop(g, a, prop) && get_prop(g, a, prop) == val)

filter_nodes(g::AbstractMetaNexus, fn::Function) =
    Iterators.filter(n -> fn(g, n), nodes(g))
filter_nodes(g::AbstractMetaNexus, prop::Symbol) =
    filter_nodes(g, (g, n) -> has_prop(g, n, prop))
filter_nodes(g::AbstractMetaNexus, prop::Symbol, val) =
    filter_nodes(g, (g, n) -> has_prop(g, n, prop) && get_prop(g, n, prop) == val)

# getindex
getindex(g::AbstractMetaNexus{T}, n::T) where {T} = props(g, n)
getindex(g::AbstractMetaNexus{T}, a::Arc{T}) where {T} = props(g, a)
getindex(g::AbstractMetaNexus{T}, u::T, v::T, key::Int) where {T} =
    getindex(g, Arc(u, v, key))