text:
# Global variables
const epsilon = 10.0^(-10);
const dx = 0.25;
const dt = 0.02;
const total_rate = 40;

# === Upgrading from ForwardDiff v0.1 to v0.2
# instead of ForwardDiff.GradientNumber and ForwardDiff.HessianNumber,
# we will use ForwardDiff.Dual

convert(::Type{Float64}, x::ForwardDiff.Dual) = Float64(x.value)
function convert(::Array{Float64}, x::Array{ForwardDiff.Dual})
    y = zeros(size(x));
    for i in 1:prod(size(x))
        y[i] = convert(Float64, x[i])
    end
    return y
end

immutable NumericPair{X,Y} <: Number
  x::X
  y::Y
end
Base.isless(a::NumericPair, b::NumericPair) = (a.x<b.x) || (a.x==b.x && a.y<b.y)

"""
function bin_centers = make_bins(B, dx, binN)

Makes a series of points that will indicate bin centers. The first and
last points will indicate sticky bins. No "bin edges" are made-- the edge
between two bins is always implicity at the halfway point between their
corresponding centers. The center bin is always at x=0; bin spacing
(except for last and first bins) is always dx; and the position
of the first and last bins is chosen so that |B| lies exactly at the
midpoint between 1st (sticky) and 2nd (first real) bins, as well as
exactly at the midpoint between last but one (last real) and last
(sticky) bins.

Playing nice with ForwardDiff means that the *number* of bins must be predetermined.
So this function will not actually set the number of bins; what it'll do is determine their
locations. To accomplish this separation, the function uses as a third parameter binN,
which should be equal to the number of bins with bin centers > 0, as follows:
   binN = ceil(B/dx)
and then the total number of bins will be 2*binN+1, with the center one always corresponding
to position zero. Use non-differentiable types for B and dx for this to work.
"""
function make_bins{T}(bins::Vector{T}, B, dx::T, binN)
    cnt = 1
    for i=-binN:binN
        bins[cnt] = i*dx
        cnt = cnt+1
    end

    if binN*dx == B
        bins[end] = B + dx
        bins[1] = -B - dx
    else
        bins[end] = 2*B - (binN-1)*dx
        bins[1] = -2*B + (binN-1)*dx
    end
end

"""
function F = Fmatrix([sigma, lambda, c], bin_centers)

Uses globals
    dt
    dx
    epsilon       (=10.0^-10)

Returns a square Markov matrix of transition probabilities.
Plays nice with ForwardDiff-- that is why bin_centers is a global vector (so that the rem
operations that go into defining the bins, which ForwardDiff doesn't know how to deal with,
stay outside of this differentiable function)

sigma  should be in (accumulator units) per (second^(1/2))
lambda should be in s^-1
c      should be in accumulator units per second
bin_centers should be a vector of the centers of all the bins. Edges will be at midpoints
       between the centers, and the first and last bin will be sticky.

dx is not used inside Fmatrix, because bin_centers specifies all we need to know.
dt *is* used inside Fmatrix, to convert sigma, lambda, and c into timestep units
"""
function Fmatrix{T}(F::AbstractArray{T,2},params::Vector, bin_centers)
    sigma2 = params[1];
    lam   = params[2];
    c     = params[3];

    sigma2_sbin = convert(Float64, sigma2)
    # println(typeof(sigma2))
    # println(size(sigma2))
    # println(sigma2)
    # println("Converted ", sigma2_sbin)
    # println(typeof(sigma2_sbin))

    n_sbins = max(70, ceil(10*sqrt(sigma2_sbin)/dx))

    F[1,1] = 1;
    F[end,end] = 1;

    swidth = 5.*sqrt(sigma2_sbin)

    sbinsize = swidth/n_sbins #sbins[2] - sbins[1]
    base_sbins    = collect(-swidth:sbinsize:swidth)

    ps       = exp(-base_sbins.^2/(2*sigma2)) # exp(Array) -> exp.(x)
    ps       = ps/sum(ps);

    sbin_length = length(base_sbins)
    binN = length(bin_centers)

    mu = 0.
    for j in 2:binN-1
        if lam == 0
            mu = bin_centers[j] + c*dt#(exp(lam*dt))
        else
            mu = (bin_centers[j] + c/lam)*exp(lam*dt) - c/lam
        end

        for k in 1:sbin_length
            sbin = (k-1)*sbinsize + mu - swidth

            if sbin <= bin_centers[1] #(bin_centers[1] + bin_centers[2])/2
                F[1,j] = F[1,j] + ps[k]
            elseif bin_centers[end] <= sbin#(bin_centers[end]+bin_centers[end-1])/2 <= sbins[k]
                F[end,j] = F[end,j] + ps[k]
            else # more condition
                if (sbin > bin_centers[1] && sbin < bin_centers[2])
                    lp = 1; hp = 2;
                elseif (sbin > bin_centers[end-1] && sbin < bin_centers[end])
                    lp = binN-1; hp = binN;
                else
                    lp = floor(Int,((sbin-bin_centers[2])/dx)) + 2#find(bin_centers .<= sbins[k])[end]
                    hp = ceil(Int,((sbin-bin_centers[2])/dx)) + 2#lp+1#Int(ceil((sbins[k]-bin_centers[2])/dx) + 1);
                end

                if lp == hp
                    F[lp,j] = F[lp,j] + ps[k]
                else
                    F[hp,j] = F[hp,j] + ps[k]*(sbin - bin_centers[lp])/(bin_centers[hp] - bin_centers[lp])
                    F[lp,j] = F[lp,j] + ps[k]*(bin_centers[hp] - sbin)/(bin_centers[hp] - bin_centers[lp])
                end
            end
        end
    end
end

"""
version with inter-click interval(ici) for c_eff_net / c_eff_tot (followed the matlab code)
(which was using dt for c_eff)

function logProbRight(params::Vector)

    RightClickTimes   vector with elements indicating times of right clicks
    LeftClickTimes    vector with elements indicating times of left clicks
    Nsteps number of timesteps to simulate

Takes params
    sigma_a = params[1]; sigma_s = params[2]; sigma_i = params[3];
    lambda = params[4]; B = params[5]; bias = params[6];
    phi = params[7]; tau_phi = params[8]; lapse = params[9]

Returns the log of the probability that the agent chose Right.
"""
function logProbRight(RightClickTimes::Array{Float64,1}, LeftClickTimes::Array{Float64,1}, Nsteps::Int
    ;sigma_a = 0.01, sigma_s_R = 0.01, sigma_s_L = 0.01,
    sigma_i = 0.01, lambda = 0., B = 8., bias = 0.,
    phi = 1., tau_phi = 0.02, lapse_R = 0.01, lapse_L = 0.01,
    input_gain_weight = 0.5)

# now it considers 12p/9p function
# we can update the default parameter later

    # check whether sigma_S_L/sigma_S_R are specified
    # 1. set one of them as sigma_s
    if xor(sigma_s_R!=0.01, sigma_s_L!=0.01)
        if sigma_s_R!=0.01
            sigma_s_L=sigma_s_R
        elseif sigma_s_L!=0.01
            sigma_s_R=sigma_s_L
        end
    end

    # same for lapse
    # check whether lapse_L/lapse_R are specified
    # 1. set one of them as lapse
    if xor(lapse_R!=0.01, lapse_L!=0.01)
        if lapse_R!=0.01
            lapse_L=lapse_R
        elseif lapse_L!=0.01
            lapse_R=lapse_L
        end
    end

# function logProbRight(params::Vector, RightClickTimes::Array{Float64,1}, LeftClickTimes::Array{Float64,1}, Nsteps::Int)
#     sigma_a = params[1]; sigma_s_R = params[2]; sigma_s_L = params[3];
#     sigma_i = params[4]; lambda = params[5]; B = params[6]; bias = params[7];
#     phi = params[8]; tau_phi = params[9]; lapse_R = params[10]; lapse_L = params[11];
#     input_gain_weight = params[12];

    if isempty(RightClickTimes) RightClickTimes = zeros(0) end;
    if isempty(LeftClickTimes ) LeftClickTimes  = zeros(0) end;

    NClicks = zeros(Int, Nsteps);
    Lhere  = zeros(Int, length(LeftClickTimes));
    Rhere = zeros(Int, length(RightClickTimes));

    for i in 1:length(LeftClickTimes)
        Lhere[i] = ceil((LeftClickTimes[i]+epsilon)/dt)
    end
    for i in 1:length(RightClickTimes)
        Rhere[i] = ceil((RightClickTimes[i]+epsilon)/dt)
    end

    for i in Lhere
        NClicks[Int(i)] = NClicks[Int(i)]  + 1
    end
    for i in Rhere
        NClicks[Int(i)] = NClicks[Int(i)]  + 1
    end

    # === Upgrading from ForwardDiff v0.1 to v0.2
    # instead of using convert we can use floor(Int, ForwardDiff.Dual) and
    # ceil(Int, ForwardDiff.Dual)

    binN = ceil(Int, B/dx)#Int(ceil(my_B/dx))
    binBias = floor(Int, bias/dx) + binN+1
    binBias_hp = ceil(Int, bias/dx) + binN+1

    if binBias<1 binBias = 1; end
    if binBias>binN*2+1 binBias = binN*2+1; end

    if binBias_hp<1 binBias_hp = 1; end
    if binBias_hp>binN*2+1 binBias_hp = binN*2+1; end

    bin_centers = zeros(typeof(dx), binN*2+1)
    make_bins(bin_centers, B, dx, binN)

    # Visualization
    a_trace = zeros(length(bin_centers), Nsteps)
    c_trace = zeros(1, Nsteps)

    ## biased lapse rate (lapse_R, lapse_L)
    a0 = zeros(typeof(sigma_a),length(bin_centers))
    a0[1] = lapse_L/2;
    a0[end] = lapse_R/2;
    a0[binN+1] = 1-lapse_L/2-lapse_R/2;

    temp_l = [NumericPair(LeftClickTimes[i],-1) for i=1:length(LeftClickTimes)]
    temp_r = [NumericPair(RightClickTimes[i],1) for i=1:length(RightClickTimes)]
    allbups = sort!([temp_l; temp_r])

    if phi == 1
      c_eff = 1.
    else
      c_eff = 0.
    end
    cnt = 0

    Fi = zeros(typeof(sigma_i),length(bin_centers),length(bin_centers))
    Fmatrix(Fi,[sigma_i, 0., 0.0], bin_centers)
    a = Fi*a0;

    a_trace[:,1] = a;

    F0 = zeros(typeof(sigma_a),length(bin_centers),length(bin_centers))
    Fmatrix(F0,[sigma_a*dt, lambda, 0.0], bin_centers)
    for i in 2:Nsteps
        net_input = 0.
        c_eff_tot = 0.
        c_eff_net = 0.
        net_i_input = 0.
        net_c_input = 0.

        if NClicks[i-1]==0
            c_eff_tot = 0.
            c_eff_net = 0.
            a = F0*a
        else
            for j in 1:NClicks[i-1]
                if cnt != 0 || j != 1
                    ici = allbups[cnt+j].x - allbups[cnt+j-1].x

                    c_eff = 1 + (c_eff*phi - 1)*exp(-ici/tau_phi)
                    c_eff_tot = c_eff_tot + c_eff
                    c_eff_net = c_eff_net + c_eff*allbups[cnt+j].y

                    ## (input_gain_weight) 0 to 1 : 0-left, 1-right
                    net_c_input = (c_eff_tot+c_eff_net)/2 # right
                    net_i_input = c_eff_tot-net_c_input # left

                    net_input = 2*input_gain_weight*net_c_input - 2*(1-input_gain_weight)*net_i_input
                elseif cnt==0 && j==1
                    ici = 0.
                    c_eff = 1 + (c_eff*phi - 1)*exp(-ici/tau_phi)

                    c_eff_tot = c_eff_tot + c_eff
                    c_eff_net = c_eff_net + c_eff*allbups[cnt+j].y

                    ## (input_gain_weight) 0 to 1 : 0-left, 1-right
                    # 0.5 is neutral
                    net_c_input = (c_eff_tot+c_eff_net)/2 # right
                    net_i_input = c_eff_tot-net_c_input # left

                    net_input = 2*input_gain_weight*net_c_input - 2*(1-input_gain_weight)*net_i_input
                end
                if j == NClicks[i-1]
                    cnt = cnt+j
                end
            end

            ## biased params added
            net_sigma = sigma_a*dt + (sigma_s_R*net_i_input)/total_rate + (sigma_s_L*net_c_input)/total_rate
            F = zeros(typeof(net_sigma),length(bin_centers),length(bin_centers))
            Fmatrix(F,[net_sigma, lambda, net_input/dt], bin_centers)
            a = F*a

        end

        a_trace[:,i] = a
        c_trace[i] = c_eff*exp(lambda*dt)
    end

    # likelihood of poking right
    if binBias == binBias_hp
      pright = sum(a[binBias+1:end])+a[binBias]/2
    else
      pright = sum(a[binBias+2:end]) +
      a[binBias]*((bin_centers[binBias+1] - bias)/dx/2) +
      a[binBias+1]*(0.5 + (bin_centers[binBias+1] - bias)/dx/2)
    end
    if pright-1 < epsilon && pright > 1
        pright = 1
    end
    if pright < epsilon && pright > 0
        pright = 0
    end

    return log(pright)
end

function LogLikelihood(RightClickTimes::Vector, LeftClickTimes::Vector, Nsteps::Int, rat_choice::Int
    ;kwargs...)
    if rat_choice > 0
        # println("Right")
        return logProbRight(RightClickTimes, LeftClickTimes, Nsteps;
            kwargs...)#make_dict(args, x)...)
    elseif rat_choice < 0
        # println("Left")
        return log(1 - exp(logProbRight(RightClickTimes, LeftClickTimes, Nsteps;
            kwargs...)))#make_dict(args, x)...)))
    end
end

"""
function (LL, LLgrad, LLhessian, bin_centers, bin_times, a_trace) =
    llikey(params, rat_choice, maxT=1, RightPulseTimes=[], LeftPulseTimes=[], dx=0.25, dt=0.02)

Computes the log likelihood according to Bing's model, and returns log likelihood, gradient, and hessian

params is a vector whose elements, in order, are
    sigma_a    square root of accumulator variance per unit time sqrt(click units^2 per second)
    sigma_s    standard deviation introduced with each click (will get scaled by click adaptation)
    sigma_i    square root of initial accumulator variance sqrt(click units^2)
    lambda     1/accumulator time constant (sec^-1). Positive means unstable, neg means stable
    B          sticky bound height (click units)
    bias       where the decision boundary lies (click units)
    phi        click adaptation/facilitation multiplication parameter
    tau_phi    time constant for recovery from click adaptation (sec)
    lapse      2*lapse fraction of trials are decided randomly

rat_choice     should be either "R" or "L"

RETURNS:

"""

# function single_trial(params::Vector, RightClickTimes::Vector, LeftClickTimes::Vector, Nsteps::Int, rat_choice::Int, hess_mode=0::Int)
#     function llikey(params::Vector)
#         logLike(params, RightClickTimes, LeftClickTimes, Nsteps, rat_choice)
#     end

#     if hess_mode > 0
#         result =  HessianResult(params)
#         ForwardDiff.hessian!(result, llikey, params);
#     else
#         result =  GradientResult(params)
#         ForwardDiff.gradient!(result, llikey, params);
#     end

#     LL     = ForwardDiff.value(result)
#     LLgrad = ForwardDiff.gradient(result)

#     if hess_mode > 0
#         LLhessian = ForwardDiff.hessian(result)
#     end

#     if hess_mode > 0
#         return LL, LLgrad, LLhessian
#     else
#         return LL, LLgrad
#     end
# end


text:
using FileIO, Gnuplot, ColorSchemes
using GeometryBasics, LinearAlgebra, Statistics
# based on https://matplotlib.org/matplotblog/posts/custom-3d-engine/
# download this file
# https://matplotlib.org/matplotblog/posts/custom-3d-engine/bunny.obj
bunny = load("bunny.obj")
ptstemp = bunny.position
npts = length(ptstemp)
points = zeros(npts, 3)
for i in 1:npts
    points[i,:] = ptstemp[i]
end
# normalize into a box
mnpts = minimum(points, dims=1)
mxpts = maximum(points, dims=1)
# all the data needed.
verpts = (points .- (mxpts .+ mnpts)./2)./maximum(mxpts .- mnpts)
triface = decompose(TriangleFace{Int32}, bunny)
# just lines and no order
bunnyB = Vector{String}()
for i in 1:length(triface)
    polytri = verpts[triface[i],:]
    x, y = polytri[:,1], polytri[:,2] # polytri[:,3]
    push!(bunnyB, join(string.(x) .* " ".* string.(y), "\n") * "\n")
end
# perpective, views, rotations
function frustum(left, right, bottom, top, znear, zfar)
    M = zeros(Float32, (4, 4))
    M[1, 1] = 2.0 * znear / (right - left)
    M[2, 2] = 2.0 * znear / (top - bottom)
    M[3, 3] = -(zfar + znear) / (zfar - znear)
    M[1, 3] = (right + left) / (right - left)
    M[3, 2] = (top + bottom) / (top - bottom)
    M[3, 4] = -2.0 * znear * zfar / (zfar - znear)
    M[4, 3] = -1.0
    M
end
function perspective(fovy, aspect, znear, zfar)
    h = tan(fovy*π/360) * znear
    w = h * aspect
    return frustum(-w, w, -h, h, znear, zfar)
end
function translate(x, y, z)
    [1 0 0 x; 0 1 0 y; 0 0 1 z; 0 0 0 1]
end
function xrotate(θ)
    t = π * θ / 180
    c, s = cos(t), sin(t)
    [1 0 0 0; 0 c -s 0; 0 s c 0; 0 0 0 1]
end
function yrotate(θ)
    t = π * θ / 180
    c, s = cos(t), sin(t)
    [c 0 s 0; 0 1 0 0; -s 0 c 0; 0 0 0 1]
end
# Model, view, perspective (MVP)
model = xrotate(20) * yrotate(45)
view  = translate(0,0,-3.5)
proj  = perspective(25, 1, 1, 100)
MVP   = proj * view * model
verpts = hcat(verpts, ones(npts)) * MVP'
verpts ./= verpts[:,4]
# zdepth_order
zdepth = zeros(length(triface))
ptsxy = []
for i in 1:length(triface)
    polytri = verpts[triface[i],:]
    x, y = polytri[:,1], polytri[:,2]
    push!(ptsxy, [x,y])
    zdepth[i] = -mean(polytri[:,3])
end
zmin, zmax = minimum(zdepth), maximum(zdepth)
zdepth = (zdepth .- zmin)/(zmax-zmin)
zdepth_order = sortperm(zdepth)
zdepth = zdepth[zdepth_order] # used for the colormap
# polygons to gnuplot
bunnyC = Vector{String}()
for (indx,i) in enumerate(zdepth_order) # order in which polygons should be drawn
    x, y = ptsxy[i][1], ptsxy[i][2]
    push!(bunnyC, join(string.(x) .* " ".* string.(y) .* " " .*
                  string(zdepth[indx]), "\n") * "\n")
end
# let's do an egg
x = -1:0.05:1
y = -1.5:0.05:2
egg(x,y) = x^2 + y^2/(1.4 + y/5)^2
segg = [egg(x,y) for x in x, y in y]
# the bunny !
@gp "set multi layout 1,3 title 'Easter'" :-
@gp :- 2 "set style fill solid 1 noborder" title ="Bunny in color"
@gp :- "set size ratio -1" :-
@gp :- bunnyC "w filledcurves notit lc pal" palette(:spring)
@gp :- "unset colorbox; unset xtics; unset ytics; unset border"
@gp :- 3 "set style fill solid 1 noborder" title ="Bunny lines"
@gp :- "set size ratio -1" :-
@gp :- bunnyB "w l notit lc 'black' lw 0.1" :-
@gp :- "unset xtics; unset ytics; unset border"
@gp :- 1 title = "Egg" :-
@gsp :- x y segg "w l lc palette" palette(:cool) "set view map" :-
@gsp :- "set contour base;set key off" "set auto fix" :-
@gsp :- "set cntrparam levels incremental  0,0.01,1" "unset surface" :-
@gsp :- "set size ratio -1" cbrange =(0,1)
@gp :- "unset colorbox; unset xtics; unset ytics; unset border"
@gsp :- "unset xtics; unset ytics; unset border"
Gnuplot.save(term = "pngcairo size 1600,800", output = "bunnyC.png")

ext: jl

max_stars_repo_name: lazarusA/gnuplot-examples

max_issues_repo_name: lazarusA/gnuplot-examples

max_forks_repo_name: lazarusA/gnuplot-examples


text:
export  minmax_normalize,
        opencv_disparity_map_to_image

"Normalize all values in array based on min and max value"
function minmax_normalize(A::AbstractArray)
    min = minimum(A)
    max = maximum(A)
    (A .- min) ./ (max - min)
end

"""
    opencv_disparity_map_to_image(A::AbstractArray) -> Matrix{Gray}

OpenCV algorithms for stereo matching (create 3D image from two 2D images)
outputs grayscale images representing disparity maps. These are 16-bit integers
which represent fixed point numbers. They are encoded such that 16 means  1 and
1 means 1/16.

OpenCV images are tranposed relative to Julia images. In Julia images are column ordered,
while OpenCV is row ordered. That is Julia follows the typical Fortran convention while
OpenCV follows the C convention. This means for a Julia image if you ask for size, then
the first dimension is the  height, and the second is the width.
"""
function opencv_disparity_map_to_image(A::AbstractArray)
	grays = Gray.(minmax_normalize(A))
	img = reshape(grays, size(A, 2), size(A, 3))
	transpose(img)
end

"""
    image_to_opencv_input(img::AbstractMatrix) -> Array{UInt8, 3}

For OpenCV Image data is always stored in 3D arrays. The reason is that the color
channel represents a dimension. Thus in OpenCV a 200×300 image with RGB values
will be represented by a 3×200×300 array. If the image was grayscale however it would be
represented by a 1×200×300 array.

However in Julia this is different. The first case would be a 300×200 matrix
of `RBG` values. The type would be `Array{RGB, 2}`. Rows and columns would be transposed because rows
are specifies first for a Julia matrix.

The grayscale image would be a 300×200 matrix as well, except the element type would be `Gray`.
The type would be `Array{Gray, 2}`.

The element type of `img` could be `RGB`, `Gray` or some `Real` value. It doesn't matter
as each element will be converted to `Gray` values anyway.

# Examples
```julia
import OpenCV
import ImageView, Images, FileIO

imgL = FileIO.load("images/L1.jpg");
imgR = FileIO.load("images/R1.jpg");

imgL = image_to_opencv_input(imgL)
imgR = image_to_opencv_input(imgR)

stereo    = OpenCV.StereoBM_create(numDisparities=Int32(96), blockSize=Int32(15));
disparity = OpenCV.compute(stereo, imgL, imgR);

ImageView.imshow(opencv_disparity_map_to_image(disparity))
```
"""
function image_to_opencv_input(img::AbstractMatrix)
    h, w = size(img)
    imgᵀ = transpose(img)

    # We don't know whether we got gray scales or RGB pixes, but it doesn't matter
    # as this will convert to grayscale no matter what the input was.
    grays = Gray.(reshape(imgᵀ, 1, w, h))
    opencv_input = round.(UInt8, Float32.(grays) .* 255)
end


text:
module MyPkgDemoEn

"""
Add numbers together.
"""
function add_nums end

"""
    add_nums(a,b)

Add two numbers.
"""
function add_nums(a,b)
  a+b
end

"""
    add_nums(a,b,c)

Add three numbers.
"""
function add_nums(a,b,c)
  a+b+c
end

end


text:
# EXAMPLE: test send and receive

using MPI
MPI.Init()

comm = MPI.COMM_WORLD
rank = MPI.Comm_rank(comm)

if rank==0
    data=[7.0,8.0,9.0,10.0]
    MPI.Send(data,1,99,comm) #99 is an unique tag for this message
elseif rank==1
    data=Array{Float64}(undef, 4)
    MPI.Recv!(data,0,99,comm)

    println(data)
end

MPI.Finalize()


text:
import LinearMaps

struct ZeroMap{T,U,V} <: LinearMap{T}
    range::U
    domain::V
end

ZeroMap{T}(range::U, domain::V) where {T,U,V} = ZeroMap{T,U,V}(range, domain)
LinearMaps.MulStyle(A::ZeroMap) = LinearMaps.FiveArg()

Base.size(A::ZeroMap) = (length(A.range), length(A.domain),)

function LinearAlgebra.mul!(y::AbstractVector, L::ZeroMap, x::AbstractVector,
    α::Number, β::Number)

    y .*= β
end

# function LinearAlgebra.mul!(y::AbstractVector,
#     Lt::LinearMaps.TransposeMap{<:Any,<:ZeroMap},
#     x::AbstractVector, α::Number, β::Number)

#     y .*= β
# end

function LinearAlgebra.mul!(y::AbstractVector, L::ZeroMap, x::AbstractVector)
    y .= 0
end

# function LinearAlgebra.mul!(y::AbstractVector,
#     Lt::LinearMaps.TransposeMap{<:Any,<:ZeroMap}, x::AbstractVector)

#     y .= 0
# end

LinearAlgebra.adjoint(A::ZeroMap{T}) where {T} = ZeroMap{T}(A.domain, A.range)
LinearAlgebra.transpose(A::ZeroMap{T}) where {T} = ZeroMap{T}(A.domain, A.range)

function Base.:(*)(A::ZeroMap, x::AbstractVector)
    T = eltype(A)
    y = similar(A.range, T)
    fill!(y, zero(T))
    LinearAlgebra.mul!(y,A,x)
end

Base.Matrix{T}(A::ZeroMap) where {T} = zeros(T, length(A.range), length(A.domain))


text:
# test core functionalities

# test nodes
a = Node(1, "a")
@test  node_key(a) == "a"
@test node_index(a) == 1
@test eltype(a) <: AbstractString
println(a)

a1 = Node(1, "a")
@test a == a1

b = AttributeNode(0, "a",  Dict())
b1 = AttributeNode{String}("a")
node_attributes(b) =  Dict("a" => 2)
@test node_index(b) == 0
@test node_key(b) == "a"
@test node_attributes(b) ==  Dict("a" => 2)
@test eltype(b) <: AbstractString
@test b == b1
println(b)

d = TimeNode(1, "a",  "t1")
@test node_key(d) == "a"
@test node_timestamp(d) == "t1"
@test node_index(d) == 1
@test eltype(d)[2] <: AbstractString
println(d)

# test edges
e1 = Edge('a', 'b')
@test source(e1) == 'a'
@test target(e1) == 'b'
e3 = Edge('b', 'a')
@test edge_reverse(e3) == e1
println(e1)

e2 = TimeEdge('a', 'b', 3)
@test source(e2) == 'a'
@test target(e2) == 'b'
@test edge_timestamp(e2) == 3
println(e2)
@test has_node(e2, 'a')

e = WeightedTimeEdge(1, 2, 2.3, 2)
@test source(e) == 1
@test target(e) == 2
@test edge_timestamp(e) == 2
@test edge_weight(e) == 2.3
println(e)


text:
"""
    circshiftpush!(v, e)

Shifts all elements of the vector `v` one step to the left and sets
`e` as the last element.
"""
function circshiftpush!(v::V, e::T) where {T,V<:AbstractVector{T}}
    for i = 1:length(v)-1
        v[i] = v[i+1]
    end
    v[end] = e
    v
end

"""
    ismonotonous(v[, comp=isless])

Returns true if the magnitude of every value fulfils `comp(cur,prev)`.
"""
function ismonotonous(v::V, comp=isless) where {T,V<:AbstractVector{T}}
    for i = 2:length(v)
        comp(abs(v[i]), abs(v[i-1])) || return false
    end
    true
end

"""
    scf!([fun!, ]fock[; ω=0, max_iter=200, tol=1e-8, verbosity=1])

Perform the SCF iterations for the `fock` operator. One iteration is
performed by [`scf_iteration!`](@ref). The optional `fun!(P̃,c̃)`
argument allows for extra operations to be performed every SCF cycle
(such as plotting, etc).

`ω` is a relaxation parameter; the orbitals and mixing coefficients
are updated as `wᵢ₊₁ = (1-ω)w̃ + ωwᵢ` where `w̃` is the solution in the
current iteration and `wᵢ` the previous solution. The default (`ω=0`)
is to only use this solution. A larger value of `ω` makes it easier to
achieve convergence in oscillatory problems, but a too large value
decreases the convergence rate. It is therefore desireable to reduce
the value of `ω` if the convergence is deemed to be monotonous, the
criterion for which is whether the change over the `monotonous_window`
last iterations is steadily decreasing. If this is the case, `ω` will
be reduced by multiplying by `ωfactor`. Conversely, if the change is
non-monotonous, `ω` will be increased, but not beyond `ωmax`.

The SCF procedure continues until either the amount of iterations
equals `max_iter` or the change in the coefficients is below `tol`.
"""
function scf!(fun!::Function, fock::Fock{Q};
              max_iter=200, tol=1e-8,
              ω=0, monotonous_window=10, ωfactor=0.9, ωmax=0.999,
              double_counted_total_energy=false,
              update_mixing_coefficients=true,
              verbosity=1, num_printouts=min(max_iter,10),
              kwargs...) where Q
    trace,tolerance,relaxation,eng,virial,flags =
        setup_solver_trace(verbosity, max_iter, tol, ω, num_printouts)

    # Views of the orbitals and mixing coefficients in the fock object.
    P = orbitals(fock.quantum_system)
    c = coefficients(fock.quantum_system)

    norb = size(P,2)
    nc = length(c)

    ΔP = [Inf for j in 1:norb]
    Δc = [Inf for j in 1:nc]

    Δhistory = zeros(monotonous_window)

    if verbosity ≥ 2
        nc > 1 && print("Multi-Configurational ")
        println("Self-Consistent-Field calculation of")
        print("- ")
        display(fock.quantum_system)
        println("- Maximum amount of iterations: $(max_iter)")
        tb,te = base_exp(tol)
        println("- Stopping tolerance: ", format(tolerance.tol_fmt, tb, to_superscript(te)))
        ω != 0 && println("- Successive relaxation: ω = $(ω)")
        println()
    end

    !isnothing(trace) && print_header(trace)
    t₀ = time()

    # Energy matrix
    H = spzeros(nc, nc)
    solve_secular_problem!(H, c, fock, update_mixing_coefficients)
    # Energy matrix for double-counted terms
    Hd = spzeros(nc, nc)
    # Kinetic energy matrix
    T = spzeros(nc, nc)

    if verbosity > 2
        println("Initial energy matrix")
        display(Matrix(H))
        println()
        println("Initial mixing coefficients:")
        display(c)
        println()
    end

    # Prepare all orbital integrals before the first iteration.
    update!(fock; verbosity=max(0,verbosity-4))
    okws = [OrthogonalKrylovWrapper(hamiltonian(eq))
            for eq in fock.equations]

    # Current estimates
    P̃ = copy(P)
    c̃ = copy(c)

    for i = 1:max_iter
        !isnothing(flags) && empty!(flags.val)
        did_rotate = scf_iteration!(fock, P̃, H, c̃, okws;
                                    update_mixing_coefficients=update_mixing_coefficients && i>1,
                                    rotate_orbitals=i>1,
                                    verbosity=verbosity-2, kwargs...)
        !isnothing(flags) && did_rotate && push!(flags.val, "R")

        fun!(P̃, c̃)

        for j = 1:norb
            ΔP[j] = 1.0 - dot(view(P̃,:,j),P[:,j])/norm(P[:,j])^2
        end
        Δc .= c̃ .- c

        aΔ = norm(ΔP) + norm(Δc)
        isnothing(tolerance) || (tolerance.current = aΔ)

        if ω == 0
            copyto!(P, P̃)
            copyto!(c, c̃)
        else
            # Relaxation; see e.g. p. 490 of
            #
            # - Fischer, C. F., & Guo, W. (1990). Spline Algorithms for the
            #   Hartree-Fock Equation for the Helium Ground State. Journal of
            #   Computational Physics, 90(2),
            #   486–496. http://dx.doi.org/10.1016/0021-9991(90)90176-2
            lmul!(ω, P)
            lmul!(1-ω, P̃)
            P[:] += P̃[:] # Is this efficient?
            lmul!(ω, c)
            lmul!(1-ω, c̃)
            c[:] += c̃[:] # Is this efficient?
            normalize!(c)
            copyto!(c̃, c)
        end

        circshiftpush!(Δhistory, aΔ)
        if ismonotonous(Δhistory)
            ω *= ωfactor
        else
            ω /= ωfactor
        end
        ω = clamp(ω, 0.0, ωmax)

        isnothing(relaxation) || (relaxation.ω = ω)
        if !isnothing(eng)
            Etot = if double_counted_total_energy
                energy_matrix!(Hd, fock, :double_counted_energy)
                sum(energy.(fock.equations)) - c'Hd*c
            else
                c'H*c
            end
            energy_matrix!(T, fock, :kinetic_energy)
            ET = c'T*c
            EV = Etot-ET
            eng[1].E = Etot
            eng[2].E = ET
            eng[3].E = EV
            virial.V = EV/ET
        end
        SolverTraces.next!(trace)

        if aΔ < tol
            println()
            break
        end
    end
    elapsed = time() - t₀
    verbosity > 0 && println("Finished in $(elapsed) seconds")

    analyze_symmetry_orbitals(fock, P, okws, verbosity=verbosity)

    norm(ΔP) + norm(Δc) > tol && @warn "Desired tolerance $(tol) not reached in $(max_iter) iterations"

    fock
end

scf!(fock::Fock, args...; kwargs...) =
    scf!((_,_)->nothing, fock, args...; kwargs...)

"""
    scf_iteration!(fock, P, H, c, okws,
                   [; verbosity=0, method=:arnoldi, σ=nothing, tol=1e-10,
                    update_mixing_coefficients=true])

Perform one step of the SCF iteration. This will

1) Improve each of the orbitals in turn, using the values of the
   orbitals `P` and mixing coefficients `c` from the previous step as
   input.

2) Solve the secular problem to find new values for the mixing
   coefficients, `c`, unless `update_mixing_coefficients==false`.

`okws` is a vector of [`OrthogonalKrylovWrapper`](@ref)s, one for each
orbital.
"""
function scf_iteration!(fock::Fock{Q,E}, P::M, H::HM, c::V,
                        okws;
                        verbosity=0, method=:arnoldi,
                        tol=1e-10,
                        update_mixing_coefficients=true,
                        kwargs...) where {Q,E,M<:AbstractVecOrMat,
                                          HM<:AbstractMatrix,V<:AbstractVector}
    verbosity > 0 && println("Improving orbitals using $(method)")

    Threads.@threads for j = 1:length(fock.equations)
        vPj = view(P,:,j)

        solve_orbital_equation!(vPj, okws[j], method, tol;
                                verbosity=verbosity-2,
                                kwargs...)

        # Normalize eigenvector and rotate it such that the
        # largest lobe is positive.
        norm_rot!(fock, vPj)
    end

    did_rotate = rotate_orbitals!(P, fock, okws;
                                  verbosity=verbosity-2, kwargs...)

    # energy_matrix! requires fresh integrals to be calculated
    # correctly, hence we update the integrals after improving the
    # orbitals.
    update!(fock; verbosity=max(0,verbosity-2))

    solve_secular_problem!(H, c, fock, update_mixing_coefficients, tol=tol)

    did_rotate
end


text:
# A simple forward-mode AD. Simplified so that many things don't work (e.g.
# control flow), but shows the basic ideas.

using IRTools.All
using IRTools: Pipe
using Base: tail

ntail(x, n) = n <= 0 ? x : xcall(:tail, ntail(x, n-1))

zerolike(x::Number) = zero(x)
zerolike(x::Tuple) = zerolike.(x)
zerolike(x::T) where T =
  NamedTuple{fieldnames(T)}(map(f -> zerolike(getfield(x, f)), fieldnames(T)))
zerolike(x::Union{Module,Type}) = nothing

function instrument!(pr, v, st)
  ex = st.expr
  if isexpr(ex, :new)
    st = stmt(st, expr = xcall(Main, :__new__, ex.args...))
    pr[v] = st
  end
  return st
end

function dual(ir)
  pr = Pipe(ir)
  Δs = Dict()
  partial(x::Variable) = Δs[x]
  partial(v, x::Variable) = Δs[x]
  partial(v, x) = insert!(pr, v, xcall(Main, :zerolike, x))
  dx = argument!(pr, at = 1)
  for (i, x) in enumerate(arguments(ir))
    if i == length(arguments(ir)) && ir.meta.method.isva
      Δs[x] = push!(pr, ntail(dx, i-1))
    else
      Δs[x] = push!(pr, xcall(:getindex, dx, i))
    end
  end
  for (v, st) in pr
    st = instrument!(pr, v, st)
    if isexpr(st.expr, :call)
      dargs = insert!(pr, v, xcall(:tuple, partial.((v,), st.expr.args)...))
      result = insert!(pr, v, stmt(st, expr = xcall(Main, :diff, dargs, st.expr.args...)))
      pr[v] = xcall(:getindex, result, 1)
      Δs[v] = push!(pr, xcall(:getindex, result, 2))
    elseif !isexpr(st.expr)
      Δs[v] = push!(pr, xcall(Main, :zerolike, v))
    else
      error("Unsupported $(st.expr.head) expression")
    end
  end
  ret = returnvalue(block(ir, 1))
  return!(pr, xcall(:tuple, ret, partial(ret)))
  return finish(pr)
end

@dynamo function diff(_, x...)
  ir = IR(x...)
  ir == nothing && return :(error("non-differentiable function $(args[2])"))
  @assert length(blocks(ir)) == 1 "Control flow not yet supported"
  return dual(ir)
end

@generated function __new__(T, args...)
  quote
    Base.@_inline_meta
    $(Expr(:new, :T, [:(args[$i]) for i = 1:length(args)]...))
  end
end

# Julia internal definitions
diff(_, ::typeof(zerolike), x) = zerolike(x), zerolike(x)
diff(_, ::typeof(one), x) = one(x), zerolike(x)
diff(_, ::typeof(println), x...) = println(x...), nothing
diff(_, ::typeof(typeof), x) = typeof(x), nothing
diff(_, ::typeof(Core.apply_type), args...) = Core.apply_type(args...), nothing
diff(ṫ, ::typeof(tuple), t...) = t, tail(ṫ)
diff((_, ṫ, _), ::typeof(getfield), t, i) = getfield(t, i), getfield(ṫ, i)
diff((_, ṫ, _), ::typeof(getindex), t, i) = getindex(t, i), getindex(ṫ, i)
diff(ṡ, ::typeof(__new__), T, s...) = __new__(T, s...), NamedTuple{fieldnames(T)}(tail(tail(ṡ)))

# Mathematical definitions
diff((_, ȧ, ḃ), ::typeof(+), a, b) = a + b, ȧ + ḃ
diff((_, ȧ, ḃ), ::typeof(-), a, b) = a - b, ȧ - ḃ
diff((_, ȧ, ḃ), ::typeof(*), a, b) = a*b, ȧ*b+ḃ*a
diff((_, ȧ), ::typeof(-), a) = -a, -ȧ

diff((_, ẋ), ::typeof(sin), x) = sin(x), ẋ*cos(x)
diff((_, ẋ), ::typeof(cos), x) = cos(x), -ẋ*sin(x)

# Test cases

D(f, x) = diff((zerolike(f), one(x)), f, x)[2]

D(x -> sin(cos(x)), 0.5) # -cos(cos(x))sin(x)

D(x -> D(cos, x), 0.5) # -cos(x)

D(x -> x*D(y -> x*y, 1), 4) # 8


text:
### SOME CONVERGENCE REQUIRED ---

"""
$(TYPEDEF)

Condensed representation of KernelDensityEstimate, by saving points and bandwidth
"""
mutable struct EasyMessage{T <: Tuple}
  pts::Array{Float64,2}
  bws::Array{Float64,1}
  manifolds::T
  inferdim::Float64
  EasyMessage{T}() where {T <: Tuple} = new{T}()
  EasyMessage{T}(a::Array{Float64,2}, b::Array{Float64,1}, manis::T, inferdim::Union{Float64, Int32, Int64}=0.0) where {T <: Tuple} = new{T}(a,b, manis, Float64(inferdim))
  EasyMessage{T}(p::BallTreeDensity, manis::T, inferdim::Union{Float64, Int32, Int64}=0.0) where {T <: Tuple}  = new{T}(getPoints(p), getBW(p)[:,1], manis, Float64(inferdim))
end
EasyMessage(a::Array{Float64,2}, b::Array{Float64,1}, manis::T, inferdim::Union{Float64, Int32, Int64}=0) where {T <: Tuple} = EasyMessage{T}(a, b, manis, inferdim)
EasyMessage(p::BallTreeDensity, manis::T, inferdim::Union{Float64, Int32, Int64}=0) where {T <: Tuple} = EasyMessage{T}(p, manis, inferdim)

const TempBeliefMsg = Dict{Symbol, Tuple{BallTreeDensity, Float64}}

# Dict{Symbol,   -- is for variable label
#  Vector{       -- multiple msgs for the same variable
#   Symbol,      -- Clique index
#   Int,         -- Depth in tree
#   BTD          -- Belief estimate
#   inferredDim  -- Information count
#  }
const TempUpMsgPlotting = Dict{Symbol,Vector{Tuple{Symbol, Int, BallTreeDensity, Float64}}}

"""
$(TYPEDEF)

DESPARATELY NEEDS TO BE UPDATED TO USE TempBeliefMsg DEFINITION (start of refactor).
"""
mutable struct NBPMessage <: Singleton
  p::Dict{Symbol, EasyMessage}
end

### SOME CONVERGENCE REQUIRED ^^^


text:
__precompile__()
module OttawaSlabCell
using FilmDataStructures, ResponseModels,eps_gold,eps_InAsSbP,eps_InAs_ntype
export uOttawaSlabs
# Code for initializing uOttawa slab structure
include("uOttawaSlabStruct.jl")
# Creates uOttawaSlabs(tEmit::Float64, tBck::Float64, divNCell::Int, divPCell::Int)::Tuple{lyrDsc, Array{Int64,2}}
precompile(uOttawaSlabs, (Float64, Float64, Int, Int))
end


text:
using Test
using SenseHat

@test -40 <= temperature() <= 60
@test 0 <= humidity() <= 100
@test 900 <= pressure() <= 1200


text:
# duration

const change_duration = RadioMenu(["yes", "no"])

function test_duration(file::VideoFile)
    onfile = Time(0) + secondtoms(VideoIO.get_duration(joinpath(coffeesource, file.name)))
    regist = Time(0) + duration(file)
    regist == onfile && return NamedTuple()
    Δ = Time(0) + abs(onfile - regist)
    @warn "the registered duration doesn't match the duration on the file" file.name regist onfile Δ
    i = requestᵐ("Do you want to change the registered duration to the file's duration?", change_duration)
    i == 2 && return NamedTuple()
    (; duration = onfile - Time(0))
end

function test_duration(wv::WholeVideo)
    file = files(wv)[]
    # WholeVideo(wv, (; files = VideoFile(file, test_duration(file))))
    WholeVideo(wv, test_duration(file))
end

function test_duration(tl::T) where T <: AbstractTimeLine
    fs = files(tl)
    for (i, file) in enumerate(fs)
        fs[i] = VideoFile(file, test_duration(file))
    end
    T(tl, (; files = fs))
end

function test_duration()
    @info "testing the duration and starting date & time of the videos"
    vs = JLSO.load(joinpath(sourcefolder, "videos.jlso"))["data"]
    pass = true
    for (i, v) in enumerate(vs)
        v2 = test_duration(v)
        if v2 ≠ v
            vs[i] = v2
            pass = false
        end
    end
    if pass
        @info "on-file and registered duration and starting date & time are equal"
    else
        @info "changes are saved to file"
        JLSO.save(joinpath(sourcefolder, "videos.jlso"), vs)
    end
    pass
end

# starting
#=const change_start = RadioMenu(["yes", "no"])

function test_start(file)
    onfile = min_creation(joinpath(coffeesource, file.name))
    regist = start(file)
    regist == onfile && return NamedTuple()
    Δ = Time(0) + abs(onfile - regist)
    @warn "the registered starting date & time doesn't match the date & time on the file" file.name regist onfile Δ
    i = requestᵐ("Do you want to change the registered starting date & time to the file's date & time?", change_start)
    i == 2 && return NamedTuple()
    (; start = onfile)
end

function test_duration_start(wv::WholeVideo)
    file = files(wv)[]
    WholeVideo(wv, merge(test_start(file), test_duration(file)))
end

function test_duration_start(tl::T) where T <: AbstractTimeLine
    fs = files(tl)
    for (i, file) in enumerate(fs)
        fs[i] = VideoFile(file, merge(test_start(file), test_duration(file)))
    end
    T(tl, (; files = fs))
end

function test_duration_start()
    @info "testing the duration and starting date & time of the videos"
    vs = JLSO.load(joinpath(sourcefolder, "videos.jlso"))["data"]
    pass = true
    for (i, v) in enumerate(vs)
        v2 = test_duration_start(v)
        if v2 ≠ v
            vs[i] = v2
            pass = false
        end
    end
    if pass
        @info "on-file and registered duration and starting date & time are equal"
    end
    JLSO.save(joinpath(sourcefolder, "videos.jlso"), vs)
    pass
end=#

function test_integrity()
    @info "testing integrity of the videos"
    vs = JLSO.load(joinpath(sourcefolder, "videos.jlso"))["data"]
    allregistered = vcat(filenames.(vs)...)
    allfiles = filter(goodvideo, readdir(coffeesource))
    pass1 = true
    for file in allfiles
        if file ∉ allregistered
            @warn "found an unregistered video file!" file
            pass1 = false
        end
    end
    if pass1
        @info "all video files are registered"
    end
    pass2 = true
    for file in allregistered
        if file ∉ allfiles
            @warn "a registered video file is missing its file!" file
            i = findfirst(v -> file ∈ filenames(v), vs)
            !isnothing(i) && deleteat!(vs, i)
            pass2 = false
        end
    end
    if pass2
        @info "all registered video files are accounted for"
    end
    JLSO.save(joinpath(sourcefolder, "videos.jlso"), vs)
    pass1 && pass2
end


text:
#ДАНО: Робот - Робот - в произвольной клетке ограниченного прямоугольного поля с перегородками
#РЕЗУЛЬТАТ: Робот - в исходном положении, и клетки поля промакированы так: нижний ряд - полностью,
#следующий - весь, за исключением одной последней клетки на Востоке, следующий - за исключением двух последних клеток
#на Востоке, и т.д.
include("library.jl")
function putmarker!(robot::CoordsRobot)
    x, y = get_xy(get_coords(robot))
    if x - y <= 0
        putmarker!(get_robot(robot))
    end
end
function lestniza_with_obstacles(r::Robot)
    back_path = BackPath(r)
    R = CoordsRobot(r)
    marks!(R)
    BackPath(R)
    back!(R, back_path)
end

max_stars_repo_name: listova-nastya/mirea-progs

max_issues_repo_name: listova-nastya/mirea-progs

max_forks_repo_name: listova-nastya/mirea-progs


text:
# Column sampling sketch of a matrix
# LinearTimeSVD - Drineas, et  al. "Fast monte carlo algorithms for matrices ii: computing a low rank approximation to a matrix", SIAM Journal of Computing, 2006.
#
# Danny Perry (dperry@cs.utah.edu)
# April 2015

using Debug

@debug function LinearTimeSVD(A, num_cols)
	n = size(A,1)
	d = size(A,2)
	c = num_cols

	C = zeros(c,d)
	norm_est = 0
	for i=1:n
		normi = norm(A[i,:])^2
		norm_est += normi
		pc = normi/norm_est
		scale = 1/sqrt(c*pc)
		for j=1:c
			if rand() <= pc
				C[j,:] = scale * A[i,:]
			end
		end
	end
	U,S2,V = svd(C*C')
	S = sqrt(S2) # S are the approximate singular values of A
	H = (C' * V' * pinv(diagm(S)))  # H is an approximate right singular vector of A (left singular vector of A').
	return H,S
end

# same but using leverage scores
@debug function LeverageLinearTimeSVD(A, Uk,k, num_cols)
	n = size(A,1)
	d = size(A,2)
	c = num_cols

	row_lev = sum(Uk.^2,2) ./ k

	C = zeros(c,d)
	for i=1:n
		pc = row_lev[i]
		scale = 1/sqrt(c*pc)
		for j=1:c
			if rand() <= pc
				C[j,:] = scale * A[i,:]
			end
		end
	end
	U,S2,V = svd(C*C')
	S = sqrt(S2) # S are the approximate singular values of A
	H = (C' * V' * pinv(diagm(S)))  # H is an approximate right singular vector of A (left singular vector of A').
	return H,S
end


text:
using GLMakie
using Profile, BenchmarkTools

println("""=========================================================================================

                                ███▄ ▄███▓ ▄▄▄       ██▓ ███▄     █
                                ▓██▒▀█▀ ██▒▒████▄    ▓██▒ ██ ▀█   █
                                ▓██    ▓██░▒██  ▀█▄  ▒██▒▓██  ▀█ ██▒
                                ▒██    ▒██ ░██▄▄▄▄██ ░██░▓██▒  ▐▌██▒
                                ▒██▒   ░██▒ ▓█   ▓██▒░██░▒██░   ▓██░
                                ░ ▒░   ░  ░ ▒▒   ▓▒█░░▓  ░ ▒░   ▒ ▒
                                ░  ░      ░  ▒   ▒▒ ░ ▒ ░░ ░░   ░ ▒░
                                ░      ░     ░   ▒    ▒ ░   ░   ░ ░
                                    ░         ░  ░ ░           ░

===============================================================================================""")

time = Node(0.0)

xs = LinRange(0, 7, 40)

ys_1 = @lift(sin.(xs .- $time))
ys_2 = @lift(cos.(xs .- $time) .+ 3)

figure, _ = lines(xs, ys_1, color = :blue, linewidth = 4)
scatter!(xs, ys_2, color = :red, markersize = 15)
figure
# timestamps = 0:1/30:2

# record(figure, "time_animation.mp4", timestamps; framerate = 30) do t
#     time[] = t
# end

max_stars_repo_path: GL_playground/Makie_playground 0x02.jl

max_stars_repo_name: leroy-walton/playgrounds

max_issues_repo_path: GL_playground/Makie_playground 0x02.jl

max_issues_repo_name: leroy-walton/playgrounds

max_forks_repo_path: GL_playground/Makie_playground 0x02.jl

max_forks_repo_name: leroy-walton/playgrounds


text:
# ==================================
# Forward approximation from d/dt
# ==================================

"""
    ForwardDdt{EM, SO, SI, IT, BT} <: AbstractApproximationModel

Forward approximation model used in `d/dt`. It can be used for overapproximation
and underapproximation.

### Fields

- `oa`      -- (optional, default: `true`) flag to choose between
               overapproximation and underapproximation
- `exp`     -- (optional, default: `BaseExp`) exponentiation method
- `setops`  -- (optional, default: `:lazy`) set operations method
- `sih`     -- (optional, default: `:concrete`) way to compute the symmetric
               interval hull
- `inv`     -- (optional, default: `false`) if `true`, assume that the state
               matrix is invertible and use its inverse in the `Φ` functions
- `backend` -- (optional, default: `nothing`) used if the algorithm needs to
               apply concrete polyhedral computations

### Algorithm

The transformations are:

- ``Φ ← \\exp(Aδ)``,
- ``Ω_0 ← bloat(CH(\\mathcal{X}_0, Φ\\mathcal{X}_0), ε)``

where ``bloat(\\mathcal{X}, ε)`` bloats the set ``\\mathcal{X}`` with the value
``ε``. If `oa == false`, the bloating acts in an inverted way and shrinks the
set.

### Reference

E. Asarin, T. Dang, O. Maler, O. Bournez: *Approximate reachability analysis of
piecewise-linear dynamical systems*. HSCC 2000.
"""
struct ForwardDdt{EM, SO, SI, IT, BT} <: AbstractApproximationModel
    oa::Bool
    exp::EM
    setops::SO
    sih::SI
    inv::IT
    backend::BT
end

hasbackend(alg::ForwardDdt) = !isnothing(alg.backend)

# convenience constructor using symbols
function ForwardDdt(; oa::Bool=true, exp=BaseExp, setops=:lazy, sih=:concrete,
                      inv=false, backend=nothing)
    return ForwardDdt(oa, _alias(exp), _alias(setops), Val(sih), Val(inv), backend)
end

function Base.show(io::IO, alg::ForwardDdt)
    print(io, "`ForwardDdt` approximation model with: \n")
    print(io, "    - $(alg.oa ? "over" : "under")approximation \n")
    print(io, "    - exponentiation method: $(alg.exp) \n")
    print(io, "    - set operations method: $(alg.setops)\n")
    print(io, "    - symmetric interval hull method: $(alg.sih)\n")
    print(io, "    - invertibility assumption: $(alg.inv)")
    print(io, "    - polyhedral computations backend: $(alg.backend)")
end

Base.show(io::IO, m::MIME"text/plain", alg::ForwardDdt) = print(io, alg)

# ------------------------------------------------------------
# ForwardDdt Approximation: Homogeneous case
# ------------------------------------------------------------

# if A == |A|, then Φ can be reused in the computation of Φ₂(|A|, δ)
function discretize(ivp::IVP{<:CLCS, <:LazySet}, δ, alg::ForwardDdt)
    A = state_matrix(ivp)
    X0 = initial_state(ivp)

    Φ = _exp(A, δ, alg.exp)
    Y = ConvexHull(X0, Φ * X0)
    Y = _apply_setops(Y, alg)

    # bloating
    ε = _estimate_bloating_value_ddt(A, X0, δ)
    if !alg.oa
        ε = -ε
    end
    Ω0 = Bloating(Y, ε)

    X = stateset(ivp)
    Sdis = ConstrainedLinearDiscreteSystem(Φ, X)
    return InitialValueProblem(Sdis, Ω0)
end

function _estimate_bloating_value_ddt(A, X0, δ)
    norm_A = opnorm(A)
    u = 1/8 * norm_A^2 * δ^2
    v = exp(norm_A * δ) - 1 - (norm_A * δ) - (norm_A^2 * δ^2 / 2)
    return (u + v) * norm(X0)
end

# outer bloating a polytope into a polytope
function _bloat(P::LazySet, ε)
    A, b = tosimplehrep(P)
    bε = copy(b)
    for i in 1:length(b)
        bε[i] += ε * opnorm(transpose(A[i, :]))
    end
    return HPolytope(A, bε)
end


text:
params = DummyRobotParams()
rob = DummyRobot(deviceID="dummy", params=params, dependencies=Dict{String, Union{Device, Missing}}())
@test state(rob)==:INIT
@test getPosition(rob)==[1.0,0,0]u"mm"
@test dof(rob)==3

setup(rob)
@test state(rob)==:DISABLED
@test_throws RobotStateError moveAbs(rob,[1,1,1]u"mm")
@test_throws RobotStateError setup(rob)

@test !isReferenced(rob)
enable(rob)
@test_throws RobotReferenceError moveAbs(rob, [1,1,1]u"mm")
@test_logs (:warn, "Performing relative movement in unreferenced state, cannot validate coordinates! Please proceed carefully and perform only movements which are safe!") moveRel(rob,[1,0,0]u"m")
doReferenceDrive(rob)
@test isReferenced(rob)
moveAbs(rob, [1,1,1]u"mm")
reset(rob)
@test state(rob)==:INIT


text:
df = DataFrame()
df[:A] = 1:numData

lamb_grid = [10. .^(-7:1)]
c_grid = linspace(1, 5, 6)  # This choice of c_grid yields no distinguishable difference. Try: c_grid = 2. .^(1:5)
deg_grid = [2:6]    #2 is a pretty meaningless choice.  drop to 3.
N = length(lamb_grid) * length(c_grid) * length(deg_grid)

res = Array(Float64, N, 5)
ix = 1
for l in lamb_grid
    for c in c_grid
        for d in deg_grid
            train(df) = train(df[:A], l, d, c, demand_data, flow_data, arcs)
            test(df, fit) = test(fit, df[:A], demand_data, flow_data, arcs, g, vArcs)
            rtrain, rtest = kfold_crossvalidate(df, train, test, 5)

            res[ix, 1] = l
            res[ix, 2] = c
            res[ix, 3] = float(d)
            res[ix, 4] = mean(rtest) / 1e6
            res[ix, 5] = std(rtest) / 1e6
            ix +=1

            show(res)
        end
    end
end

writetable("trafficCVal.csv", DataFrame(res))

max_stars_repo_name: jingzbu/InverseVITraffic

max_issues_repo_name: jingzbu/InverseVITraffic

max_forks_repo_name: jingzbu/InverseVITraffic


text:
### Day 8 - Problem 1
## Two-Factor Authentication
## Authors: Thanasis Georgiou, Marina Grigoropoulou

# Read input
f = open("input.txt")
input = readlines(f)
close(f)

# Screen
lcd = Array(Bool, 50, 6)

# Fill a rectangle at top left
function rect(w, h)
    for x = 1:w
        for y = 1:h
            lcd[x, y] = true
        end
    end
end

# Rotate a row by Δ
function rotateRow(y, Δ)
    lcd[1:50, y] = circshift(lcd[1:50, y], Δ)
end

# Rotate a column by Δ
function rotateColumn(x, Δ)
    lcd[x, 1:6] = circshift(lcd[x, 1:6], Δ)
end

# Parse input
for line in input
    str = split(line, ' ')

    # Determine command
    if str[1] == "rect"
        coords = split(str[2], 'x')
        w = parse(Int, coords[1])
        h = parse(Int, coords[2])
        rect(w, h)
    elseif str[1] == "rotate"
        Δ = parse(Int, str[end])
        l = parse(Int, str[3][3:end]) + 1

        if str[2] == "row"
            rotateRow(l, Δ)
        else
            rotateColumn(l, Δ)
        end
    end
end

# Count pixels
count = 0
for y = 1:6
    for x = 1:50
        if lcd[x, y] == true
            count += 1
            print("#")
        else
            print(" ")
        end
    end
    print("\n")
end

println("Count: $count")


text:
using Libdl

function find_dwf()
  if Sys.islinux()
    path = "/usr/lib"
    libdwf = "libdwf.so"
  elseif Sys.isapple()
    path = "/Library/Frameworks/dwf.framework"
    libdwf = "dwf"
  else
    error("DigilentWaveForms.jl only supported on Linux, and MacOS platforms")
  end

  return path, libdwf
end

function configure()

  path, libdwf = find_dwf()
  libdwf = find_library(libdwf,[path])

  libdwf != "" || @error "Digilent WaveForm SDK cannot be found"

  open(joinpath(@__DIR__, "deps.jl"), "w") do f
    write(f, """
      const libdwf = \"$(libdwf)\"
    """)
  end

end

configure()


text:
using SeqTools
using Test

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


text:
export solve_modelTRDiag_HO_vs_Nwt_λ

"""
If the Newton direction is accepted and the high order correction lies within
a bigger trust region then we use the high order correction.
"""
function solve_modelTRDiag_HO_vs_Nwt_λ(nlp_stop, PData :: PDataFact, δ:: T; ho_correction :: Symbol = :Shamanskii, fact = 2.0, λfact = 1.0, nwt_res_fact = 0.25) where T
    # Solve the TR subproblem once diagonalized into Δ using the norm |Δ|
    # Setup the problem
    # printstyled("On est dans solve_model_TRDiag_HO_vs_Nwt_λ  ↓ \n", color = :red)
    nlp_at_x = nlp_stop.current_state
    M = ones(T, size(PData.Δ))
    ϵ = sqrt(eps(T)) / T(100.0)
    ϵ2 = ϵ .* (T(1.0) .+ PData.λ)
    global dHO = nothing

    if PData.success # take care of eventual hard case and Newton's direction interior (λ = 0)
        # (PData.Δ + PData.λ * M) ⪰ 0
        # println("on a PData.succes = $(PData.success)")
        λ = max(ϵ2, ϵ2 + PData.λ) # to make sure (PData.Δ + λ * M) ≻ 0
        # λ = PData.λ

        d̃ = -(PData.Δ .+ λ * M) .\ PData.g̃ # Ajouter Shamanskii ici!
        normd̃ = sqrt(d̃⋅d̃)
        if normd̃ < δ
            if PData.λ == 0.0 # Newton's direction
                λ = PData.λ
                # println(" Newton's direction inside the region")
                #  d̃ is the Newton's direction, nothing more to do
            else              # hard case
                # println(" hard case")
                bidon, i = findmin(PData.Δ)
                d̃[i] = 0.0; d̃[i] = - sign(PData.g̃[i]) * sqrt(δ^2 - d̃⋅d̃)
            end
        else
            d̃,λ = solve_diagTR(λ, PData.Δ, PData.g̃, δ, ϵ)
        end
    else # hard case impossible, λ already > λ_min
        # println("on est dans le cas hard cases impossible")
        # Solve the subproblem (Δ + λ I) d̃ = -g̃ such that ||d̃|| = δ
        d̃, λ = solve_diagTR(PData.λ, PData.Δ, PData.g̃, δ, ϵ)
    end

    PData.λ = λ

    # Transform back d̃ into d

    d = AInv(PData, d̃)
    # @show λfact
    if λ <= λfact
        # printstyled("on a λ < λfact \n", color = :yellow)
        # @show ho_correction
        dHO = eval(ho_correction)(nlp_stop, PData, d, PData.g̃)
        # @show dHO
        # @show d
        # @show dHO == d
        if dHO == d
            # println("on est ici")
            return d, NaN * rand(length(d)), λ
        end
        # printstyled("on a dHO \n", color = :yellow)
        nwt_residual = (-(nlp_at_x.gx + 0.5 * nlp_at_x.Hx * d)⋅d)
        # printstyled("on a nwt_residual \n", color = :yellow)
        if (norm(dHO) < 2.0 .* δ) && ((-(nlp_at_x.gx + 0.5 * nlp_at_x.Hx * dHO)⋅dHO) >= nwt_res_fact .* nwt_residual)
            return dHO, dHO, λ
        else
            return d, dHO, λ
        end
    end

    #try assert((PData.g̃ + 0.5*PData.Δ .* d̃)⋅d̃ <= 0.0)  catch  @bp  end
    return d, NaN * rand(length(d)), λ
end


text:
plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* ( DatPkg_base.Dt[:LI] ./ DatPkg_base.Dt[:N] )[idx_plot]  );
plot( DatPkg_high.Dt[:Year][idx_plot], 100 .* ( DatPkg_high.Dt[:LI]  ./ DatPkg_high.Dt[:N]  )[idx_plot], "-.b" );
plot( DatPkg_low.Dt[:Year][idx_plot], 100 .* ( DatPkg_low.Dt[:LI]  ./ DatPkg_low.Dt[:N] )[idx_plot], "--r" );
legend(["base","high","low"]); grid(true)

plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* ( 1.0 .- dict_Demog_base["LaborPopu"] ./ dict_Demog_base["TotalPopu"] )[idx_plot]  );
plot( DatPkg_high.Dt[:Year][idx_plot], 100 .* ( 1.0 .- dict_Demog_high["LaborPopu"]  ./ dict_Demog_high["TotalPopu"]  )[idx_plot], "-.b" );
plot( DatPkg_low.Dt[:Year][idx_plot], 100 .* ( 1.0 .- dict_Demog_low["LaborPopu"]  ./ dict_Demog_low["TotalPopu"] )[idx_plot], "--r" );
legend(["base","high","low"]); grid(true)
title(L"\rho")

expr_GetDemogDat = :(
   Dict( "TotalPopu" => Dt[:N],
      "LaborPopu" => sum(Ps[:N][:,1:env.Sr],dims=2)[:],
      "AgingPopu_65plus" => sum(Ps[:N][:, (65 - env.START_AGE + 1):env.S],dims=2)[:],
      "AgingPopuRatio" => sum(Ps[:N][:, (65 - env.START_AGE + 1):env.S],dims=2)[:] ./ sum(Ps[:N][:,1:env.Sr],dims=2)[:]
   )
)

figure()
   subplot(1,3,1)
      plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* ( DatPkg_base.Dt[:LI] ./ DatPkg_base.Dt[:N] )[idx_plot]  );
      plot( DatPkg_base.Dt[:Year][idx_plot], 100 .* ( 1.0 .- dict_Demog_base["LaborPopu"] ./ dict_Demog_base["TotalPopu"] )[idx_plot]  );
      legend(["gap/exp",L"\rho"])
   subplot(1,3,2)

#


text:
module CellNumbers

using Gridap
using Gridap.Helpers

using StaticArrays

export NumberLike
export CellNumber
export IterCellNumber
export IndexCellNumber

export test_index_cell_number
export test_iter_cell_number

const NumberLike = Union{Number,SArray}

# Iterable cell Numbers

const IterCellNumber{A<:NumberLike} = IterCellValue{A}

# Indexable cell arrays

const IndexCellNumber{A<:NumberLike,D} = IndexCellValue{A,D}

# Cell Numbers

const CellNumber{A<:NumberLike} = Union{IterCellNumber{A},IndexCellNumber{A}}

# Testers

function test_iter_cell_number(icv::CellNumber, a::AbstractArray{<:NumberLike})
  test_iter_cell_value(icv,a)
end

function test_index_cell_number(icv::IndexCellNumber, a::AbstractArray{<:NumberLike})
  test_index_cell_value(icv,a)
end

end # module CellNumbers


text:
module LinkageDisequilibrium

include("./utils.jl")

include("./measures.jl")

export fisher_exact_test, χ²_test
include("./hypothesis_tests.jl")

export ld_select
include("./ld_select.jl")

export informative_select
include("./informative_select.jl")

end


text:
#=

# 1: Static container

```@raw html
	<img src='../assets/static_container.png' width="50%" height="50%" alt='missing' /><br>
```

This is a hello world example of SPH.
Simulates motionless fluid in uniform gravitational field.
Things that may be tested by this benchmark are:
* walls,
* zero point stability of time integrator,
* stability of free surface.

Let us begin by declaring a module and importing some stuff.
=#

module static_container

using Printf
using SmoothedParticles

#=
Declare constant parameters
=#

const dr = 3.0e-3       #average particle distance
const h = 1.8*dr        #size of kernel support
const rho0 = 1000.0     #fluid density
const m = rho0*dr^2     #particle mass
const c = 40.0          #numerical speed of sound
const g = -VECY         #gravitational acceleration
const mu = 8.4e-4       #dynamic viscosity of water

const water_depth = 0.14
const box_height = 0.18
const box_width = 0.14
const wall_width = 2.5*dr

##temporal parameters
const dt = 0.2*h/c
const dt_frame = 0.1
const t_end = 0.5

##particle types
const FLUID = 0.
const WALL = 1.

#=
Declare variables to be stored in a Particle
=#

mutable struct Particle <: AbstractParticle
	x::RealVector #position
	v::RealVector #velocity
	a::RealVector #acceleration
	rho::Float64 #density
	type::Float64 #particle type
	Particle(x::RealVector, type::Float64) = new(
		x,
		VEC0,
		VEC0,
		rho0,
		type
	)
end

##dependance of pressure on density
function pressure(p::Particle)
	return c^2*(p.rho - rho0)
end

##fluid identier
function isfluid(p::Particle)::Float64
	return Float64(p.type == FLUID)
end

#=
Define geometry and make particles
=#
function make_system()
	grid = Grid(dr, :square)
	box = Rectangle(0., 0., box_width, box_height)
	fluid = Rectangle(0., 0., box_width, water_depth)
	walls = BoundaryLayer(box, grid, wall_width)
	sys = ParticleSystem(Particle, box + walls, h)
	generate_particles!(sys, grid, fluid, x -> Particle(x, FLUID))
	generate_particles!(sys, grid, walls, x -> Particle(x,  WALL))
	return sys
end

#=
Define particle interactions
=#
@inbounds function balance_of_mass!(p::Particle, q::Particle, r::Float64)
	p.rho += dt*dot(p.x-q.x, p.v-q.v)*m*rDwendland2(h,r)
end

@inbounds function internal_force!(p::Particle, q::Particle, r::Float64)
	if p.type == FLUID
		ker = m*rDwendland2(h,r)
		#pressure force
		p.a += -ker*(pressure(p)/p.rho^2 + pressure(q)/q.rho^2)*(p.x - q.x)
		#viscous force
		p.a += ker*2*mu/(p.rho*q.rho)*(p.v - q.v)
	end
end

function update!(p::Particle)
	p.v += dt*isfluid(p)*(p.a + g)
	p.x += dt*isfluid(p)*p.v
	p.a = VEC0
end

#=
Put everything into a time loop
=#
function main()
	sys = make_system()
	@show sys.key_max
	out = new_pvd_file("results/static_container")
	for k = 0 : Int64(round(t_end/dt))
		if (k %  Int64(round(dt_frame/dt)) == 0)
			println("# of particles = ", length(sys.particles))
			@printf("t = %.6e\n", k*dt)
			save_frame!(out, sys, :rho, :type, :v)
		end
		create_cell_list!(sys)
		apply!(sys, balance_of_mass!)
		apply!(sys, internal_force!)
		apply!(sys, update!)
	end
	save_pvd_file(out)
end ##function main()

end ##module


text:
using RandomSubSamplers, Test, Random

Random.seed!(UInt32[0xb0a863be, 0x4c2f0833, 0xa08d7276, 0xb3fe604f])

@testset "random subsampler" begin
    v = rand(1:100, 1000)
    w = randn(1000)
    vw = tuple.(v, w)
    rvw = collect(random_subsample(first, 0.3, vw))
    k = unique(first.(rvw))
    @test 26 ≤ length(k)  ≤ 40  # generous bounds for CI
    @test filter(x -> first(x) ∈ k, vw) == rvw
end

max_stars_repo_name: tpapp/RandomSubSamplers

max_issues_repo_name: tpapp/RandomSubSamplers

max_forks_repo_name: tpapp/RandomSubSamplers


text:
function cantorPairing(x, y)
	return Int64((x + y)*(x + y + 1)/2 + y);
end

max_stars_repo_name: driesverhees/dobble

max_issues_repo_name: driesverhees/dobble

max_forks_repo_name: driesverhees/dobble


text:
numterms = 200
C4 = Array{BigInt}(numterms+1) # memoization dictionary
fill!(C4,-1) # -1 implies not yet computed
C4[1] = 1 # Base case for n=0, C[n+1] provides nth term
# memoize partial sums as well
sum2store = similar(C4)
sum3store = similar(C4)
fill!(sum2store, -1)
fill!(sum3store, -1)
function catalan4(n,C)
    C[n+1] == -1 || return C[n+1]
    sum1 = convert(BigInt,0)
    for i in 1:n
        if sum2store[n-i+1] == -1
            sum2 = convert(BigInt,0)
            for j in 1:(n-i+1)
                if sum3store[n-i-j+2] == -1
                    sum3 = convert(BigInt,0)
                    for k in 1:(n-i-j+2)
                        sum3+= catalan4(k-1,C)*catalan4(n-i-j-k+2,C)
                    end
                    sum3store[n-i-j+2] = sum3
                end
                sum2 += catalan4(j-1,C)*sum3store[n-i-j+2]
            end
            sum2store[n-i+1] = sum2
        end
        sum1 += catalan4(i-1,C)*sum2store[n-i+1]
    end
    C[n+1] = sum1
    return sum1
end
for i in 1:numterms
    println(i,"\t",catalan4(200,C4))
end

max_stars_repo_name: octonion/examples

max_issues_repo_name: octonion/examples

max_forks_repo_name: octonion/examples


text:
using SimpleCG
using Base.Test

# No need to test for now.


text:
module WindowTrans

using DSP

# The windowed transforms work by sliding a window over the signal and
# performing the Fourier transform. The input signal is assumed to be
# apodized (zero at the ends of the interval).

function wind_transf(t, x, w)
    f = fftshift(fftfreq(length(t),1.0/(t[2]-t[1])))

    Cₓ = hcat([x.*circshift(w,i) for i = 1:length(t)]...)
    Wₓ = fftshift(fft(Cₓ, 1), 1)
    f,Wₓ
end

#=
The Gabor transform
$$
G_x(t,f) = \int_{-\infty}^\infty \mathrm{d}\tau
\exp[-\pi(\tau-t)^2]\exp(-j\pi f\tau)x(\tau)
$$

Here, we use a version with variable width.
=#

gabor(t, x, σ) = wind_transf(t, x, fftshift(exp.(-(t-mean(t)).^2/2σ^2)))

#=
The Wigner distribution function (WDF) is defined as [[1]]

$$
W_x(t,f) =
\int_{-\infty}^\infty d\tau
x\left(t+\frac{\tau}{2}\right)
x^*\left(t-\frac{\tau}{2}\right)
\exp(-j2\pi f\tau)
$$

Thus, for every $t$, we need to form

$$C_x\left(t+\frac{\tau}{2}, t-\frac{\tau}{2}\right)
\equiv x\left(t+\frac{\tau}{2}\right)
x^*\left(t-\frac{\tau}{2}\right),$$

but since the integration limits are $\pm\infty$, we instead form

$$x\left(t\right)
x^*\left(t-\tau\right).$$

The function is assumed to be windowed on input.

The good thing about the WDF is that the resolution is very high. The
bad thing is the cross term that shows up as soon as there are more
than one frequency present in the signal.

[1]: http://dx.doi.org/10.1109/TSP.2007.896271
=#
wigner(t, x) = wind_transf(t, x, fftshift(conj(reverse(x))))

#=
The "NMR" transform uses a window function that is derivating--apodizing:

$$
W(t) = t^n\exp(-\lambda_w t)
$$
=#
nmr(t, x, λ, n = 2) = wind_transf(t, x, t.^n.*exp(-λ*t))

export wind_transf, gabor, wigner, nmr

end # module


text:
# Tests for the ArbiterTask type.

facts("imports") do
    # Ensure that Arbiter is importable from the root module.
    @fact isa(ArbiterTask, DataType) --> true
end


text:
# Julia wrapper for header: /usr/include/scip/pub_misc.h
# Automatically generated using Clang.jl wrap_c

function SCIPstudentTGetCriticalValue(clevel, df)
    ccall((:SCIPstudentTGetCriticalValue, libscip), Cdouble, (SCIP_CONFIDENCELEVEL, Cint), clevel, df)
end

function SCIPcomputeTwoSampleTTestValue(meanx, meany, variancex, variancey, countx, county)
    ccall((:SCIPcomputeTwoSampleTTestValue, libscip), Cdouble, (Cdouble, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble), meanx, meany, variancex, variancey, countx, county)
end

function SCIPerf(x)
    ccall((:SCIPerf, libscip), Cdouble, (Cdouble,), x)
end

function SCIPnormalGetCriticalValue(clevel)
    ccall((:SCIPnormalGetCriticalValue, libscip), Cdouble, (SCIP_CONFIDENCELEVEL,), clevel)
end

function SCIPnormalCDF(mean, variance, value)
    ccall((:SCIPnormalCDF, libscip), Cdouble, (Cdouble, Cdouble, Cdouble), mean, variance, value)
end

function SCIPregressionGetNObservations(regression)
    ccall((:SCIPregressionGetNObservations, libscip), Cint, (Ptr{SCIP_REGRESSION},), regression)
end

function SCIPregressionGetSlope(regression)
    ccall((:SCIPregressionGetSlope, libscip), Cdouble, (Ptr{SCIP_REGRESSION},), regression)
end

function SCIPregressionGetIntercept(regression)
    ccall((:SCIPregressionGetIntercept, libscip), Cdouble, (Ptr{SCIP_REGRESSION},), regression)
end

function SCIPregressionRemoveObservation(regression, x, y)
    ccall((:SCIPregressionRemoveObservation, libscip), Cvoid, (Ptr{SCIP_REGRESSION}, Cdouble, Cdouble), regression, x, y)
end

function SCIPregressionAddObservation(regression, x, y)
    ccall((:SCIPregressionAddObservation, libscip), Cvoid, (Ptr{SCIP_REGRESSION}, Cdouble, Cdouble), regression, x, y)
end

function SCIPregressionReset(regression)
    ccall((:SCIPregressionReset, libscip), Cvoid, (Ptr{SCIP_REGRESSION},), regression)
end

function SCIPregressionCreate(regression)
    ccall((:SCIPregressionCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_REGRESSION}},), regression)
end

function SCIPregressionFree(regression)
    ccall((:SCIPregressionFree, libscip), Cvoid, (Ptr{Ptr{SCIP_REGRESSION}},), regression)
end

function SCIPgmlWriteNode(file, id, label, nodetype, fillcolor, bordercolor)
    ccall((:SCIPgmlWriteNode, libscip), Cvoid, (Ptr{FILE}, UInt32, Cstring, Cstring, Cstring, Cstring), file, id, label, nodetype, fillcolor, bordercolor)
end

function SCIPgmlWriteNodeWeight(file, id, label, nodetype, fillcolor, bordercolor, weight)
    ccall((:SCIPgmlWriteNodeWeight, libscip), Cvoid, (Ptr{FILE}, UInt32, Cstring, Cstring, Cstring, Cstring, Cdouble), file, id, label, nodetype, fillcolor, bordercolor, weight)
end

function SCIPgmlWriteEdge(file, source, target, label, color)
    ccall((:SCIPgmlWriteEdge, libscip), Cvoid, (Ptr{FILE}, UInt32, UInt32, Cstring, Cstring), file, source, target, label, color)
end

function SCIPgmlWriteArc(file, source, target, label, color)
    ccall((:SCIPgmlWriteArc, libscip), Cvoid, (Ptr{FILE}, UInt32, UInt32, Cstring, Cstring), file, source, target, label, color)
end

function SCIPgmlWriteOpening(file, directed)
    ccall((:SCIPgmlWriteOpening, libscip), Cvoid, (Ptr{FILE}, UInt32), file, directed)
end

function SCIPgmlWriteClosing(file)
    ccall((:SCIPgmlWriteClosing, libscip), Cvoid, (Ptr{FILE},), file)
end

function SCIPsparseSolCreate(sparsesol, vars, nvars, cleared)
    ccall((:SCIPsparseSolCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_SPARSESOL}}, Ptr{Ptr{SCIP_VAR}}, Cint, UInt32), sparsesol, vars, nvars, cleared)
end

function SCIPsparseSolFree(sparsesol)
    ccall((:SCIPsparseSolFree, libscip), Cvoid, (Ptr{Ptr{SCIP_SPARSESOL}},), sparsesol)
end

function SCIPsparseSolGetVars(sparsesol)
    ccall((:SCIPsparseSolGetVars, libscip), Ptr{Ptr{SCIP_VAR}}, (Ptr{SCIP_SPARSESOL},), sparsesol)
end

function SCIPsparseSolGetNVars(sparsesol)
    ccall((:SCIPsparseSolGetNVars, libscip), Cint, (Ptr{SCIP_SPARSESOL},), sparsesol)
end

function SCIPsparseSolGetLbs(sparsesol)
    ccall((:SCIPsparseSolGetLbs, libscip), Ptr{Clonglong}, (Ptr{SCIP_SPARSESOL},), sparsesol)
end

function SCIPsparseSolGetUbs(sparsesol)
    ccall((:SCIPsparseSolGetUbs, libscip), Ptr{Clonglong}, (Ptr{SCIP_SPARSESOL},), sparsesol)
end

function SCIPsparseSolGetFirstSol(sparsesol, sol, nvars)
    ccall((:SCIPsparseSolGetFirstSol, libscip), Cvoid, (Ptr{SCIP_SPARSESOL}, Ptr{Clonglong}, Cint), sparsesol, sol, nvars)
end

function SCIPsparseSolGetNextSol(sparsesol, sol, nvars)
    ccall((:SCIPsparseSolGetNextSol, libscip), UInt32, (Ptr{SCIP_SPARSESOL}, Ptr{Clonglong}, Cint), sparsesol, sol, nvars)
end

function SCIPqueueCreate(queue, initsize, sizefac)
    ccall((:SCIPqueueCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_QUEUE}}, Cint, Cdouble), queue, initsize, sizefac)
end

function SCIPqueueFree(queue)
    ccall((:SCIPqueueFree, libscip), Cvoid, (Ptr{Ptr{SCIP_QUEUE}},), queue)
end

function SCIPqueueClear(queue)
    ccall((:SCIPqueueClear, libscip), Cvoid, (Ptr{SCIP_QUEUE},), queue)
end

function SCIPqueueInsert(queue, elem)
    ccall((:SCIPqueueInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_QUEUE}, Ptr{Cvoid}), queue, elem)
end

function SCIPqueueRemove(queue)
    ccall((:SCIPqueueRemove, libscip), Ptr{Cvoid}, (Ptr{SCIP_QUEUE},), queue)
end

function SCIPqueueFirst(queue)
    ccall((:SCIPqueueFirst, libscip), Ptr{Cvoid}, (Ptr{SCIP_QUEUE},), queue)
end

function SCIPqueueIsEmpty(queue)
    ccall((:SCIPqueueIsEmpty, libscip), UInt32, (Ptr{SCIP_QUEUE},), queue)
end

function SCIPqueueNElems(queue)
    ccall((:SCIPqueueNElems, libscip), Cint, (Ptr{SCIP_QUEUE},), queue)
end

function SCIPpqueueCreate(pqueue, initsize, sizefac, ptrcomp)
    ccall((:SCIPpqueueCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_PQUEUE}}, Cint, Cdouble, Ptr{Cvoid}), pqueue, initsize, sizefac, ptrcomp)
end

function SCIPpqueueFree(pqueue)
    ccall((:SCIPpqueueFree, libscip), Cvoid, (Ptr{Ptr{SCIP_PQUEUE}},), pqueue)
end

function SCIPpqueueClear(pqueue)
    ccall((:SCIPpqueueClear, libscip), Cvoid, (Ptr{SCIP_PQUEUE},), pqueue)
end

function SCIPpqueueInsert(pqueue, elem)
    ccall((:SCIPpqueueInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_PQUEUE}, Ptr{Cvoid}), pqueue, elem)
end

function SCIPpqueueRemove(pqueue)
    ccall((:SCIPpqueueRemove, libscip), Ptr{Cvoid}, (Ptr{SCIP_PQUEUE},), pqueue)
end

function SCIPpqueueFirst(pqueue)
    ccall((:SCIPpqueueFirst, libscip), Ptr{Cvoid}, (Ptr{SCIP_PQUEUE},), pqueue)
end

function SCIPpqueueNElems(pqueue)
    ccall((:SCIPpqueueNElems, libscip), Cint, (Ptr{SCIP_PQUEUE},), pqueue)
end

function SCIPpqueueElems(pqueue)
    ccall((:SCIPpqueueElems, libscip), Ptr{Ptr{Cvoid}}, (Ptr{SCIP_PQUEUE},), pqueue)
end

function SCIPrealHashCode(x)
    ccall((:SCIPrealHashCode, libscip), UInt32, (Cdouble,), x)
end

function SCIPhashtableCreate(hashtable, blkmem, tablesize, hashgetkey, hashkeyeq, hashkeyval, userptr)
    ccall((:SCIPhashtableCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_HASHTABLE}}, Ptr{BMS_BLKMEM}, Cint, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), hashtable, blkmem, tablesize, hashgetkey, hashkeyeq, hashkeyval, userptr)
end

function SCIPhashtableFree(hashtable)
    ccall((:SCIPhashtableFree, libscip), Cvoid, (Ptr{Ptr{SCIP_HASHTABLE}},), hashtable)
end

function SCIPhashtableClear(hashtable)
    ccall((:SCIPhashtableClear, libscip), Cvoid, (Ptr{SCIP_HASHTABLE},), hashtable)
end

function SCIPhashtableInsert(hashtable, element)
    ccall((:SCIPhashtableInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHTABLE}, Ptr{Cvoid}), hashtable, element)
end

function SCIPhashtableSafeInsert(hashtable, element)
    ccall((:SCIPhashtableSafeInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHTABLE}, Ptr{Cvoid}), hashtable, element)
end

function SCIPhashtableRetrieve(hashtable, key)
    ccall((:SCIPhashtableRetrieve, libscip), Ptr{Cvoid}, (Ptr{SCIP_HASHTABLE}, Ptr{Cvoid}), hashtable, key)
end

function SCIPhashtableExists(hashtable, element)
    ccall((:SCIPhashtableExists, libscip), UInt32, (Ptr{SCIP_HASHTABLE}, Ptr{Cvoid}), hashtable, element)
end

function SCIPhashtableRemove(hashtable, element)
    ccall((:SCIPhashtableRemove, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHTABLE}, Ptr{Cvoid}), hashtable, element)
end

function SCIPhashtableRemoveAll(hashtable)
    ccall((:SCIPhashtableRemoveAll, libscip), Cvoid, (Ptr{SCIP_HASHTABLE},), hashtable)
end

function SCIPhashtableGetNElements(hashtable)
    ccall((:SCIPhashtableGetNElements, libscip), Clonglong, (Ptr{SCIP_HASHTABLE},), hashtable)
end

function SCIPhashtableGetNEntries(hashtable)
    ccall((:SCIPhashtableGetNEntries, libscip), Cint, (Ptr{SCIP_HASHTABLE},), hashtable)
end

function SCIPhashtableGetEntry(hashtable, entryidx)
    ccall((:SCIPhashtableGetEntry, libscip), Ptr{Cvoid}, (Ptr{SCIP_HASHTABLE}, Cint), hashtable, entryidx)
end

function SCIPhashtableGetLoad(hashtable)
    ccall((:SCIPhashtableGetLoad, libscip), Cdouble, (Ptr{SCIP_HASHTABLE},), hashtable)
end

function SCIPhashtablePrintStatistics(hashtable, messagehdlr)
    ccall((:SCIPhashtablePrintStatistics, libscip), Cvoid, (Ptr{SCIP_HASHTABLE}, Ptr{SCIP_MESSAGEHDLR}), hashtable, messagehdlr)
end

function SCIPcalcMultihashSize(minsize)
    ccall((:SCIPcalcMultihashSize, libscip), Cint, (Cint,), minsize)
end

function SCIPmultihashCreate(multihash, blkmem, tablesize, hashgetkey, hashkeyeq, hashkeyval, userptr)
    ccall((:SCIPmultihashCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_MULTIHASH}}, Ptr{BMS_BLKMEM}, Cint, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), multihash, blkmem, tablesize, hashgetkey, hashkeyeq, hashkeyval, userptr)
end

function SCIPmultihashFree(multihash)
    ccall((:SCIPmultihashFree, libscip), Cvoid, (Ptr{Ptr{SCIP_MULTIHASH}},), multihash)
end

function SCIPmultihashInsert(multihash, element)
    ccall((:SCIPmultihashInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_MULTIHASH}, Ptr{Cvoid}), multihash, element)
end

function SCIPmultihashSafeInsert(multihash, element)
    ccall((:SCIPmultihashSafeInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_MULTIHASH}, Ptr{Cvoid}), multihash, element)
end

function SCIPmultihashRetrieve(multihash, key)
    ccall((:SCIPmultihashRetrieve, libscip), Ptr{Cvoid}, (Ptr{SCIP_MULTIHASH}, Ptr{Cvoid}), multihash, key)
end

function SCIPmultihashRetrieveNext(multihash, multihashlist, key)
    ccall((:SCIPmultihashRetrieveNext, libscip), Ptr{Cvoid}, (Ptr{SCIP_MULTIHASH}, Ptr{Ptr{SCIP_MULTIHASHLIST}}, Ptr{Cvoid}), multihash, multihashlist, key)
end

function SCIPmultihashExists(multihash, element)
    ccall((:SCIPmultihashExists, libscip), UInt32, (Ptr{SCIP_MULTIHASH}, Ptr{Cvoid}), multihash, element)
end

function SCIPmultihashRemove(multihash, element)
    ccall((:SCIPmultihashRemove, libscip), SCIP_RETCODE, (Ptr{SCIP_MULTIHASH}, Ptr{Cvoid}), multihash, element)
end

function SCIPmultihashRemoveAll(multihash)
    ccall((:SCIPmultihashRemoveAll, libscip), Cvoid, (Ptr{SCIP_MULTIHASH},), multihash)
end

function SCIPmultihashGetNElements(multihash)
    ccall((:SCIPmultihashGetNElements, libscip), Clonglong, (Ptr{SCIP_MULTIHASH},), multihash)
end

function SCIPmultihashGetLoad(multihash)
    ccall((:SCIPmultihashGetLoad, libscip), Cdouble, (Ptr{SCIP_MULTIHASH},), multihash)
end

function SCIPmultihashPrintStatistics(multihash, messagehdlr)
    ccall((:SCIPmultihashPrintStatistics, libscip), Cvoid, (Ptr{SCIP_MULTIHASH}, Ptr{SCIP_MESSAGEHDLR}), multihash, messagehdlr)
end

function SCIPhashKeyEqString(userptr, key1, key2)
    ccall((:SCIPhashKeyEqString, libscip), UInt32, (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), userptr, key1, key2)
end

function SCIPhashKeyValString(userptr, key)
    ccall((:SCIPhashKeyValString, libscip), UInt64, (Ptr{Cvoid}, Ptr{Cvoid}), userptr, key)
end

function SCIPhashGetKeyStandard(userptr, elem)
    ccall((:SCIPhashGetKeyStandard, libscip), Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}), userptr, elem)
end

function SCIPhashKeyEqPtr(userptr, key1, key2)
    ccall((:SCIPhashKeyEqPtr, libscip), UInt32, (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), userptr, key1, key2)
end

function SCIPhashKeyValPtr(userptr, key)
    ccall((:SCIPhashKeyValPtr, libscip), UInt64, (Ptr{Cvoid}, Ptr{Cvoid}), userptr, key)
end

function SCIPhashmapCreate(hashmap, blkmem, mapsize)
    ccall((:SCIPhashmapCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_HASHMAP}}, Ptr{BMS_BLKMEM}, Cint), hashmap, blkmem, mapsize)
end

function SCIPhashmapFree(hashmap)
    ccall((:SCIPhashmapFree, libscip), Cvoid, (Ptr{Ptr{SCIP_HASHMAP}},), hashmap)
end

function SCIPhashmapInsert(hashmap, origin, image)
    ccall((:SCIPhashmapInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}, Ptr{Cvoid}), hashmap, origin, image)
end

function SCIPhashmapInsertReal(hashmap, origin, image)
    ccall((:SCIPhashmapInsertReal, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}, Cdouble), hashmap, origin, image)
end

function SCIPhashmapGetImage(hashmap, origin)
    ccall((:SCIPhashmapGetImage, libscip), Ptr{Cvoid}, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}), hashmap, origin)
end

function SCIPhashmapGetImageReal(hashmap, origin)
    ccall((:SCIPhashmapGetImageReal, libscip), Cdouble, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}), hashmap, origin)
end

function SCIPhashmapSetImage(hashmap, origin, image)
    ccall((:SCIPhashmapSetImage, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}, Ptr{Cvoid}), hashmap, origin, image)
end

function SCIPhashmapSetImageReal(hashmap, origin, image)
    ccall((:SCIPhashmapSetImageReal, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}, Cdouble), hashmap, origin, image)
end

function SCIPhashmapExists(hashmap, origin)
    ccall((:SCIPhashmapExists, libscip), UInt32, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}), hashmap, origin)
end

function SCIPhashmapRemove(hashmap, origin)
    ccall((:SCIPhashmapRemove, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHMAP}, Ptr{Cvoid}), hashmap, origin)
end

function SCIPhashmapPrintStatistics(hashmap, messagehdlr)
    ccall((:SCIPhashmapPrintStatistics, libscip), Cvoid, (Ptr{SCIP_HASHMAP}, Ptr{SCIP_MESSAGEHDLR}), hashmap, messagehdlr)
end

function SCIPhashmapIsEmpty(hashmap)
    ccall((:SCIPhashmapIsEmpty, libscip), UInt32, (Ptr{SCIP_HASHMAP},), hashmap)
end

function SCIPhashmapGetNElements(hashmap)
    ccall((:SCIPhashmapGetNElements, libscip), Cint, (Ptr{SCIP_HASHMAP},), hashmap)
end

function SCIPhashmapGetNEntries(hashmap)
    ccall((:SCIPhashmapGetNEntries, libscip), Cint, (Ptr{SCIP_HASHMAP},), hashmap)
end

function SCIPhashmapGetEntry(hashmap, entryidx)
    ccall((:SCIPhashmapGetEntry, libscip), Ptr{SCIP_HASHMAPENTRY}, (Ptr{SCIP_HASHMAP}, Cint), hashmap, entryidx)
end

function SCIPhashmapEntryGetOrigin(entry)
    ccall((:SCIPhashmapEntryGetOrigin, libscip), Ptr{Cvoid}, (Ptr{SCIP_HASHMAPENTRY},), entry)
end

function SCIPhashmapEntryGetImage(entry)
    ccall((:SCIPhashmapEntryGetImage, libscip), Ptr{Cvoid}, (Ptr{SCIP_HASHMAPENTRY},), entry)
end

function SCIPhashmapEntryGetImageReal(entry)
    ccall((:SCIPhashmapEntryGetImageReal, libscip), Cdouble, (Ptr{SCIP_HASHMAPENTRY},), entry)
end

function SCIPhashmapEntrySetImage(entry, image)
    ccall((:SCIPhashmapEntrySetImage, libscip), Cvoid, (Ptr{SCIP_HASHMAPENTRY}, Ptr{Cvoid}), entry, image)
end

function SCIPhashmapEntrySetImageReal(entry, image)
    ccall((:SCIPhashmapEntrySetImageReal, libscip), Cvoid, (Ptr{SCIP_HASHMAPENTRY}, Cdouble), entry, image)
end

function SCIPhashmapRemoveAll(hashmap)
    ccall((:SCIPhashmapRemoveAll, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHMAP},), hashmap)
end

function SCIPhashsetCreate(hashset, blkmem, size)
    ccall((:SCIPhashsetCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_HASHSET}}, Ptr{BMS_BLKMEM}, Cint), hashset, blkmem, size)
end

function SCIPhashsetFree(hashset, blkmem)
    ccall((:SCIPhashsetFree, libscip), Cvoid, (Ptr{Ptr{SCIP_HASHSET}}, Ptr{BMS_BLKMEM}), hashset, blkmem)
end

function SCIPhashsetInsert(hashset, blkmem, element)
    ccall((:SCIPhashsetInsert, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHSET}, Ptr{BMS_BLKMEM}, Ptr{Cvoid}), hashset, blkmem, element)
end

function SCIPhashsetExists(hashset, element)
    ccall((:SCIPhashsetExists, libscip), UInt32, (Ptr{SCIP_HASHSET}, Ptr{Cvoid}), hashset, element)
end

function SCIPhashsetRemove(hashset, element)
    ccall((:SCIPhashsetRemove, libscip), SCIP_RETCODE, (Ptr{SCIP_HASHSET}, Ptr{Cvoid}), hashset, element)
end

function SCIPhashsetPrintStatistics(hashset, messagehdlr)
    ccall((:SCIPhashsetPrintStatistics, libscip), Cvoid, (Ptr{SCIP_HASHSET}, Ptr{SCIP_MESSAGEHDLR}), hashset, messagehdlr)
end

function SCIPhashsetIsEmpty(hashset)
    ccall((:SCIPhashsetIsEmpty, libscip), UInt32, (Ptr{SCIP_HASHSET},), hashset)
end

function SCIPhashsetGetNElements(hashset)
    ccall((:SCIPhashsetGetNElements, libscip), Cint, (Ptr{SCIP_HASHSET},), hashset)
end

function SCIPhashsetGetNSlots(hashset)
    ccall((:SCIPhashsetGetNSlots, libscip), Cint, (Ptr{SCIP_HASHSET},), hashset)
end

function SCIPhashsetGetSlots(hashset)
    ccall((:SCIPhashsetGetSlots, libscip), Ptr{Ptr{Cvoid}}, (Ptr{SCIP_HASHSET},), hashset)
end

function SCIPhashsetRemoveAll(hashset)
    ccall((:SCIPhashsetRemoveAll, libscip), Cvoid, (Ptr{SCIP_HASHSET},), hashset)
end

function SCIPactivityCreate(activity, var, duration, demand)
    ccall((:SCIPactivityCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_RESOURCEACTIVITY}}, Ptr{SCIP_VAR}, Cint, Cint), activity, var, duration, demand)
end

function SCIPactivityFree(activity)
    ccall((:SCIPactivityFree, libscip), Cvoid, (Ptr{Ptr{SCIP_RESOURCEACTIVITY}},), activity)
end

function SCIPactivityGetVar(activity)
    ccall((:SCIPactivityGetVar, libscip), Ptr{SCIP_VAR}, (Ptr{SCIP_RESOURCEACTIVITY},), activity)
end

function SCIPactivityGetDuration(activity)
    ccall((:SCIPactivityGetDuration, libscip), Cint, (Ptr{SCIP_RESOURCEACTIVITY},), activity)
end

function SCIPactivityGetDemand(activity)
    ccall((:SCIPactivityGetDemand, libscip), Cint, (Ptr{SCIP_RESOURCEACTIVITY},), activity)
end

function SCIPactivityGetEnergy(activity)
    ccall((:SCIPactivityGetEnergy, libscip), Cint, (Ptr{SCIP_RESOURCEACTIVITY},), activity)
end

function SCIPprofileCreate(profile, capacity)
    ccall((:SCIPprofileCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_PROFILE}}, Cint), profile, capacity)
end

function SCIPprofileFree(profile)
    ccall((:SCIPprofileFree, libscip), Cvoid, (Ptr{Ptr{SCIP_PROFILE}},), profile)
end

function SCIPprofilePrint(profile, messagehdlr, file)
    ccall((:SCIPprofilePrint, libscip), Cvoid, (Ptr{SCIP_PROFILE}, Ptr{SCIP_MESSAGEHDLR}, Ptr{FILE}), profile, messagehdlr, file)
end

function SCIPprofileGetCapacity(profile)
    ccall((:SCIPprofileGetCapacity, libscip), Cint, (Ptr{SCIP_PROFILE},), profile)
end

function SCIPprofileGetNTimepoints(profile)
    ccall((:SCIPprofileGetNTimepoints, libscip), Cint, (Ptr{SCIP_PROFILE},), profile)
end

function SCIPprofileGetTimepoints(profile)
    ccall((:SCIPprofileGetTimepoints, libscip), Ptr{Cint}, (Ptr{SCIP_PROFILE},), profile)
end

function SCIPprofileGetLoads(profile)
    ccall((:SCIPprofileGetLoads, libscip), Ptr{Cint}, (Ptr{SCIP_PROFILE},), profile)
end

function SCIPprofileGetTime(profile, pos)
    ccall((:SCIPprofileGetTime, libscip), Cint, (Ptr{SCIP_PROFILE}, Cint), profile, pos)
end

function SCIPprofileGetLoad(profile, pos)
    ccall((:SCIPprofileGetLoad, libscip), Cint, (Ptr{SCIP_PROFILE}, Cint), profile, pos)
end

function SCIPprofileFindLeft(profile, timepoint, pos)
    ccall((:SCIPprofileFindLeft, libscip), UInt32, (Ptr{SCIP_PROFILE}, Cint, Ptr{Cint}), profile, timepoint, pos)
end

function SCIPprofileInsertCore(profile, left, right, height, pos, infeasible)
    ccall((:SCIPprofileInsertCore, libscip), SCIP_RETCODE, (Ptr{SCIP_PROFILE}, Cint, Cint, Cint, Ptr{Cint}, Ptr{UInt32}), profile, left, right, height, pos, infeasible)
end

function SCIPprofileDeleteCore(profile, left, right, height)
    ccall((:SCIPprofileDeleteCore, libscip), SCIP_RETCODE, (Ptr{SCIP_PROFILE}, Cint, Cint, Cint), profile, left, right, height)
end

function SCIPprofileGetEarliestFeasibleStart(profile, est, lst, duration, height, infeasible)
    ccall((:SCIPprofileGetEarliestFeasibleStart, libscip), Cint, (Ptr{SCIP_PROFILE}, Cint, Cint, Cint, Cint, Ptr{UInt32}), profile, est, lst, duration, height, infeasible)
end

function SCIPprofileGetLatestFeasibleStart(profile, lb, ub, duration, height, infeasible)
    ccall((:SCIPprofileGetLatestFeasibleStart, libscip), Cint, (Ptr{SCIP_PROFILE}, Cint, Cint, Cint, Cint, Ptr{UInt32}), profile, lb, ub, duration, height, infeasible)
end

function SCIPdigraphResize(digraph, nnodes)
    ccall((:SCIPdigraphResize, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH}, Cint), digraph, nnodes)
end

function SCIPdigraphSetSizes(digraph, sizes)
    ccall((:SCIPdigraphSetSizes, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH}, Ptr{Cint}), digraph, sizes)
end

function SCIPdigraphFree(digraph)
    ccall((:SCIPdigraphFree, libscip), Cvoid, (Ptr{Ptr{SCIP_DIGRAPH}},), digraph)
end

function SCIPdigraphAddArc(digraph, startnode, endnode, data)
    ccall((:SCIPdigraphAddArc, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH}, Cint, Cint, Ptr{Cvoid}), digraph, startnode, endnode, data)
end

function SCIPdigraphAddArcSafe(digraph, startnode, endnode, data)
    ccall((:SCIPdigraphAddArcSafe, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH}, Cint, Cint, Ptr{Cvoid}), digraph, startnode, endnode, data)
end

function SCIPdigraphSetNSuccessors(digraph, node, nsuccessors)
    ccall((:SCIPdigraphSetNSuccessors, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH}, Cint, Cint), digraph, node, nsuccessors)
end

function SCIPdigraphGetNNodes(digraph)
    ccall((:SCIPdigraphGetNNodes, libscip), Cint, (Ptr{SCIP_DIGRAPH},), digraph)
end

function SCIPdigraphGetNodeData(digraph, node)
    ccall((:SCIPdigraphGetNodeData, libscip), Ptr{Cvoid}, (Ptr{SCIP_DIGRAPH}, Cint), digraph, node)
end

function SCIPdigraphSetNodeData(digraph, dataptr, node)
    ccall((:SCIPdigraphSetNodeData, libscip), Cvoid, (Ptr{SCIP_DIGRAPH}, Ptr{Cvoid}, Cint), digraph, dataptr, node)
end

function SCIPdigraphGetNArcs(digraph)
    ccall((:SCIPdigraphGetNArcs, libscip), Cint, (Ptr{SCIP_DIGRAPH},), digraph)
end

function SCIPdigraphGetNSuccessors(digraph, node)
    ccall((:SCIPdigraphGetNSuccessors, libscip), Cint, (Ptr{SCIP_DIGRAPH}, Cint), digraph, node)
end

function SCIPdigraphGetSuccessors(digraph, node)
    ccall((:SCIPdigraphGetSuccessors, libscip), Ptr{Cint}, (Ptr{SCIP_DIGRAPH}, Cint), digraph, node)
end

function SCIPdigraphGetSuccessorsData(digraph, node)
    ccall((:SCIPdigraphGetSuccessorsData, libscip), Ptr{Ptr{Cvoid}}, (Ptr{SCIP_DIGRAPH}, Cint), digraph, node)
end

function SCIPdigraphComputeUndirectedComponents(digraph, minsize, components, ncomponents)
    ccall((:SCIPdigraphComputeUndirectedComponents, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH}, Cint, Ptr{Cint}, Ptr{Cint}), digraph, minsize, components, ncomponents)
end

function SCIPdigraphComputeDirectedComponents(digraph, compidx, strongcomponents, strongcompstartidx, nstrongcomponents)
    ccall((:SCIPdigraphComputeDirectedComponents, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), digraph, compidx, strongcomponents, strongcompstartidx, nstrongcomponents)
end

function SCIPdigraphTopoSortComponents(digraph)
    ccall((:SCIPdigraphTopoSortComponents, libscip), SCIP_RETCODE, (Ptr{SCIP_DIGRAPH},), digraph)
end

function SCIPdigraphGetNComponents(digraph)
    ccall((:SCIPdigraphGetNComponents, libscip), Cint, (Ptr{SCIP_DIGRAPH},), digraph)
end

function SCIPdigraphGetComponent(digraph, compidx, nodes, nnodes)
    ccall((:SCIPdigraphGetComponent, libscip), Cvoid, (Ptr{SCIP_DIGRAPH}, Cint, Ptr{Ptr{Cint}}, Ptr{Cint}), digraph, compidx, nodes, nnodes)
end

function SCIPdigraphFreeComponents(digraph)
    ccall((:SCIPdigraphFreeComponents, libscip), Cvoid, (Ptr{SCIP_DIGRAPH},), digraph)
end

function SCIPdigraphPrint(digraph, messagehdlr, file)
    ccall((:SCIPdigraphPrint, libscip), Cvoid, (Ptr{SCIP_DIGRAPH}, Ptr{SCIP_MESSAGEHDLR}, Ptr{FILE}), digraph, messagehdlr, file)
end

function SCIPdigraphPrintGml(digraph, file)
    ccall((:SCIPdigraphPrintGml, libscip), Cvoid, (Ptr{SCIP_DIGRAPH}, Ptr{FILE}), digraph, file)
end

function SCIPdigraphPrintComponents(digraph, messagehdlr, file)
    ccall((:SCIPdigraphPrintComponents, libscip), Cvoid, (Ptr{SCIP_DIGRAPH}, Ptr{SCIP_MESSAGEHDLR}, Ptr{FILE}), digraph, messagehdlr, file)
end

function SCIPbtnodeCreate(tree, node, dataptr)
    ccall((:SCIPbtnodeCreate, libscip), SCIP_RETCODE, (Ptr{SCIP_BT}, Ptr{Ptr{SCIP_BTNODE}}, Ptr{Cvoid}), tree, node, dataptr)
end

function SCIPbtnodeFree(tree, node)
    ccall((:SCIPbtnodeFree, libscip), Cvoid, (Ptr{SCIP_BT}, Ptr{Ptr{SCIP_BTNODE}}), tree, node)
end

function SCIPbtnodeGetData(node)
    ccall((:SCIPbtnodeGetData, libscip), Ptr{Cvoid}, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeGetParent(node)
    ccall((:SCIPbtnodeGetParent, libscip), Ptr{SCIP_BTNODE}, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeGetLeftchild(node)
    ccall((:SCIPbtnodeGetLeftchild, libscip), Ptr{SCIP_BTNODE}, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeGetRightchild(node)
    ccall((:SCIPbtnodeGetRightchild, libscip), Ptr{SCIP_BTNODE}, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeGetSibling(node)
    ccall((:SCIPbtnodeGetSibling, libscip), Ptr{SCIP_BTNODE}, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeIsRoot(node)
    ccall((:SCIPbtnodeIsRoot, libscip), UInt32, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeIsLeaf(node)
    ccall((:SCIPbtnodeIsLeaf, libscip), UInt32, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeIsLeftchild(node)
    ccall((:SCIPbtnodeIsLeftchild, libscip), UInt32, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeIsRightchild(node)
    ccall((:SCIPbtnodeIsRightchild, libscip), UInt32, (Ptr{SCIP_BTNODE},), node)
end

function SCIPbtnodeSetData(node, dataptr)
    ccall((:SCIPbtnodeSetData, libscip), Cvoid, (Ptr{SCIP_BTNODE}, Ptr{Cvoid}), node, dataptr)
end

function SCIPbtnodeSetParent(node, parent)
    ccall((:SCIPbtnodeSetParent, libscip), Cvoid, (Ptr{SCIP_BTNODE}, Ptr{SCIP_BTNODE}), node, parent)
end

function SCIPbtnodeSetLeftchild(node, left)
    ccall((:SCIPbtnodeSetLeftchild, libscip), Cvoid, (Ptr{SCIP_BTNODE}, Ptr{SCIP_BTNODE}), node, left)
end

function SCIPbtnodeSetRightchild(node, right)
    ccall((:SCIPbtnodeSetRightchild, libscip), Cvoid, (Ptr{SCIP_BTNODE}, Ptr{SCIP_BTNODE}), node, right)
end

function SCIPbtCreate(tree, blkmem)
    ccall((:SCIPbtCreate, libscip), SCIP_RETCODE, (Ptr{Ptr{SCIP_BT}}, Ptr{BMS_BLKMEM}), tree, blkmem)
end

function SCIPbtFree(tree)
    ccall((:SCIPbtFree, libscip), Cvoid, (Ptr{Ptr{SCIP_BT}},), tree)
end

function SCIPbtPrintGml(tree, file)
    ccall((:SCIPbtPrintGml, libscip), Cvoid, (Ptr{SCIP_BT}, Ptr{FILE}), tree, file)
end

function SCIPbtIsEmpty(tree)
    ccall((:SCIPbtIsEmpty, libscip), UInt32, (Ptr{SCIP_BT},), tree)
end

function SCIPbtGetRoot(tree)
    ccall((:SCIPbtGetRoot, libscip), Ptr{SCIP_BTNODE}, (Ptr{SCIP_BT},), tree)
end

function SCIPbtSetRoot(tree, root)
    ccall((:SCIPbtSetRoot, libscip), Cvoid, (Ptr{SCIP_BT}, Ptr{SCIP_BTNODE}), tree, root)
end

function SCIPdisjointsetClear(djset)
    ccall((:SCIPdisjointsetClear, libscip), Cvoid, (Ptr{SCIP_DISJOINTSET},), djset)
end

function SCIPdisjointsetFind(djset, element)
    ccall((:SCIPdisjointsetFind, libscip), Cint, (Ptr{SCIP_DISJOINTSET}, Cint), djset, element)
end

function SCIPdisjointsetUnion(djset, p, q, forcerepofp)
    ccall((:SCIPdisjointsetUnion, libscip), Cvoid, (Ptr{SCIP_DISJOINTSET}, Cint, Cint, UInt32), djset, p, q, forcerepofp)
end

function SCIPdisjointsetGetComponentCount(djset)
    ccall((:SCIPdisjointsetGetComponentCount, libscip), Cint, (Ptr{SCIP_DISJOINTSET},), djset)
end

function SCIPdisjointsetGetSize(djset)
    ccall((:SCIPdisjointsetGetSize, libscip), Cint, (Ptr{SCIP_DISJOINTSET},), djset)
end

function SCIPcalcMachineEpsilon()
    ccall((:SCIPcalcMachineEpsilon, libscip), Cdouble, ())
end

function SCIPnextafter(from, to)
    ccall((:SCIPnextafter, libscip), Cdouble, (Cdouble, Cdouble), from, to)
end

function SCIPcalcGreComDiv(val1, val2)
    ccall((:SCIPcalcGreComDiv, libscip), Clonglong, (Clonglong, Clonglong), val1, val2)
end

function SCIPcalcSmaComMul(val1, val2)
    ccall((:SCIPcalcSmaComMul, libscip), Clonglong, (Clonglong, Clonglong), val1, val2)
end

function SCIPcalcBinomCoef(n, m)
    ccall((:SCIPcalcBinomCoef, libscip), Clonglong, (Cint, Cint), n, m)
end

function SCIPrealToRational(val, mindelta, maxdelta, maxdnom, nominator, denominator)
    ccall((:SCIPrealToRational, libscip), UInt32, (Cdouble, Cdouble, Cdouble, Clonglong, Ptr{Clonglong}, Ptr{Clonglong}), val, mindelta, maxdelta, maxdnom, nominator, denominator)
end

function SCIPcalcIntegralScalar(vals, nvals, mindelta, maxdelta, maxdnom, maxscale, intscalar, success)
    ccall((:SCIPcalcIntegralScalar, libscip), SCIP_RETCODE, (Ptr{Cdouble}, Cint, Cdouble, Cdouble, Clonglong, Cdouble, Ptr{Cdouble}, Ptr{UInt32}), vals, nvals, mindelta, maxdelta, maxdnom, maxscale, intscalar, success)
end

function SCIPfindSimpleRational(lb, ub, maxdnom, nominator, denominator)
    ccall((:SCIPfindSimpleRational, libscip), UInt32, (Cdouble, Cdouble, Clonglong, Ptr{Clonglong}, Ptr{Clonglong}), lb, ub, maxdnom, nominator, denominator)
end

function SCIPselectSimpleValue(lb, ub, maxdnom)
    ccall((:SCIPselectSimpleValue, libscip), Cdouble, (Cdouble, Cdouble, Clonglong), lb, ub, maxdnom)
end

function SCIPrelDiff(val1, val2)
    ccall((:SCIPrelDiff, libscip), Cdouble, (Cdouble, Cdouble), val1, val2)
end

function SCIPcomputeGap(eps, inf, primalbound, dualbound)
    ccall((:SCIPcomputeGap, libscip), Cdouble, (Cdouble, Cdouble, Cdouble, Cdouble), eps, inf, primalbound, dualbound)
end

function SCIPgetRandomInt(minrandval, maxrandval, seedp)
    ccall((:SCIPgetRandomInt, libscip), Cint, (Cint, Cint, Ptr{UInt32}), minrandval, maxrandval, seedp)
end

function SCIPrandomGetInt(randgen, minrandval, maxrandval)
    ccall((:SCIPrandomGetInt, libscip), Cint, (Ptr{SCIP_RANDNUMGEN}, Cint, Cint), randgen, minrandval, maxrandval)
end

function SCIPrandomGetSubset(randgen, set, nelems, subset, nsubelems)
    ccall((:SCIPrandomGetSubset, libscip), SCIP_RETCODE, (Ptr{SCIP_RANDNUMGEN}, Ptr{Ptr{Cvoid}}, Cint, Ptr{Ptr{Cvoid}}, Cint), randgen, set, nelems, subset, nsubelems)
end

function SCIPrandomGetReal(randgen, minrandval, maxrandval)
    ccall((:SCIPrandomGetReal, libscip), Cdouble, (Ptr{SCIP_RANDNUMGEN}, Cdouble, Cdouble), randgen, minrandval, maxrandval)
end

function SCIPgetRandomReal(minrandval, maxrandval, seedp)
    ccall((:SCIPgetRandomReal, libscip), Cdouble, (Cdouble, Cdouble, Ptr{UInt32}), minrandval, maxrandval, seedp)
end

function SCIPgetRandomSubset(set, nelems, subset, nsubelems, randseed)
    ccall((:SCIPgetRandomSubset, libscip), SCIP_RETCODE, (Ptr{Ptr{Cvoid}}, Cint, Ptr{Ptr{Cvoid}}, Cint, UInt32), set, nelems, subset, nsubelems, randseed)
end

function SCIPswapInts(value1, value2)
    ccall((:SCIPswapInts, libscip), Cvoid, (Ptr{Cint}, Ptr{Cint}), value1, value2)
end

function SCIPswapReals(value1, value2)
    ccall((:SCIPswapReals, libscip), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble}), value1, value2)
end

function SCIPswapPointers(pointer1, pointer2)
    ccall((:SCIPswapPointers, libscip), Cvoid, (Ptr{Ptr{Cvoid}}, Ptr{Ptr{Cvoid}}), pointer1, pointer2)
end

function SCIPpermuteIntArray(array, _begin, _end, randseed)
    ccall((:SCIPpermuteIntArray, libscip), Cvoid, (Ptr{Cint}, Cint, Cint, Ptr{UInt32}), array, _begin, _end, randseed)
end

function SCIPrandomPermuteIntArray(randgen, array, _begin, _end)
    ccall((:SCIPrandomPermuteIntArray, libscip), Cvoid, (Ptr{SCIP_RANDNUMGEN}, Ptr{Cint}, Cint, Cint), randgen, array, _begin, _end)
end

function SCIPrandomPermuteArray(randgen, array, _begin, _end)
    ccall((:SCIPrandomPermuteArray, libscip), Cvoid, (Ptr{SCIP_RANDNUMGEN}, Ptr{Ptr{Cvoid}}, Cint, Cint), randgen, array, _begin, _end)
end

function SCIPpermuteArray(array, _begin, _end, randseed)
    ccall((:SCIPpermuteArray, libscip), Cvoid, (Ptr{Ptr{Cvoid}}, Cint, Cint, Ptr{UInt32}), array, _begin, _end, randseed)
end

function SCIPcomputeArraysIntersection(array1, narray1, array2, narray2, intersectarray, nintersectarray)
    ccall((:SCIPcomputeArraysIntersection, libscip), SCIP_RETCODE, (Ptr{Cint}, Cint, Ptr{Cint}, Cint, Ptr{Cint}, Ptr{Cint}), array1, narray1, array2, narray2, intersectarray, nintersectarray)
end

function SCIPcomputeArraysSetminus(array1, narray1, array2, narray2, setminusarray, nsetminusarray)
    ccall((:SCIPcomputeArraysSetminus, libscip), SCIP_RETCODE, (Ptr{Cint}, Cint, Ptr{Cint}, Cint, Ptr{Cint}, Ptr{Cint}), array1, narray1, array2, narray2, setminusarray, nsetminusarray)
end

function SCIPmemccpy(dest, src, stop, cnt)
    ccall((:SCIPmemccpy, libscip), Cint, (Cstring, Cstring, UInt8, UInt32), dest, src, stop, cnt)
end

function SCIPprintSysError(message)
    ccall((:SCIPprintSysError, libscip), Cvoid, (Cstring,), message)
end

function SCIPstrtok(s, delim, ptrptr)
    ccall((:SCIPstrtok, libscip), Cstring, (Cstring, Cstring, Ptr{Cstring}), s, delim, ptrptr)
end

function SCIPescapeString(t, bufsize, s)
    ccall((:SCIPescapeString, libscip), Cvoid, (Cstring, Cint, Cstring), t, bufsize, s)
end

function SCIPstrncpy(t, s, size)
    ccall((:SCIPstrncpy, libscip), Cint, (Cstring, Cstring, Cint), t, s, size)
end

function SCIPstrToIntValue(str, value, endptr)
    ccall((:SCIPstrToIntValue, libscip), UInt32, (Cstring, Ptr{Cint}, Ptr{Cstring}), str, value, endptr)
end

function SCIPstrToRealValue(str, value, endptr)
    ccall((:SCIPstrToRealValue, libscip), UInt32, (Cstring, Ptr{Cdouble}, Ptr{Cstring}), str, value, endptr)
end

function SCIPstrCopySection(str, startchar, endchar, token, size, endptr)
    ccall((:SCIPstrCopySection, libscip), Cvoid, (Cstring, UInt8, UInt8, Cstring, Cint, Ptr{Cstring}), str, startchar, endchar, token, size, endptr)
end

function SCIPfileExists(filename)
    ccall((:SCIPfileExists, libscip), UInt32, (Cstring,), filename)
end

function SCIPsplitFilename(filename, path, name, extension, compression)
    ccall((:SCIPsplitFilename, libscip), Cvoid, (Cstring, Ptr{Cstring}, Ptr{Cstring}, Ptr{Cstring}, Ptr{Cstring}), filename, path, name, extension, compression)
end