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

using Markdown
using InteractiveUtils

# ╔═╡ 0d8949bb-f1b5-4c29-91d9-47276619bff3
begin
    import Pkg
    Pkg.activate(mktempdir())
    Pkg.add([
        Pkg.PackageSpec(name="Plots", version="1"),
        Pkg.PackageSpec(name="PlutoUI", version="0.7"),
	    Pkg.PackageSpec(name="DifferentialEquations", version="6"),
	    Pkg.PackageSpec(name="Parameters", version="0.12"),
        Pkg.PackageSpec(name="LabelledArrays", version="1"),
        Pkg.PackageSpec(name="Setfield", version="0.7"),
    ])
    using Plots, PlutoUI, LinearAlgebra, DifferentialEquations, Parameters, LabelledArrays, Setfield

	Plots.gr(fmt=:png, lw=2)

	PlutoUI.TableOfContents()
end

# ╔═╡ 514362bc-8708-4256-a592-37592fd7e2d6
md"""
# Figure 4.7, 4.8, 4.9, and 4.19A

Symmetric (bistable) biological networks.
"""

# ╔═╡ cc86896a-1624-438a-8e81-cbd284f0c144
p1 = (K1=20.0, K2=20.0, K3=5.0, K4=5.0, N1=1.0, N2=4.0)

# ╔═╡ 841e6858-46b3-43ea-abdc-79fc1fb8cf1b
u0s = (LVector(s1=3.0, s2=1.0), LVector(s1=1.0, s2=3.0))

# ╔═╡ ef41caa5-af55-4b26-83c9-115d37145c48
# Symmetric inhibition
p2 = (K1=20.0, K2=20.0, K3=5.0, K4=5.0, N1=4.0, N2=4.0)

# ╔═╡ 5b65d460-bde6-11eb-204f-9755e44085cf
md"""
## Appendix
Running environment and some auxillary functions.

**You can use [this helper tool](https://fonsp.com/article-test-3/pkghelper.html) to generate these commands!**
"""

# ╔═╡ 5016f59c-0a95-468a-b72c-2a6fc45b81b1
begin
	# Convenience functions
    hill(x, k) = x / (x + k)
    hill(x, k, n) = hill(x^n, k^n)
    exprel(x) = ifelse(x≈zero(x), one(x), x / expm1(x))
end

# ╔═╡ 3d9a046d-889e-4217-b22a-2c25f10fca1c
"Model of symmetric network from Figure 4.6. This code generates Figures 4.7, 4.8, 4.9, and 4.19A"
function model!(du, u, p, t)
    @unpack K1, K2, K3, K4, N1, N2 = p
    @unpack s1, s2 = u
    du.s1 = K1 * hill(1, s2, N2) - K3 * s1
    du.s2 = K2 * hill(1, s1, N1) - K4 * s2
    return du
end

# ╔═╡ 4acf70b7-dbed-4c98-93d9-9ef685e80093
function df(x, y, p = p1)
	u = LVector(s1=x, s2=y)
	du = similar(u)
	model!(du, u, p, 0.0)

	# Tweaking arrow length
	du ./ (norm(du)^0.5 * 20)
end

# ╔═╡ 920bd9af-b2af-41e5-b510-6f0e945592e8
fig47a = let
	tend = 4.0
	sols = map(u0 -> solve(ODEProblem(model!, u0, tend, p1)), u0s)

	p1 = plot(sols[1], xlabel="Time", ylabel="Concentration", legend=:right, title= "Fig 4.7A (1)")
    p2 = plot(sols[2], xlabel="Time", ylabel="Concentration", legend=:right, title= "Fig 4.7A (2)")
    fig47a = plot(p1, p2, layout=(2, 1), size=(600, 600))
end

# ╔═╡ 571a67aa-7bd5-476f-90ca-082321f6b65c
fig48a = let tend = 4.0

	sols = map(u0 -> solve(ODEProblem(model!, u0, tend, p2)), u0s)
	pl1 = plot(sols[1], xlabel="Time", ylabel="Concentration", legend=:right, title= "Fig 4.8A (1)")
    pl2 = plot(sols[2], xlabel="Time", ylabel="Concentration", legend=:right, title= "Fig 4.8A (2)")
    fig48a = plot(pl1, pl2, layout=(2, 1), size=(600, 600))
end

# ╔═╡ 83392c9a-76e9-4806-b397-0086c8aa8e10
begin
	nullclineS1(s2, p) = p.K1 / p.K3 * hill(1, s2, p.N2)
	nullclineS1(s2) = nullclineS1(s2, p1)
	nullclineS2(s1, p) = p.K2 / p.K4 * hill(1, s1, p.N1)
	nullclineS2(s1) = nullclineS2(s1, p1)
end

# ╔═╡ bc40e7ef-4286-45de-a3d6-07ddafa67c1d
fig47b = let
	r = LinRange(0.0, 5.0, 20)
	xx = [x for y in r, x in r]
	yy = [y for y in r, x in r]
	pl = quiver(xx, yy, quiver=df, line=(:lightblue))

	plot!(pl, nullclineS1, identity, 0.0, 5.0, lab="Nullcline S1", line=(:dash, :red))
	plot!(pl, identity, nullclineS2, 0.0, 5.0, lab="Nullcline S2", line=(:dash, :blue))
	plot!(pl, title="Fig 4.7 B", xlim=(0.0, 5.0), ylim=(0.0, 5.0), aspect_ratio = 1.0, size = (600, 600))

	pl
end

# ╔═╡ 53ada46f-4036-4c42-b1ec-ce7ca7ac0775
fig48b = let
	df2(x, y) = df(x, y, p2)

	r = LinRange(0.0, 5.0, 20)
	xx = [x for y in r, x in r]
	yy = [y for y in r, x in r]

	fig48b = quiver(xx, yy, quiver=df2, line=(:lightblue))

	plot!(fig48b, s2 -> nullclineS1(s2, p2) , identity, r[1], r[end], lab="Nullcline S1", line=(:dash, :red))
	plot!(fig48b, identity, s1 -> nullclineS2(s1, p2), r[1], r[end], lab="Nullcline S2", line=(:dash, :blue))
	plot!(fig48b, title="Fig 4.8 B", xlim=(r[1], r[end]), ylim=(r[1], r[end]), aspect_ratio = :equal)

	r2 = LinRange(1.0, 1.5, 20)
	xx2 = [x for y in r2, x in r2]
	yy2 = [y for y in r2, x in r2]

	pl2 = quiver(xx2, yy2, quiver=(x, y) -> df(x,y, p2) ./ 5, line=(:lightblue))

	plot!(pl2, s2 -> nullclineS1(s2, p2), identity, r2[1], r2[end], lab="Nullcline S1", line=(:dash, :red))
	plot!(pl2, identity, s1 -> nullclineS2(s1, p2), r2[1], r2[end], lab="Nullcline S2", line=(:dash, :blue))
	plot!(pl2, title="Fig 4.8 B (close up)", xlim=(r2[1], r2[end]), ylim=(r2[1], r2[end]), aspect_ratio = :equal, xlabel="[S1]", ylabel="[S2]")

	plot(fig48b, pl2, size=(1000, 500))
end

# ╔═╡ 74e5e25d-815f-4f0d-99ab-4a78764deb94
let

	pls = map((8.0, 16.0, 20.0, 35.0)) do k1
		p = (K1=k1, K2=20.0, K3=5.0, K4=5.0, N1=4.0, N2=4.0)
		plot(s2 -> nullclineS1(s2, p), s2 -> s2, 0.0, 7.0, lab="Nullcline S1")
		plot!(s1 -> s1, s1 -> nullclineS2(s1, p), 0.0, 7.0, lab="Nullcline S2")
		plot!(title = "K1 = $k1", xlim=(0.0, 7.0), ylim=(0.0, 7.0),
		  aspect_ratio = 1.0, size = (800, 800), xlabel="[S1]", ylabel="[S2]")
	end

	plot(pls...)
end

# ╔═╡ Cell order:
# ╠═514362bc-8708-4256-a592-37592fd7e2d6
# ╠═3d9a046d-889e-4217-b22a-2c25f10fca1c
# ╠═4acf70b7-dbed-4c98-93d9-9ef685e80093
# ╠═cc86896a-1624-438a-8e81-cbd284f0c144
# ╠═841e6858-46b3-43ea-abdc-79fc1fb8cf1b
# ╠═920bd9af-b2af-41e5-b510-6f0e945592e8
# ╠═83392c9a-76e9-4806-b397-0086c8aa8e10
# ╠═bc40e7ef-4286-45de-a3d6-07ddafa67c1d
# ╠═ef41caa5-af55-4b26-83c9-115d37145c48
# ╠═571a67aa-7bd5-476f-90ca-082321f6b65c
# ╠═53ada46f-4036-4c42-b1ec-ce7ca7ac0775
# ╠═74e5e25d-815f-4f0d-99ab-4a78764deb94
# ╠═5b65d460-bde6-11eb-204f-9755e44085cf
# ╠═5016f59c-0a95-468a-b72c-2a6fc45b81b1
# ╠═0d8949bb-f1b5-4c29-91d9-47276619bff3

max_stars_repo_name: stevengogogo/pluto-notebooks

max_issues_repo_name: stevengogogo/pluto-notebooks

max_forks_repo_name: stevengogogo/pluto-notebooks


text:
using Behavior
using Niancat.Persistence
using Niancat.Instances
using Niancat.Games.NiancatGames
using Niancat.Languages
using Niancat.Scores
using SQLite

@given("a game of Niancat in the default instance") do context
    sqlitedb = SQLite.DB()

    service = NiancatService(sqlitedb)
    context[:service] = service

    context[:db] = service.persistence

    gi = service.instances

    dictionary = SwedishDictionary([
        "DATORSPEL",
        "LEDARPOST",
        "ORDPUSSEL",
        "PUSSGURKA",
    ])
    context[:dictionary] = dictionary
    registergame!(service, "Niancat", (_state, gameservice) -> NiancatGame(dictionary, gameservice))

    loadgameinstances!(service)

    niancat = getgame(gi, "Niancat", "defaultinstance")
    context[:game] = niancat

end

@given("a user {String} in the default team") do context, userid
    db = context[:db]

    user = getuser(db, userid, "defaultteam")
    context[:user] = user
end

@given("these users in the default team") do context
    db = context[:db]

    usernames = column(context.datatable)

    users = [getuser(db, username, "defaultteam")
             for username in usernames]
    context[:users] = users
end

@when("{String} solves the puzzle with word {String}") do context, username, word
    db = context[:db]
    user = getuser(db, username, "defaultteam")

    response = gamecommand(context[:game], user, Guess(word))
    context[:response] = response
end

@then("{String} has score {Int} in the scoreboard for Niancat") do context, username, points
    db = context[:db]
    user = getuser(db, username, "defaultteam")
    niancat = context[:game]

    instanceid = gameinstanceid(niancat)
    round = gameround(niancat)

    scoreboard = getscoreboard(db, instanceid, round)

    @expect userscore(scoreboard, user) == points
end

@then("{String} is not in the scoreboard") do context, username
    db = context[:db]
    user = getuser(db, username, "defaultteam")
    niancat = context[:game]

    instanceid = gameinstanceid(niancat)
    round = gameround(niancat)

    scoreboard = getscoreboard(db, instanceid, round)

    @expect hasuser(scoreboard, user) == false
end

ext: jl


text:
#######################################################################################################################
# CALCULATE MARGINAL DAMAGES FROM A CH₄ EMISSION PULSE WITH DICE.
#######################################################################################################################
# Description: This function uses the DICE model to calculate marginal climate damages that occur from a CH₄ emissions
#              pulse based on the SNEASY+CH4 climate projections.
#
# Function Arguments:
#
#       base_temp  = An array of baseline SNEASY+CH4 temperature projections (each row = climate projection using a new
#                    posterior parameter sample, each column = a new year).
#       pulse_temp = An array of SNEASY+CH4 temperature projections similar to `base_temp`, but with a pulse of CH₄
#                    emissions in a user-specified year.
#       end_year   = The final year to run DICE.
#----------------------------------------------------------------------------------------------------------------------

function dice_damages(base_temp::Array{Float64,2}, pulse_temp::Array{Float64,2}, end_year::Int)

    #Create vector of years to run DICE for (note DICE2013 has 5 year timesteps).
    dice_years = collect(2010:5:end_year)

    #Find indices in SNEASY+CH4 climate projections that correspond to DICE years (assuming SNEASY+CH4 initialized in 1765).
    sneasy2dice_indices = findall((in)(dice_years), 1765:end_year)

    #Extract climate output that corresponds to every 5th year for DICE timesteps (each row is a new model run, each column a new year).
    base_temp  = base_temp[:, sneasy2dice_indices]
    pulse_temp = pulse_temp[:, sneasy2dice_indices]

    #Caluclate number of times to run DICE (equal to number of posterior parameter samples used in climate projections).
    number_samples = size(base_temp, 1)

    # Create a vector of annual years for DICE time horizon (with DICE initializing in 2010).
    annual_years = collect(2010:end_year)

    #Get a base and CH₄ emissions pulse version of DICE model.
    dice_base  = create_iam_dice(end_year=end_year)
    dice_pulse = create_iam_dice(end_year=end_year)

    # Pre-allocate arrays to store relevant DICE output.
    damages_base  = zeros(length(dice_years))
    damages_pulse = zeros(length(dice_years))
    annual_marginal_damages = zeros(number_samples, length(annual_years))
    pc_consumption_base = zeros(number_samples, length(annual_years))

    # Caluclate marginal damages and per capita consumption values for each posterior parameter climate projection.
    for i in 1:number_samples

        # Wrap code in a try/catch statement in case extreme climate values cause a model error.
        try

            # FUND cannot accept negative temperature values (which may occur in a few early periods due to superimposed noise). In both IAMs, set negative anomolies to 1e-15 to maintain consistency.
            if minimum(base_temp[i, :]) < 0.0
                base_temp[i, findall(x -> x <= 0.0, base_temp[i,:])] .= 1e-15
                pulse_temp[i, findall(x -> x <= 0.0, pulse_temp[i,:])] .= 1e-15
            end

            # Assign SNEASY+CH4 temperature projections to DICE climate damage module.
            update_param!(dice_base,  :TATM, base_temp[i, :])
            update_param!(dice_pulse, :TATM, pulse_temp[i, :])

            #Run the two versions of DICE.
            run(dice_base)
            run(dice_pulse)

            #Calculate damages and convert from $trillions to dollars.
            damages_base[:]  = dice_base[:damages, :DAMAGES] .* 1e12
            damages_pulse[:] = dice_pulse[:damages, :DAMAGES] .* 1e12

            # Calculate marginal damages and interpolate to annual values.
            annual_marginal_damages[i,:] = dice_interpolate((damages_pulse .- damages_base), 5)

            # Convert baseline per capita consumption levels to annual values.
            pc_consumption_base[i,:] = dice_interpolate(dice_base[:neteconomy, :CPC], 5)

        # If climate projections cause a model error, set DICE output to -99999.99.
        catch
            annual_marginal_damages[i,:] .= -99999.99
            pc_consumption_base[i,:] .= -99999.99
        end
    end

    # Check if any samples caused a model error.
    error_indices = findall(x-> x <= -99999.99 || x > 1_000_000, annual_marginal_damages[:,end])
    good_indices  = findall(!in(error_indices), collect(1:number_samples))

    # Return results.
    return annual_marginal_damages[good_indices,:], pc_consumption_base[good_indices,:], error_indices, good_indices
end

#######################################################################################################################
# CALCULATE THE SC-CH4 USING DICE.
#######################################################################################################################
# Description: This function uses the marginal climate damage estimates from DICE to calculate the SC-CH4.
#
# Function Arguments:
#
#       annual_marginal_damages = Anual marginal climate damages (interpolated to annual values).
#       pc_consumption          = Per capita consumption (interpolated to annual values).
#       pulse_year              = The year that the CH₄ emission pulse is added.
#       end_year                = The final year to run DICE.
#       constant                = Boolean parameter for whether or not to use a constant discount rate (true = use constant discount rate).
#       η                       = Elasticity of marginal utility of consumption.
#       ρ                       = Pure rate of time preference.
#       dollar_conversion       = Inflation conversion factor to scale dollar units to a different year.
#----------------------------------------------------------------------------------------------------------------------

function dice_scch4(annual_marginal_damages::Array{Float64,2}, pc_consumption::Array{Float64,2}, pulse_year::Int, end_year::Int; constant::Bool, η::Float64, ρ::Float64, dollar_conversion::Float64)

    #Create vector of years DICE is run (note DICE2013 has 5 year timesteps).
    dice_annual_years = collect(2010:end_year)

    # Find timestep index in annual years when CH₄ emission pulse occurs.
    pulse_index_annual = findall(x -> x == pulse_year, dice_annual_years)[1]

    # Calculate number of SC-CH4 values to calculate.
    number_samples = size(annual_marginal_damages, 1)

    #Pre-allocate arrays to store model results.
    discounted_marginal_annual_damages = zeros(number_samples, length(dice_annual_years))
    scch4 = zeros(number_samples)

    # Allocate an array to hold either constant or Ramsey discount factors.
    df = zeros(length(dice_annual_years))

    # If using a constant discount rate, calculate constant discount factors for annual timesteps.
    if constant == true
        calculate_discount_factors!(df, ones(length(dice_annual_years)), ρ, 0.0, dice_annual_years, pulse_year, pulse_index_annual)
    end

    #-----------------------------------------------------------------------
    # Loop through each marginal damage estimate and calculate the SC-CH4.
    #-----------------------------------------------------------------------
    for i = 1:number_samples

        # If not using a constant discount rate, calculate a Ramsey discount factor for each posterior parameter sample.
        if constant == false
            calculate_discount_factors!(df, pc_consumption[i,:], ρ, η, dice_annual_years, pulse_year, pulse_index_annual)
        end

        # Calculate discounted annual marginal climate damages.
        discounted_marginal_annual_damages[i,:] = annual_marginal_damages[i,:] .* df

        # Calculate the SC-CH4 as the sum of discounted annual marginal damages (scaled by inflation conversion factor for desired year).
        scch4[i] = sum(discounted_marginal_annual_damages[i,:]) * dollar_conversion
    end

    return scch4, discounted_marginal_annual_damages
end


text:
"""
    simSize(d, n, nsim, type; twoSided, α)

Simulates size for the EPD test for special cases p = 1 or 2

# Arguments
- `d<:ContinuousUnivariateDistribution: generates data
- `n::Integer`: sample size
- `nsim::Integer`: number of monte carlo replications
- `type::AbstractString`: specifies whether the null distribution is normal or laplace
- `twoSided::Bool`: true for twosided test, false otherwise. Always twosided for laplace.
- `α::Real`: size of the test.
"""
function simSize(d::D, n::N, nsim::N, type::AbstractString; twoSided::Bool = true, α::Real = 0.05) where
    {D<:ContinuousUnivariateDistribution, N <: Integer}
    sims = zeros(nsim)
    if lowercase(type) === "normal"
        z = twoSided ? quantile(Normal(), 1-α/2) : quantile(Normal(), 1-α)
    elseif lowercase(type) === "laplace"
        z = quantile(Chisq(1), 1-α)
    else
        throw(DomainError(type, "type must be normal or laplace"))
    end
    for i in 1:nsim
        simSizeInner!(sims, rand(d, n), z, i, n, twoSided, type)
    end
    return mean(sims)
end

"""
    simSize(n, nsim, p, type; twoSided, α)

Simulates size for the EPD test for general p.

# Arguments
- `d<:ContinuousUnivariateDistribution: generates data
- `n::Integer`: sample size
- `nsim::Integer`: number of monte carlo replications
- `p::Real`: shape under the null
- `twoSided::Bool`: true for twosided test, false otherwise. Always twosided for laplace.
- `α::Real`: size of the test.
"""
function simSize(d::D, n::N, nsim::N, p::Real; twoSided::Bool = true, α::Real = 0.05, χ::Bool = false) where
    {D<:ContinuousUnivariateDistribution, N <: Integer}
    p > 0 || throw(DomainError(p, "p must be positive"))
    ((α > 0) && (α < 1)) || throw(DomainError(α, "α must be on (0,1)"))
    sims = zeros(nsim)
    if χ
        z = quantile(Chisq(1), 1-α)
    else
        z = twoSided ? quantile(Normal(), 1-α/2) : quantile(Normal(), 1-α)
    end
    for i in 1:nsim
        simSizeInner!(sims, rand(d, n), z, i, n, twoSided, p, χ)
    end
    sims[sims .!== NaN] |> mean
end

function simSizeInner!(sims::Array{<:Real, 1}, y::Array{<:Real, 1}, z::Real, i::Integer, n::Integer,
    twoSided::Bool, type::AbstractString)
    if lowercase(type) === "normal"
        y = (y .- mean(y)) ./ √(var(y))
        K₂ = mean(y.^2 .* log.(abs.(y)))
        t = √n * (K₂ - (2 - log(2) + digamma(1))/2) / √((3*π^2 - 28)/8)
        if (twoSided ? abs(t) : t) > z
            sims[i] = 1
        end
    else
        μ = median(y)
        t = epdTest(y, μ, mean(abs.(y .- μ)), 1.)
        sims[i] = t^2 >= z ? 1 : 0
    end
    nothing
end

function simSizeInner!(sims::Array{<:Real, 1}, y::Array{<:Real, 1}, z::Real, i::Integer, n::Integer,
    twoSided::Bool, p::Real, χ::Bool)
    μ, σ = try
            MLE([0, log(2.)], p, y)
        catch err
            NaN, NaN
        end
    if μ == NaN
        sims[i] = NaN
    else
        t = epdTest(y, μ, p^(1/p) * gamma(1 + 1/p) * σ, p)
        if χ
            sims[i] = t^2 > z ? 1 : 0
        else
            if (twoSided ? abs(t) : t) > z
                sims[i] = 1
            end
        end
    end
    nothing
end


text:
include("adaptive_iterative_tresholding.jl")
include("generate_random_regression_problems.jl")

N, P = (50, 20)
coefs = gencoefs(20, 6)
A, b, errors = gen_regression_problem(50, 20, coefs)

ait_fixed_scad_reg(A, b) = adaptive_iterative_tresholding(A, b; f = scad)[1]
ait_fixed_hard_reg(A, b) = adaptive_iterative_tresholding(A, b; f = hard)[1]
ait_fixed_scad_reg(rand(10, 2), rand(10)) # Ensure compiled
ait_fixed_hard_reg(rand(10, 2), rand(10)) # Ensure compiled

ait_scad_bestk_reg(A, b) = begin
  res = ait_best_k(A, b; f = scad)
  for k in sort(collect(keys(res[3])))
    println(k, " => ", res[3][k])
  end
  res[1]
end
ait_scad_bestk_reg(rand(100, 10), rand(100)) # Ensure compiled

df = compare_regressors({
#  "AIT/scad fixed k=sqrt(P)" => ait_fixed_scad_reg,
  "AIT/scad best k" => ait_scad_bestk_reg,
#  "AIT/hard fixed k=sqrt(P)" => ait_fixed_hard_reg,
})


text:
using TerraDG
using Test
using LinearAlgebra

@testset "All tests" begin

@testset "Quadrature on the reference element" begin
    n = 5
    basis = TerraDG.Basis(n,1)
    p = basis.quadpoints
    wp = basis.quadweights
    func = (x,y) -> x*y*y
    sum = 0.0
    for i in CartesianIndices((n,n))
        sum += func(p[i[1]],p[i[2]]) * wp[i[1]]*wp[i[2]]
    end
    @test abs(sum - 1. / 6.) <= 10e-15
end

@testset "Maps reference coordinate to correct physical coord" begin
    cellcenter = [1.0, 1.0]
    cellsize = [0.5, 0.5]
    cell = TerraDG.Cell(cellcenter,
            cellsize,
            [],
            [],
            -1)

    @test TerraDG.globalposition(cell, [0.5, 0.5]) == cellcenter
    @test TerraDG.globalposition(cell, [0.0, 0.0]) == [0.75, 0.75]
    @test TerraDG.globalposition(cell, [1.0, 1.0]) == [1.25, 1.25]
    @test_throws BoundsError TerraDG.globalposition(cell, [1.1, 0.0])
    @test_throws BoundsError TerraDG.globalposition(cell, [-0.1, 0.0])
end

@testset "Global to reference to global is same" begin
    cellcenter = [1.0, 1.0]
    cellsize = [0.5, 0.5]
    cell = TerraDG.Cell(cellcenter,
            cellsize,
            [],
            [],
            -1)

    coords = [
        [0.5, 0.5],
        [0.0, 0.0],
        [1.0, 1.0]
    ]
    for coord ∈ coords
        global_coord = TerraDG.globalposition(cell, coord)
        local_coord = TerraDG.localposition(cell, global_coord)
        @test local_coord == coord
    end
end

@testset "Volume of 2D cells is correct" begin
    sizes = [
        [1.0, 1.0],
        [2.0, 2.0],
        [0.5, 0.5]
    ]

    volumes = [
        1.0,
        4.0,
        0.25
    ]
    for (size, volume) ∈ zip(sizes, volumes)
        cell = TerraDG.Cell([0.0, 0.0],
            size,
            [],
            [],
            -1)
        @test TerraDG.volume(cell) == volume
    end
end

@testset "Area of 2D cells is correct" begin
    sizes = [
        [1.0, 1.0],
        [2.0, 2.0],
        [0.5, 0.5]
    ]

    areas = [
        1.0,
        2.0,
        0.5
    ]
    for (size, area) ∈ zip(sizes, areas)
        cell = TerraDG.Cell([0.0, 0.0],
            size,
            [],
            [],
            -1)
        @test TerraDG.area(cell) == area
    end
end

@testset "Lagrange polynomials are correct" begin
    δ(a,b) = if (a == b) 1.0 else 0.0 end
    for n in range(1, length=6)
        basis = TerraDG.Basis(n, 1)
        points = basis.quadpoints
        for (i,p) in enumerate(points)
            for (j,q) in enumerate(points)
                @test TerraDG.lagrange_1d(points, i, q) == δ(i,j)
            end
        end
    end
end

@testset "Lagrange polynomials sum to one" begin
    for n in range(1, length=6)
        for x in [0.0, 0.5, 1.0]
            basis = TerraDG.Basis(n, 1)
            points = basis.quadpoints
            sum = 0.0
            for (i,p) in enumerate(points)
                sum += TerraDG.lagrange_1d(points, i, x)
            end
            @test isapprox(sum, 1, atol=10^-14)
        end
    end
end

@testset "Integral of derivatives of 1D-Lagrange polynomials is correct" begin
    Δx = 1e-4
    for n in range(1, length=6)
        basis = TerraDG.Basis(n, 1)
        points = basis.quadpoints
        for (i,p) in enumerate(points)
            for (j, x) in enumerate(points)
                f_1 = TerraDG.lagrange_1d(points, i, x)
                f_2 = TerraDG.lagrange_1d(points, i, x + Δx)
                df = TerraDG.lagrange_diff(points, i, x)
                @test isapprox(f_2, f_1 + Δx*df, atol=10^-5)
            end
        end
    end
end

@testset "Integral of derivatives of 2D-Lagrange polynomials is also correct" begin
    Δx = 1e-4
    Δy = 1e-4
    for x in [0.0, 0.5, 1.0]
        for y in [0.0, 0.5, 1.0]
            for n in range(1, length=6)
                basis = TerraDG.Basis(n, 1)
                points = basis.quadpoints
                for (i, p) in enumerate(points)
                    for (j, q) in enumerate(points)
                        f = TerraDG.lagrange_1d(points, i, x) * TerraDG.lagrange_1d(points, j, y)
                        f_1 = TerraDG.lagrange_1d(points, i, x + Δx) * TerraDG.lagrange_1d(points, j, y)
                        f_2 = TerraDG.lagrange_1d(points, i, x) * TerraDG.lagrange_1d(points, j, y + Δy)
                        df_x = TerraDG.lagrange_diff(points, i, x) * TerraDG.lagrange_1d(points, j, y)
                        df_y = TerraDG.lagrange_1d(points, i, x) * TerraDG.lagrange_diff(points, j, y)
                        @test isapprox(f_1, f + Δx*df_x, atol=10^-5) & isapprox(f_2, f + Δy*df_y, atol=10^-5)
                    end
                end
            end
        end
    end
end

@testset "Derivative of const = 0" begin
    for n=1:6
        basis = TerraDG.Basis(n, 1)
        for x in [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
            @test isapprox(
            sum([TerraDG.lagrange_diff(basis.quadpoints, i, x) for i=1:size(basis, 1)]), 0, atol=10e-14)
        end
    end
end

@testset "Mass matrix is correct for 2D" begin
    basis_order1 = TerraDG.Basis(1, 2)
    basis_order2 = TerraDG.Basis(2, 2)
    @test TerraDG.massmatrix(basis_order1, 2) == reshape([1], 1, 1)
    massmatrix_order2 = Diagonal([0.25,0.25,0.25,0.25])
    @test TerraDG.massmatrix(basis_order2, 2) == massmatrix_order2

end

# TODO: Enable for worksheet >2
#if false
@testset "Projection/evaluation works for polynomials" begin
    ns = [1,2,3,4,5,6]
    funs = [
        (x, y) -> [1],
        (x, y) -> [x + y],
        (x, y) -> [(x + y)^2],
        (x, y) -> [(x + y)^3],
        (x, y) -> [(x + y)^4],
        (x, y) -> [(x + y)^5]
    ]
    points = [
        [0.21, 0.23],
        [0.38, 0.93],
        [0.92, 0.23],
        [0.01, 0.01],
        [0.99, 0.99],
    ]
    proj_reshaped(basis, func) = reshape(
        TerraDG.project_to_reference_basis(func, basis, 1), length(basis.quadweights)^2 )

    for (n, fun) in zip(ns, funs)
        basis = TerraDG.Basis(n, 2)
        coeffs = proj_reshaped(basis, fun)
        for point in points
            evaluated = TerraDG.evaluate_basis(basis, coeffs, point)
            reference = fun(point[1], point[2])[1]
            @test isapprox(evaluated, reference, atol=10e-14)
        end
    end
end

@testset "Face projection matrix is correct" begin
    ns = [1,2,3,4,5,6]
    funs = [
        (x, y) -> [1,1,1]
        (x, y) -> [0,0,0]
        (x, y) -> [0,1,0]
    ]
    for n in ns
        basis = TerraDG.Basis(n, 2)
        for func in funs
            func_proj = TerraDG.project_to_reference_basis(func, basis, 3)
            for face in [TerraDG.top, TerraDG.bottom, TerraDG.left, TerraDG.right]
                fp = TerraDG.face_projection_matrix(basis, TerraDG.top)
                func_proj_face = fp * func_proj
                @test sum(func_proj)/length(func_proj) ≈ sum(func_proj_face)/length(func_proj_face)
            end
        end
    end
end

@testset "Derivative matrix is correct" begin
    ns = [1,2,3,2,3,4,5,6]

    funs = [
        (x, y) -> [1]
        (x, y) -> [1]
        (x, y) -> [1]
        (x, y) -> [x + y]
        (x, y) -> [(x + y)^2]
        (x, y) -> [(x + y)^3]
        (x, y) -> [(x + y)^4]
        (x, y) -> [(x + y)^5]
    ]
    funs_deriv_x = [
        (x,y) -> [0]
        (x,y) -> [0]
        (x,y) -> [0]
        (x,y) -> [1]
        (x,y) -> [2 * (x + y)]
        (x,y) -> [3 * (x + y)^2]
        (x,y) -> [4 * (x + y)^3]
        (x,y) -> [5 * (x + y)^4]
    ]
    funs_deriv_y = [
        (x,y) -> [0]
        (x,y) -> [0]
        (x,y) -> [0]
        (x,y) -> [1]
        (x,y) -> [2 * (x + y)]
        (x,y) -> [3 * (x + y)^2]
        (x,y) -> [4 * (x + y)^3]
        (x,y) -> [5 * (x + y)^4]
    ]

    for (n, fun, deriv_x, deriv_y) in zip(ns, funs, funs_deriv_x, funs_deriv_y)
        proj_reshaped(basis, func) = reshape(
            TerraDG.project_to_reference_basis(func, basis, 1), length(basis.quadweights)^2 )
        basis = TerraDG.Basis(n, 2)
        fun_evaluated = proj_reshaped(basis, fun)
        reference_derivx_evaluated = proj_reshaped(basis, deriv_x)
        reference_derivy_evaluated = proj_reshaped(basis, deriv_y)
        ∇ = TerraDG.derivativematrix(basis)
        derivx_evaluated = transpose(∇[:, 1:length(basis)]) * fun_evaluated
        derivy_evaluated = transpose(∇[:, length(basis) + 1 : end]) * fun_evaluated

        @test all(isapprox.(derivx_evaluated, reference_derivx_evaluated, atol=10e-12))
        @test all(isapprox.(derivy_evaluated, reference_derivy_evaluated, atol=10e-12))

    end
end

end


text:
module Client

include("versions.jl")

const API_SIGN = "API\0"
const HEADTYPE = UInt32    # sizeof(HEADTYPE) == 4 bytes
const MAX_LEN =  0xffffff

isascii(m, d) = all(<(0x80), Iterators.drop(m, d))

function write_one(socket, buf)

  s = reset(buf)

  len = bytesavailable(buf) - sizeof(HEADTYPE)

  @assert len ≤ MAX_LEN

  # Write length
  s += write(buf, hton(HEADTYPE(len)))

  msg = take!(buf)

  @assert isascii(msg, s)

  write(socket, msg)
end

function read_one(socket)

  len = ntoh(read(socket, HEADTYPE))

  @assert len ≤ MAX_LEN

  read(socket, len)
end

function buffer(sign)

  buf = IOBuffer(sizehint=64)

  sign && write(buf, API_SIGN)

  mark(buf)

  # Leave space for the header
  write(buf, zero(HEADTYPE))

  buf
end

end


text:
using TensorBoardLogger #import the TensorBoardLogger package
using Logging #import Logging package

logger = TBLogger("histogramlogs", tb_append) #create tensorboard logger

################log histogram example:################
#using logger interface
with_logger(logger) do
    for i in 1:100
        x0 = 0.5+i/30; s0 = 0.5/(i/20);
        edges = collect(-5:0.1:5)
        centers = collect(edges[1:end-1] .+0.05)
        histvals = [exp(-((c-x0)/s0)^2) for c = centers]
        data_tuple = (edges, histvals)
        @info "histogram/loggerinterface" autobin=rand(10).+0.1*i manualbin=data_tuple
    end
end

#using explicit function interface
for i in 1:100
    x0 = 0.5+i/30; s0 = 0.5/(i/20);
    edges = collect(-5:0.1:5)
    centers = collect(edges[1:end-1] .+0.05)
    histvals = [exp(-((c-x0)/s0)^2) for c = centers]
    data_tuple = (edges, histvals)
    log_histogram(logger, "histogram/explicitinterface/autobin", rand(10).+0.1*i, step = i) #automatic bins
    log_histogram(logger, "histogram/explicitinterface/manualbin", data_tuple, step = i) #manual bins
end


text:
using BinaryBuilder

name = "Libffi"
version = v"3.2.1"

# Collection of sources required to build libffi
sources = [
    ArchiveSource("https://sourceware.org/pub/libffi/libffi-$(version).tar.gz",
                  "d06ebb8e1d9a22d19e38d63fdb83954253f39bedc5d46232a05645685722ca37"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/libffi-*/
update_configure_scripts
autoreconf -f -i
./configure --prefix=$prefix --host=$target --disable-static --enable-shared
make -j${nproc}
make install
"""

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

# The products that we will ensure are always built
products = [
    LibraryProduct("libffi", :libffi)
]

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

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

max_stars_repo_name: blenessy/Yggdrasil

max_issues_repo_name: blenessy/Yggdrasil

max_forks_repo_name: blenessy/Yggdrasil


text:
module JDBCLoader

# https://github.com/JuliaDatabases/JDBC.jl
using JDBC # v0.5.0
using DataFrames: DataFrame

using Octo: Repo, AdapterBase, DBMS, SQLElement, Structured
using .Repo: SQLKeyword, ExecuteResult
using Octo.Backends: UnsupportedError

# db_dbname
function db_dbname(nt::NamedTuple)::String
    nt.connection.url
end

# db_connect
function db_connect(; kwargs...)
    connection = getindex(kwargs, :connection)
    url = connection.url
    opts = collect(pairs(connection))[2:end]
    if isempty(opts)
        conn = JDBC.DriverManager.getConnection(url)
    else
        props = Dict([string.(kv) for kv in opts])
        conn = JDBC.DriverManager.getConnection(url, props)
    end
    conn
end

# db_disconnect
function db_disconnect(conn)
    JDBC.close(conn)
end

function Vector{<:NamedTuple}(df::DataFrame)
    map(eachrow(df)) do x
        NamedTuple{keys(x)}(values(x))
    end
end

# query
function query(conn, sql::String)
    stmt = JDBC.createStatement(conn)
    rs = JDBC.executeQuery(stmt, sql)
    df = JDBC.load(DataFrame, rs)
    JDBC.close(rs)
    JDBC.close(stmt)
    Vector{<:NamedTuple}(df)
end

function prepared_execute(conn, prepared::String, vals::Vector)
    ppstmt = JDBC.prepareStatement(conn, prepared)
    for (idx, val) in enumerate(vals)
        if val isa Int
            typ = :Int
        elseif val isa Float32
            typ = :Float
        elseif val isa Float64
            typ = :Double
        else
            typ = Symbol(typeof(val))
        end
        name = Symbol(:set, typ)
        if isdefined(JDBC, name)
            setter = getfield(JDBC, name)
            setter(ppstmt, idx, val)
        else
            throw(UnsupportedError(string(name, " is not defined in JDBC")))
        end
    end
    n = JDBC.executeUpdate(ppstmt)
    JDBC.close(ppstmt)
    n
end

function query(conn, prepared::String, vals::Vector)
    rs = prepared_execute(conn, prepared, vals)
    df = JDBC.load(DataFrame, rs)
    JDBC.close(rs)
    Vector{<:NamedTuple}(df)
end

# execute
function execute(conn, sql::String)::ExecuteResult
    stmt = JDBC.createStatement(conn)
    n = JDBC.executeUpdate(stmt, sql)
    JDBC.close(stmt)
    nothing
end

function execute(conn, prepared::String, vals::Vector)::ExecuteResult
    n = prepared_execute(conn, prepared, vals)
    nothing
end

function execute(conn, prepared::String, nts::Vector{<:NamedTuple})::ExecuteResult
    for tup in nts
        vals = collect(tup)
        n = prepared_execute(conn, prepared, vals)
    end
    nothing
end

# execute_result
function execute_result(conn, command::SQLKeyword)::NamedTuple
    NamedTuple()
end

function Base.show(io::IO, mime::MIME"text/plain", element::Union{E,Structured} where E<:SQLElement)
    dbms = DBMS.SQL()
    AdapterBase._show(io, mime, dbms, element)
end

end # module Octo.Backends.JDBCLoader


text:
module AdvancedPS

using AbstractMCMC: AbstractMCMC
using Distributions: Distributions
using Libtask: Libtask
using Random: Random
using StatsFuns: StatsFuns
using Random123: Random123

include("resampling.jl")
include("rng.jl")
include("container.jl")
include("smc.jl")
include("model.jl")

end


text:
# Exports
export analyze_plan
export plot_resources

function analyze_plan(problem::SatPlanningProblem, plan::Array{<:Opportunity, 1})

    # Evaluate any constraint violations
    feasible = true
    for i in 1:length(plan)-1
        col_start = plan[i]
        col_end   = plan[i+1]

        # Only check validity of opportunity transitions
        if (typeof(col_start) == Collect ||
            typeof(col_start) == Contact) &&
            (typeof(col_end) == Collect ||
            typeof(col_end) == Contact)
            # Set transition valid by default
            valid = true

            for constraint in problem.constraints
                # Use logical and to evaulate path feasibility on graph
                if !constraint(col_start, col_end)
                    println("Collect Failed:\n Start: $col_start\n End: $col_end\n")
                    feasible = false
                    break
                end
            end
        end
    end

    unique_requests = Request[]
    duplicate_requests = Request[]

    n_contacts = 0
    n_requests = 0
    n_dup_requests = 0

    reward = 0.0

    for opp in plan
        if typeof(opp) == Collect
            n_requests += 1
            if !(opp.location in unique_requests)
                reward += opp.reward
                push!(unique_requests, opp.location)
            else
                push!(duplicate_requests, opp.location)
                n_dup_requests += 1
            end
        elseif typeof(opp) == Contact
            n_contacts += 1
        end
    end
    n_unique_reqests = length(unique_requests)

    return feasible, reward, n_unique_reqests, n_dup_requests, n_requests, n_contacts
end

function plot_resources(states::Array{SatMDPState, 1}; width::Real=25, height::Real=12.5, hsep::Real=2.0, vsep::Real=2.0, xmax::Real=24)
    # Plot history of power

    # Initialize array
    epochs = Epoch[]
    times  = Float64[]
    power  = Float64[]
    data   = Float64[]

    # Aggregate data
    for state in states
        push!(epochs, state.time)
        push!(times, (state.time - epochs[1])/3600.0)
        push!(power, state.power)
        push!(data, state.data)
    end

    hsepstr = @sprintf "%.2f" hsep
    vsepstr = @sprintf "%.2f" vsep
    wsepstr = @sprintf "%.2f" width
    hsepstr = @sprintf "%.2f" height

    g = GroupPlot(1, 2, groupStyle = "horizontal sep = $(hsepstr)cm, vertical sep = $(vsepstr)cm")
    push!(g, Axis(Plots.Linear(times, power),
        xlabel="Elapsed Time [Hrs]",
        ylabel="Power Fraction",
        title="Satellite Power History",
        xmin=0.0,
        xmax=xmax,
        ymin=0.0,
        ymax=1.0,
        style = "width=$(wsepstr)cm,height=$(hsepstr)cm"
    ))

    push!(g, Axis(Plots.Linear(times, data),
        xlabel="Elapsed Time [Hrs]",
        ylabel="Data Storage",
        title="Satellite Data History",
        xmin=0.0,
        xmax=xmax,
        ymin=0.0,
        ymax=1.0,
        style = "width=$(wsepstr)cm,height=$(hsepstr)cm"
    ))
end


text:
module PkgBowen2

greet() = print("007 20200502 16:32 太好了，這樣太棒了 🐷 可以有自己的包裝了～ Hello World!")
println("hihi pkg bowen 2")

end # module


text:
# Julia wrapper for header: gurobi_c.h
# Automatically generated using Clang.jl

function GRBgetattrinfo(model, attrname, datatypeP, attrtypeP, settableP)
    ccall((:GRBgetattrinfo, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), model, attrname, datatypeP, attrtypeP, settableP)
end

function GRBisattravailable(model, attrname)
    ccall((:GRBisattravailable, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}), model, attrname)
end

function GRBgetintattr(model, attrname, valueP)
    ccall((:GRBgetintattr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Cint}), model, attrname, valueP)
end

function GRBsetintattr(model, attrname, newvalue)
    ccall((:GRBsetintattr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint), model, attrname, newvalue)
end

function GRBgetintattrelement(model, attrname, element, valueP)
    ccall((:GRBgetintattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}), model, attrname, element, valueP)
end

function GRBsetintattrelement(model, attrname, element, newvalue)
    ccall((:GRBsetintattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint), model, attrname, element, newvalue)
end

function GRBgetintattrarray(model, attrname, first, len, values)
    ccall((:GRBgetintattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cint}), model, attrname, first, len, values)
end

function GRBsetintattrarray(model, attrname, first, len, newvalues)
    ccall((:GRBsetintattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cint}), model, attrname, first, len, newvalues)
end

function GRBgetintattrlist(model, attrname, len, ind, values)
    ccall((:GRBgetintattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Cint}), model, attrname, len, ind, values)
end

function GRBsetintattrlist(model, attrname, len, ind, newvalues)
    ccall((:GRBsetintattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Cint}), model, attrname, len, ind, newvalues)
end

function GRBgetcharattrelement(model, attrname, element, valueP)
    ccall((:GRBgetcharattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cchar}), model, attrname, element, valueP)
end

function GRBsetcharattrelement(model, attrname, element, newvalue)
    ccall((:GRBsetcharattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, UInt8), model, attrname, element, newvalue)
end

function GRBgetcharattrarray(model, attrname, first, len, values)
    ccall((:GRBgetcharattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}), model, attrname, first, len, values)
end

function GRBsetcharattrarray(model, attrname, first, len, newvalues)
    ccall((:GRBsetcharattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}), model, attrname, first, len, newvalues)
end

function GRBgetcharattrlist(model, attrname, len, ind, values)
    ccall((:GRBgetcharattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Cchar}), model, attrname, len, ind, values)
end

function GRBsetcharattrlist(model, attrname, len, ind, newvalues)
    ccall((:GRBsetcharattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Cchar}), model, attrname, len, ind, newvalues)
end

function GRBgetdblattr(model, attrname, valueP)
    ccall((:GRBgetdblattr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Cdouble}), model, attrname, valueP)
end

function GRBsetdblattr(model, attrname, newvalue)
    ccall((:GRBsetdblattr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cdouble), model, attrname, newvalue)
end

function GRBgetdblattrelement(model, attrname, element, valueP)
    ccall((:GRBgetdblattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cdouble}), model, attrname, element, valueP)
end

function GRBsetdblattrelement(model, attrname, element, newvalue)
    ccall((:GRBsetdblattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cdouble), model, attrname, element, newvalue)
end

function GRBgetdblattrarray(model, attrname, first, len, values)
    ccall((:GRBgetdblattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cdouble}), model, attrname, first, len, values)
end

function GRBsetdblattrarray(model, attrname, first, len, newvalues)
    ccall((:GRBsetdblattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cdouble}), model, attrname, first, len, newvalues)
end

function GRBgetdblattrlist(model, attrname, len, ind, values)
    ccall((:GRBgetdblattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Cdouble}), model, attrname, len, ind, values)
end

function GRBsetdblattrlist(model, attrname, len, ind, newvalues)
    ccall((:GRBsetdblattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Cdouble}), model, attrname, len, ind, newvalues)
end

function GRBgetstrattr(model, attrname, valueP)
    ccall((:GRBgetstrattr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Ptr{Cchar}}), model, attrname, valueP)
end

function GRBsetstrattr(model, attrname, newvalue)
    ccall((:GRBsetstrattr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Cchar}), model, attrname, newvalue)
end

function GRBgetstrattrelement(model, attrname, element, valueP)
    ccall((:GRBgetstrattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Ptr{Cchar}}), model, attrname, element, valueP)
end

function GRBsetstrattrelement(model, attrname, element, newvalue)
    ccall((:GRBsetstrattrelement, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cchar}), model, attrname, element, newvalue)
end

function GRBgetstrattrarray(model, attrname, first, len, values)
    ccall((:GRBgetstrattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Ptr{Cchar}}), model, attrname, first, len, values)
end

function GRBsetstrattrarray(model, attrname, first, len, newvalues)
    ccall((:GRBsetstrattrarray, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Ptr{Cchar}}), model, attrname, first, len, newvalues)
end

function GRBgetstrattrlist(model, attrname, len, ind, values)
    ccall((:GRBgetstrattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Ptr{Cchar}}), model, attrname, len, ind, values)
end

function GRBsetstrattrlist(model, attrname, len, ind, newvalues)
    ccall((:GRBsetstrattrlist, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Ptr{Cchar}}), model, attrname, len, ind, newvalues)
end

function GRBsetcallbackfunc(model, cb, usrdata)
    ccall((:GRBsetcallbackfunc, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cvoid}, Ptr{Cvoid}), model, cb, usrdata)
end

function GRBgetcallbackfuncenv(env, cbP)
    ccall((:GRBgetcallbackfuncenv, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Ptr{Cvoid}}), env, cbP)
end

function GRBsetcallbackfuncenv(env, cb, usrdata)
    ccall((:GRBsetcallbackfuncenv, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cvoid}, Ptr{Cvoid}), env, cb, usrdata)
end

function GRBgetcallbackfunc(model, cbP)
    ccall((:GRBgetcallbackfunc, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{Cvoid}}), model, cbP)
end

function GRBsetlogcallbackfunc(model, cb, logdata)
    ccall((:GRBsetlogcallbackfunc, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cvoid}, Ptr{Cvoid}), model, cb, logdata)
end

function GRBsetlogcallbackfuncenv(env, cb, logdata)
    ccall((:GRBsetlogcallbackfuncenv, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cvoid}, Ptr{Cvoid}), env, cb, logdata)
end

function GRBgetlogcallbackfuncenv(env, cbP, logdataP)
    ccall((:GRBgetlogcallbackfuncenv, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Ptr{Cvoid}}, Ptr{Ptr{Cvoid}}), env, cbP, logdataP)
end

function GRBcbget(cbdata, where, what, resultP)
    ccall((:GRBcbget, libgurobi), Cint, (Ptr{Cvoid}, Cint, Cint, Ptr{Cvoid}), cbdata, where, what, resultP)
end

function GRBcbsetparam(cbdata, paramname, newvalue)
    ccall((:GRBcbsetparam, libgurobi), Cint, (Ptr{Cvoid}, Ptr{Cchar}, Ptr{Cchar}), cbdata, paramname, newvalue)
end

function GRBcbsolution(cbdata, solution, objvalP)
    ccall((:GRBcbsolution, libgurobi), Cint, (Ptr{Cvoid}, Ptr{Cdouble}, Ptr{Cdouble}), cbdata, solution, objvalP)
end

function GRBcbcut(cbdata, cutlen, cutind, cutval, cutsense, cutrhs)
    ccall((:GRBcbcut, libgurobi), Cint, (Ptr{Cvoid}, Cint, Ptr{Cint}, Ptr{Cdouble}, UInt8, Cdouble), cbdata, cutlen, cutind, cutval, cutsense, cutrhs)
end

function GRBcblazy(cbdata, lazylen, lazyind, lazyval, lazysense, lazyrhs)
    ccall((:GRBcblazy, libgurobi), Cint, (Ptr{Cvoid}, Cint, Ptr{Cint}, Ptr{Cdouble}, UInt8, Cdouble), cbdata, lazylen, lazyind, lazyval, lazysense, lazyrhs)
end

function GRBgetcoeff(model, constr, var, valP)
    ccall((:GRBgetcoeff, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cdouble}), model, constr, var, valP)
end

function GRBgetconstrs(model, numnzP, cbeg, cind, cval, start, len)
    ccall((:GRBgetconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Cint, Cint), model, numnzP, cbeg, cind, cval, start, len)
end

function GRBXgetconstrs(model, numnzP, cbeg, cind, cval, start, len)
    ccall((:GRBXgetconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Cint, Cint), model, numnzP, cbeg, cind, cval, start, len)
end

function GRBgetvars(model, numnzP, vbeg, vind, vval, start, len)
    ccall((:GRBgetvars, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Cint, Cint), model, numnzP, vbeg, vind, vval, start, len)
end

function GRBXgetvars(model, numnzP, vbeg, vind, vval, start, len)
    ccall((:GRBXgetvars, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Cint, Cint), model, numnzP, vbeg, vind, vval, start, len)
end

function GRBgetsos(model, nummembersP, sostype, beg, ind, weight, start, len)
    ccall((:GRBgetsos, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Cint, Cint), model, nummembersP, sostype, beg, ind, weight, start, len)
end

function GRBgetgenconstrMax(model, genconstr, resvarP, nvarsP, vars, constantP)
    ccall((:GRBgetgenconstrMax, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, genconstr, resvarP, nvarsP, vars, constantP)
end

function GRBgetgenconstrMin(model, genconstr, resvarP, nvarsP, vars, constantP)
    ccall((:GRBgetgenconstrMin, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, genconstr, resvarP, nvarsP, vars, constantP)
end

function GRBgetgenconstrAbs(model, genconstr, resvarP, argvarP)
    ccall((:GRBgetgenconstrAbs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}), model, genconstr, resvarP, argvarP)
end

function GRBgetgenconstrAnd(model, genconstr, resvarP, nvarsP, vars)
    ccall((:GRBgetgenconstrAnd, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), model, genconstr, resvarP, nvarsP, vars)
end

function GRBgetgenconstrOr(model, genconstr, resvarP, nvarsP, vars)
    ccall((:GRBgetgenconstrOr, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), model, genconstr, resvarP, nvarsP, vars)
end

function GRBgetgenconstrNorm(model, genconstr, resvarP, nvarsP, vars, whichP)
    ccall((:GRBgetgenconstrNorm, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, genconstr, resvarP, nvarsP, vars, whichP)
end

function GRBgetgenconstrIndicator(model, genconstr, binvarP, binvalP, nvarsP, vars, vals, senseP, rhsP)
    ccall((:GRBgetgenconstrIndicator, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Cdouble}), model, genconstr, binvarP, binvalP, nvarsP, vars, vals, senseP, rhsP)
end

function GRBgetgenconstrPWL(model, genconstr, xvarP, yvarP, nptsP, xpts, ypts)
    ccall((:GRBgetgenconstrPWL, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}), model, genconstr, xvarP, yvarP, nptsP, xpts, ypts)
end

function GRBgetgenconstrPoly(model, genconstr, xvarP, yvarP, plenP, p)
    ccall((:GRBgetgenconstrPoly, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, genconstr, xvarP, yvarP, plenP, p)
end

function GRBgetgenconstrExpA(model, genconstr, xvarP, yvarP, aP)
    ccall((:GRBgetgenconstrExpA, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, genconstr, xvarP, yvarP, aP)
end

function GRBgetgenconstrLogA(model, genconstr, xvarP, yvarP, aP)
    ccall((:GRBgetgenconstrLogA, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, genconstr, xvarP, yvarP, aP)
end

function GRBgetgenconstrPow(model, genconstr, xvarP, yvarP, aP)
    ccall((:GRBgetgenconstrPow, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, genconstr, xvarP, yvarP, aP)
end

function GRBgetgenconstrExp(model, genconstr, xvarP, yvarP)
    ccall((:GRBgetgenconstrExp, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}), model, genconstr, xvarP, yvarP)
end

function GRBgetgenconstrLog(model, genconstr, xvarP, yvarP)
    ccall((:GRBgetgenconstrLog, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}), model, genconstr, xvarP, yvarP)
end

function GRBgetgenconstrSin(model, genconstr, xvarP, yvarP)
    ccall((:GRBgetgenconstrSin, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}), model, genconstr, xvarP, yvarP)
end

function GRBgetgenconstrCos(model, genconstr, xvarP, yvarP)
    ccall((:GRBgetgenconstrCos, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}), model, genconstr, xvarP, yvarP)
end

function GRBgetgenconstrTan(model, genconstr, xvarP, yvarP)
    ccall((:GRBgetgenconstrTan, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}), model, genconstr, xvarP, yvarP)
end

function GRBgetq(model, numqnzP, qrow, qcol, qval)
    ccall((:GRBgetq, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, numqnzP, qrow, qcol, qval)
end

function GRBgetqconstr(model, qconstr, numlnzP, lind, lval, numqnzP, qrow, qcol, qval)
    ccall((:GRBgetqconstr, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, qconstr, numlnzP, lind, lval, numqnzP, qrow, qcol, qval)
end

function GRBgetvarbyname(model, name, indexP)
    ccall((:GRBgetvarbyname, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Cint}), model, name, indexP)
end

function GRBgetconstrbyname(model, name, indexP)
    ccall((:GRBgetconstrbyname, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Cint}), model, name, indexP)
end

function GRBgetqconstrbyname(model, name, indexP)
    ccall((:GRBgetqconstrbyname, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Cint}), model, name, indexP)
end

function GRBgetpwlobj(model, var, pointsP, x, y)
    ccall((:GRBgetpwlobj, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}), model, var, pointsP, x, y)
end

function GRBoptimize(model)
    ccall((:GRBoptimize, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBoptimizeasync(model)
    ccall((:GRBoptimizeasync, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBoptimizebatch(model, batchid)
    ccall((:GRBoptimizebatch, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}), model, batchid)
end

function GRBcopymodel(model)
    ccall((:GRBcopymodel, libgurobi), Ptr{GRBmodel}, (Ptr{GRBmodel},), model)
end

function GRBfixmodel(model, fixedP)
    ccall((:GRBfixmodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, fixedP)
end

function GRBfeasrelax(model, relaxobjtype, minrelax, lbpen, ubpen, rhspen, feasobjP)
    ccall((:GRBfeasrelax, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}), model, relaxobjtype, minrelax, lbpen, ubpen, rhspen, feasobjP)
end

function GRBsinglescenariomodel(model, singlescenarioP)
    ccall((:GRBsinglescenariomodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, singlescenarioP)
end

function GRBgetcbwhatinfo(cbdata, what, typeP, sizeP)
    ccall((:GRBgetcbwhatinfo, libgurobi), Cint, (Ptr{Cvoid}, Cint, Ptr{Cint}, Ptr{Cint}), cbdata, what, typeP, sizeP)
end

function GRBrelaxmodel(model, relaxedP)
    ccall((:GRBrelaxmodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, relaxedP)
end

function GRBconverttofixed(model)
    ccall((:GRBconverttofixed, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBpresolvemodel(model, presolvedP)
    ccall((:GRBpresolvemodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, presolvedP)
end

function GRBiismodel(model, iisP)
    ccall((:GRBiismodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, iisP)
end

function GRBfeasibility(model, feasP)
    ccall((:GRBfeasibility, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, feasP)
end

function GRBlinearizemodel(model, linearizedP)
    ccall((:GRBlinearizemodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, linearizedP)
end

function GRBresultmodel(model, type, resultP)
    ccall((:GRBresultmodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Ptr{Ptr{GRBmodel}}), model, type, resultP)
end

function GRBfixedmodel(model)
    ccall((:GRBfixedmodel, libgurobi), Ptr{GRBmodel}, (Ptr{GRBmodel},), model)
end

function GRBdualmodel(model, dualP)
    ccall((:GRBdualmodel, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{GRBmodel}}), model, dualP)
end

function GRBloadenvsyscb(envP, logfilename, malloccb, calloccb, realloccb, freecb, threadcreatecb, threadjoincb, syscbusrdata)
    ccall((:GRBloadenvsyscb, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Ptr{Cchar}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), envP, logfilename, malloccb, calloccb, realloccb, freecb, threadcreatecb, threadjoincb, syscbusrdata)
end

function GRBemptyenvadv(envP, apitype, major, minor, tech, malloccb, calloccb, realloccb, freecb, threadcreatecb, threadjoincb, syscbusrdata)
    ccall((:GRBemptyenvadv, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Cint, Cint, Cint, Cint, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), envP, apitype, major, minor, tech, malloccb, calloccb, realloccb, freecb, threadcreatecb, threadjoincb, syscbusrdata)
end

function GRBreadmodel(env, filename, modelP)
    ccall((:GRBreadmodel, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Ptr{GRBmodel}}), env, filename, modelP)
end

function GRBread(model, filename)
    ccall((:GRBread, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}), model, filename)
end

function GRBwrite(model, filename)
    ccall((:GRBwrite, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}), model, filename)
end

function GRBismodelfile(filename)
    ccall((:GRBismodelfile, libgurobi), Cint, (Ptr{Cchar},), filename)
end

function GRBisattrfile(filename)
    ccall((:GRBisattrfile, libgurobi), Cint, (Ptr{Cchar},), filename)
end

function GRBfiletype(filename)
    ccall((:GRBfiletype, libgurobi), Cint, (Ptr{Cchar},), filename)
end

function GRBisrecordfile(filename)
    ccall((:GRBisrecordfile, libgurobi), Cint, (Ptr{Cchar},), filename)
end

function GRBgetjsonsolution(model, buffP)
    ccall((:GRBgetjsonsolution, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Ptr{Cchar}}), model, buffP)
end

function GRBloadjson(env, fname, buffP)
    ccall((:GRBloadjson, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Ptr{Cchar}}), env, fname, buffP)
end

function GRBnewmodel(env, modelP, Pname, numvars, obj, lb, ub, vtype, varnames)
    ccall((:GRBnewmodel, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Ptr{GRBmodel}}, Ptr{Cchar}, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Ptr{Cchar}}), env, modelP, Pname, numvars, obj, lb, ub, vtype, varnames)
end

function GRBloadmodel(env, modelP, Pname, numvars, numconstrs, objsense, objcon, obj, sense, rhs, vbeg, vlen, vind, vval, lb, ub, vtype, varnames, constrnames)
    ccall((:GRBloadmodel, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Ptr{GRBmodel}}, Ptr{Cchar}, Cint, Cint, Cint, Cdouble, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Ptr{Cchar}}, Ptr{Ptr{Cchar}}), env, modelP, Pname, numvars, numconstrs, objsense, objcon, obj, sense, rhs, vbeg, vlen, vind, vval, lb, ub, vtype, varnames, constrnames)
end

function GRBXloadmodel(env, modelP, Pname, numvars, numconstrs, objsense, objcon, obj, sense, rhs, vbeg, vlen, vind, vval, lb, ub, vtype, varnames, constrnames)
    ccall((:GRBXloadmodel, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Ptr{GRBmodel}}, Ptr{Cchar}, Cint, Cint, Cint, Cdouble, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Ptr{Cchar}}, Ptr{Ptr{Cchar}}), env, modelP, Pname, numvars, numconstrs, objsense, objcon, obj, sense, rhs, vbeg, vlen, vind, vval, lb, ub, vtype, varnames, constrnames)
end

function GRBaddvar(model, numnz, vind, vval, obj, lb, ub, vtype, varname)
    ccall((:GRBaddvar, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cdouble}, Cdouble, Cdouble, Cdouble, UInt8, Ptr{Cchar}), model, numnz, vind, vval, obj, lb, ub, vtype, varname)
end

function GRBaddvars(model, numvars, numnz, vbeg, vind, vval, obj, lb, ub, vtype, varnames)
    ccall((:GRBaddvars, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Ptr{Cchar}}), model, numvars, numnz, vbeg, vind, vval, obj, lb, ub, vtype, varnames)
end

function GRBXaddvars(model, numvars, numnz, vbeg, vind, vval, obj, lb, ub, vtype, varnames)
    ccall((:GRBXaddvars, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Ptr{Cchar}}), model, numvars, numnz, vbeg, vind, vval, obj, lb, ub, vtype, varnames)
end

function GRBaddconstr(model, numnz, cind, cval, sense, rhs, constrname)
    ccall((:GRBaddconstr, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cdouble}, UInt8, Cdouble, Ptr{Cchar}), model, numnz, cind, cval, sense, rhs, constrname)
end

function GRBaddconstrs(model, numconstrs, numnz, cbeg, cind, cval, sense, rhs, constrnames)
    ccall((:GRBaddconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Cdouble}, Ptr{Ptr{Cchar}}), model, numconstrs, numnz, cbeg, cind, cval, sense, rhs, constrnames)
end

function GRBXaddconstrs(model, numconstrs, numnz, cbeg, cind, cval, sense, rhs, constrnames)
    ccall((:GRBXaddconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cchar}, Ptr{Cdouble}, Ptr{Ptr{Cchar}}), model, numconstrs, numnz, cbeg, cind, cval, sense, rhs, constrnames)
end

function GRBaddrangeconstr(model, numnz, cind, cval, lower, upper, constrname)
    ccall((:GRBaddrangeconstr, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cdouble}, Cdouble, Cdouble, Ptr{Cchar}), model, numnz, cind, cval, lower, upper, constrname)
end

function GRBaddrangeconstrs(model, numconstrs, numnz, cbeg, cind, cval, lower, upper, constrnames)
    ccall((:GRBaddrangeconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Ptr{Cchar}}), model, numconstrs, numnz, cbeg, cind, cval, lower, upper, constrnames)
end

function GRBXaddrangeconstrs(model, numconstrs, numnz, cbeg, cind, cval, lower, upper, constrnames)
    ccall((:GRBXaddrangeconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Ptr{Cchar}}), model, numconstrs, numnz, cbeg, cind, cval, lower, upper, constrnames)
end

function GRBaddsos(model, numsos, nummembers, types, beg, ind, weight)
    ccall((:GRBaddsos, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, numsos, nummembers, types, beg, ind, weight)
end

function GRBaddgenconstrMax(model, name, resvar, nvars, vars, constant)
    ccall((:GRBaddgenconstrMax, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cint}, Cdouble), model, name, resvar, nvars, vars, constant)
end

function GRBaddgenconstrMin(model, name, resvar, nvars, vars, constant)
    ccall((:GRBaddgenconstrMin, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cint}, Cdouble), model, name, resvar, nvars, vars, constant)
end

function GRBaddgenconstrAbs(model, name, resvar, argvar)
    ccall((:GRBaddgenconstrAbs, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint), model, name, resvar, argvar)
end

function GRBaddgenconstrAnd(model, name, resvar, nvars, vars)
    ccall((:GRBaddgenconstrAnd, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cint}), model, name, resvar, nvars, vars)
end

function GRBaddgenconstrOr(model, name, resvar, nvars, vars)
    ccall((:GRBaddgenconstrOr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cint}), model, name, resvar, nvars, vars)
end

function GRBaddgenconstrNorm(model, name, resvar, nvars, vars, which)
    ccall((:GRBaddgenconstrNorm, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cint}, Cdouble), model, name, resvar, nvars, vars, which)
end

function GRBaddgenconstrIndicator(model, name, binvar, binval, nvars, vars, vals, sense, rhs)
    ccall((:GRBaddgenconstrIndicator, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Cint, Ptr{Cint}, Ptr{Cdouble}, UInt8, Cdouble), model, name, binvar, binval, nvars, vars, vals, sense, rhs)
end

function GRBaddgenconstrPWL(model, name, xvar, yvar, npts, xpts, ypts)
    ccall((:GRBaddgenconstrPWL, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}), model, name, xvar, yvar, npts, xpts, ypts)
end

function GRBaddgenconstrPoly(model, name, xvar, yvar, plen, p, options)
    ccall((:GRBaddgenconstrPoly, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Cint, Ptr{Cdouble}, Ptr{Cchar}), model, name, xvar, yvar, plen, p, options)
end

function GRBaddgenconstrExpA(model, name, xvar, yvar, a, options)
    ccall((:GRBaddgenconstrExpA, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Cdouble, Ptr{Cchar}), model, name, xvar, yvar, a, options)
end

function GRBaddgenconstrLogA(model, name, xvar, yvar, a, options)
    ccall((:GRBaddgenconstrLogA, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Cdouble, Ptr{Cchar}), model, name, xvar, yvar, a, options)
end

function GRBaddgenconstrPow(model, name, xvar, yvar, a, options)
    ccall((:GRBaddgenconstrPow, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Cdouble, Ptr{Cchar}), model, name, xvar, yvar, a, options)
end

function GRBaddgenconstrExp(model, name, xvar, yvar, options)
    ccall((:GRBaddgenconstrExp, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}), model, name, xvar, yvar, options)
end

function GRBaddgenconstrLog(model, name, xvar, yvar, options)
    ccall((:GRBaddgenconstrLog, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}), model, name, xvar, yvar, options)
end

function GRBaddgenconstrSin(model, name, xvar, yvar, options)
    ccall((:GRBaddgenconstrSin, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}), model, name, xvar, yvar, options)
end

function GRBaddgenconstrCos(model, name, xvar, yvar, options)
    ccall((:GRBaddgenconstrCos, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}), model, name, xvar, yvar, options)
end

function GRBaddgenconstrTan(model, name, xvar, yvar, options)
    ccall((:GRBaddgenconstrTan, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}), model, name, xvar, yvar, options)
end

function GRBaddqconstr(model, numlnz, lind, lval, numqnz, qrow, qcol, qval, sense, rhs, QCname)
    ccall((:GRBaddqconstr, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cdouble}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}, UInt8, Cdouble, Ptr{Cchar}), model, numlnz, lind, lval, numqnz, qrow, qcol, qval, sense, rhs, QCname)
end

function GRBaddcone(model, nummembers, members)
    ccall((:GRBaddcone, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}), model, nummembers, members)
end

function GRBaddqpterms(model, numqnz, qrow, qcol, qval)
    ccall((:GRBaddqpterms, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, numqnz, qrow, qcol, qval)
end

function GRBdelvars(model, len, ind)
    ccall((:GRBdelvars, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}), model, len, ind)
end

function GRBdelconstrs(model, len, ind)
    ccall((:GRBdelconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}), model, len, ind)
end

function GRBdelsos(model, len, ind)
    ccall((:GRBdelsos, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}), model, len, ind)
end

function GRBdelgenconstrs(model, len, ind)
    ccall((:GRBdelgenconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}), model, len, ind)
end

function GRBdelqconstrs(model, len, ind)
    ccall((:GRBdelqconstrs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}), model, len, ind)
end

function GRBdelq(model)
    ccall((:GRBdelq, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBchgcoeffs(model, cnt, cind, vind, val)
    ccall((:GRBchgcoeffs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, cnt, cind, vind, val)
end

function GRBXchgcoeffs(model, cnt, cind, vind, val)
    ccall((:GRBXchgcoeffs, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, cnt, cind, vind, val)
end

function GRBsetpwlobj(model, var, points, x, y)
    ccall((:GRBsetpwlobj, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}), model, var, points, x, y)
end

function GRBupdatemodel(model)
    ccall((:GRBupdatemodel, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBreset(model, clearall)
    ccall((:GRBreset, libgurobi), Cint, (Ptr{GRBmodel}, Cint), model, clearall)
end

function GRBresetmodel(model)
    ccall((:GRBresetmodel, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBfreemodel(model)
    ccall((:GRBfreemodel, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBcomputeIIS(model)
    ccall((:GRBcomputeIIS, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBFSolve(model, b, x)
    ccall((:GRBFSolve, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{GRBsvec}, Ptr{GRBsvec}), model, b, x)
end

function GRBBinvColj(model, j, x)
    ccall((:GRBBinvColj, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{GRBsvec}), model, j, x)
end

function GRBBinvj(model, j, x)
    ccall((:GRBBinvj, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{GRBsvec}), model, j, x)
end

function GRBBSolve(model, b, x)
    ccall((:GRBBSolve, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{GRBsvec}, Ptr{GRBsvec}), model, b, x)
end

function GRBBinvi(model, i, x)
    ccall((:GRBBinvi, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{GRBsvec}), model, i, x)
end

function GRBBinvRowi(model, i, x)
    ccall((:GRBBinvRowi, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{GRBsvec}), model, i, x)
end

function GRBgetBasisHead(model, bhead)
    ccall((:GRBgetBasisHead, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cint}), model, bhead)
end

function GRBcbstoponemultiobj(model, cbdata, objnum)
    ccall((:GRBcbstoponemultiobj, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cvoid}, Cint), model, cbdata, objnum)
end

function GRBstrongbranch(model, num, cand, downobjbd, upobjbd, statusP)
    ccall((:GRBstrongbranch, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}), model, num, cand, downobjbd, upobjbd, statusP)
end

function GRBcheckmodel(model)
    ccall((:GRBcheckmodel, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBsetsignal(model)
    ccall((:GRBsetsignal, libgurobi), Cvoid, (Ptr{GRBmodel},), model)
end

function GRBterminate(model)
    ccall((:GRBterminate, libgurobi), Cvoid, (Ptr{GRBmodel},), model)
end

function GRBcbproceed(model)
    ccall((:GRBcbproceed, libgurobi), Cvoid, (Ptr{GRBmodel},), model)
end

function GRBreplay(filename)
    ccall((:GRBreplay, libgurobi), Cint, (Ptr{Cchar},), filename)
end

function GRBsetobjective(model, sense, constant, lnz, lind, lval, qnz, qrow, qcol, qval)
    ccall((:GRBsetobjective, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cdouble, Cint, Ptr{Cint}, Ptr{Cdouble}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), model, sense, constant, lnz, lind, lval, qnz, qrow, qcol, qval)
end

function GRBsetobjectiven(model, index, priority, weight, abstol, reltol, name, constant, lnz, lind, lval)
    ccall((:GRBsetobjectiven, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Cint, Cdouble, Cdouble, Cdouble, Ptr{Cchar}, Cdouble, Cint, Ptr{Cint}, Ptr{Cdouble}), model, index, priority, weight, abstol, reltol, name, constant, lnz, lind, lval)
end

function GRBclean2(lenP, ind, val)
    ccall((:GRBclean2, libgurobi), Cvoid, (Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), lenP, ind, val)
end

function GRBclean3(lenP, ind0, ind1, val)
    ccall((:GRBclean3, libgurobi), Cvoid, (Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cdouble}), lenP, ind0, ind1, val)
end

function GRBmsg(env, message)
    ccall((:GRBmsg, libgurobi), Cvoid, (Ptr{GRBenv}, Ptr{Cchar}), env, message)
end

function GRBgetlogfile(env, logfileP)
    ccall((:GRBgetlogfile, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Ptr{Cint}}), env, logfileP)
end

function GRBfixtuneparam(env, paramname)
    ccall((:GRBfixtuneparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}), env, paramname)
end

function GRBgetintparam(env, paramname, valueP)
    ccall((:GRBgetintparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cint}), env, paramname, valueP)
end

function GRBgetdblparam(env, paramname, valueP)
    ccall((:GRBgetdblparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cdouble}), env, paramname, valueP)
end

function GRBgetstrparam(env, paramname, valueP)
    ccall((:GRBgetstrparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cchar}), env, paramname, valueP)
end

function GRBgetlongstrparam(env, paramname, valueP, size, requiredlenP)
    ccall((:GRBgetlongstrparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cchar}, Cint, Ptr{Cint}), env, paramname, valueP, size, requiredlenP)
end

function GRBgetintparaminfo(env, paramname, valueP, minP, maxP, defP)
    ccall((:GRBgetintparaminfo, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), env, paramname, valueP, minP, maxP, defP)
end

function GRBgetdblparaminfo(env, paramname, valueP, minP, maxP, defP)
    ccall((:GRBgetdblparaminfo, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}), env, paramname, valueP, minP, maxP, defP)
end

function GRBgetstrparaminfo(env, paramname, valueP, defP)
    ccall((:GRBgetstrparaminfo, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}), env, paramname, valueP, defP)
end

function GRBgetparamflags(env, parname, valueP)
    ccall((:GRBgetparamflags, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{UInt32}), env, parname, valueP)
end

function GRBsetparam(env, paramname, value)
    ccall((:GRBsetparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cchar}), env, paramname, value)
end

function GRBsetintparam(env, paramname, value)
    ccall((:GRBsetintparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Cint), env, paramname, value)
end

function GRBsetdblparam(env, paramname, value)
    ccall((:GRBsetdblparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Cdouble), env, paramname, value)
end

function GRBsetstrparam(env, paramname, value)
    ccall((:GRBsetstrparam, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Cchar}), env, paramname, value)
end

function GRBgetparamtype(env, paramname)
    ccall((:GRBgetparamtype, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}), env, paramname)
end

function GRBresetparams(env)
    ccall((:GRBresetparams, libgurobi), Cint, (Ptr{GRBenv},), env)
end

function GRBcopyparams(dest, src)
    ccall((:GRBcopyparams, libgurobi), Cint, (Ptr{GRBenv}, Ptr{GRBenv}), dest, src)
end

function GRBwriteparams(env, filename)
    ccall((:GRBwriteparams, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}), env, filename)
end

function GRBreadparams(env, filename)
    ccall((:GRBreadparams, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}), env, filename)
end

function GRBgetnumparams(env)
    ccall((:GRBgetnumparams, libgurobi), Cint, (Ptr{GRBenv},), env)
end

function GRBgetparamname(env, i, paramnameP)
    ccall((:GRBgetparamname, libgurobi), Cint, (Ptr{GRBenv}, Cint, Ptr{Ptr{Cchar}}), env, i, paramnameP)
end

function GRBgetnumattributes(model)
    ccall((:GRBgetnumattributes, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBgetattrname(model, i, attrnameP)
    ccall((:GRBgetattrname, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Ptr{Cchar}}), model, i, attrnameP)
end

function GRBloadenv(envP, logfilename)
    ccall((:GRBloadenv, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Ptr{Cchar}), envP, logfilename)
end

function GRBemptyenv(envP)
    ccall((:GRBemptyenv, libgurobi), Cint, (Ptr{Ptr{GRBenv}},), envP)
end

function GRBstartenv(env)
    ccall((:GRBstartenv, libgurobi), Cint, (Ptr{GRBenv},), env)
end

function GRBloadenvadv(envP, logfilename, apitype, major, minor, tech, server, router, password, group, priority, idletimeout, accessid, secretkey, cb, usrdata, logcb, logdata)
    ccall((:GRBloadenvadv, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Ptr{Cchar}, Cint, Cint, Cint, Cint, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Cint, Cint, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), envP, logfilename, apitype, major, minor, tech, server, router, password, group, priority, idletimeout, accessid, secretkey, cb, usrdata, logcb, logdata)
end

function GRBloadclientenv(envP, logfilename, computeserver, router, password, group, CStlsinsecure, priority, timeout)
    ccall((:GRBloadclientenv, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Cint, Cint, Cdouble), envP, logfilename, computeserver, router, password, group, CStlsinsecure, priority, timeout)
end

function GRBloadclientenvadv(envP, logfilename, computeserver, router, password, group, CStlsinsecure, priority, timeout, apitype, major, minor, tech, cb, usrdata)
    ccall((:GRBloadclientenvadv, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Cint, Cint, Cdouble, Cint, Cint, Cint, Cint, Ptr{Cvoid}, Ptr{Cvoid}), envP, logfilename, computeserver, router, password, group, CStlsinsecure, priority, timeout, apitype, major, minor, tech, cb, usrdata)
end

function GRBloadcloudenv(envP, logfilename, accessID, secretKey, pool, priority)
    ccall((:GRBloadcloudenv, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Cint), envP, logfilename, accessID, secretKey, pool, priority)
end

function GRBloadcloudenvadv(envP, logfilename, accessID, secretKey, pool, priority, apitype, major, minor, tech, cb, usrdata)
    ccall((:GRBloadcloudenvadv, libgurobi), Cint, (Ptr{Ptr{GRBenv}}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Cint, Cint, Cint, Cint, Cint, Ptr{Cvoid}, Ptr{Cvoid}), envP, logfilename, accessID, secretKey, pool, priority, apitype, major, minor, tech, cb, usrdata)
end

function GRBgetenv(model)
    ccall((:GRBgetenv, libgurobi), Ptr{GRBenv}, (Ptr{GRBmodel},), model)
end

function GRBgetconcurrentenv(model, num)
    ccall((:GRBgetconcurrentenv, libgurobi), Ptr{GRBenv}, (Ptr{GRBmodel}, Cint), model, num)
end

function GRBdiscardconcurrentenvs(model)
    ccall((:GRBdiscardconcurrentenvs, libgurobi), Cvoid, (Ptr{GRBmodel},), model)
end

function GRBgetmultiobjenv(model, num)
    ccall((:GRBgetmultiobjenv, libgurobi), Ptr{GRBenv}, (Ptr{GRBmodel}, Cint), model, num)
end

function GRBdiscardmultiobjenvs(model)
    ccall((:GRBdiscardmultiobjenvs, libgurobi), Cvoid, (Ptr{GRBmodel},), model)
end

function GRBgettuneenv(env, num)
    ccall((:GRBgettuneenv, libgurobi), Ptr{GRBenv}, (Ptr{GRBenv}, Cint), env, num)
end

function GRBdiscardtuneenvs(env)
    ccall((:GRBdiscardtuneenvs, libgurobi), Cvoid, (Ptr{GRBenv},), env)
end

function GRBreleaselicense(env)
    ccall((:GRBreleaselicense, libgurobi), Cvoid, (Ptr{GRBenv},), env)
end

function GRBfreeenv(env)
    ccall((:GRBfreeenv, libgurobi), Cvoid, (Ptr{GRBenv},), env)
end

function GRBgeterrormsg(env)
    ccall((:GRBgeterrormsg, libgurobi), Ptr{Cchar}, (Ptr{GRBenv},), env)
end

function GRBgetmerrormsg(model)
    ccall((:GRBgetmerrormsg, libgurobi), Ptr{Cchar}, (Ptr{GRBmodel},), model)
end

function GRBgetcommstats(env, recvtimeP, recvbytesP, recvmsgsP, sendtimeP, sendbytesP, sendmsgsP)
    ccall((:GRBgetcommstats, libgurobi), Cvoid, (Ptr{GRBenv}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}), env, recvtimeP, recvbytesP, recvmsgsP, sendtimeP, sendbytesP, sendmsgsP)
end

function GRBversion(majorP, minorP, technicalP)
    ccall((:GRBversion, libgurobi), Cvoid, (Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), majorP, minorP, technicalP)
end

function GRBplatform()
    ccall((:GRBplatform, libgurobi), Ptr{Cchar}, ())
end

function GRBplatformext()
    ccall((:GRBplatformext, libgurobi), Ptr{Cchar}, ())
end

function GRBlisttokens()
    ccall((:GRBlisttokens, libgurobi), Cint, ())
end

function GRBprinttuneparams()
    ccall((:GRBprinttuneparams, libgurobi), Cvoid, ())
end

function GRBtunemodel(model)
    ccall((:GRBtunemodel, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBtunemodels(env, nummodels, models)
    ccall((:GRBtunemodels, libgurobi), Cint, (Ptr{GRBenv}, Cint, Ptr{Ptr{GRBmodel}}), env, nummodels, models)
end

function GRBgettuneresult(model, i)
    ccall((:GRBgettuneresult, libgurobi), Cint, (Ptr{GRBmodel}, Cint), model, i)
end

function GRBgettunelog(model, i, logP)
    ccall((:GRBgettunelog, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Ptr{Cchar}}), model, i, logP)
end

function GRBsortIDi(len, ind, val)
    ccall((:GRBsortIDi, libgurobi), Cvoid, (Cint, Ptr{Cint}, Ptr{Cdouble}), len, ind, val)
end

function GRBabortbatch(batch)
    ccall((:GRBabortbatch, libgurobi), Cint, (Ptr{GRBbatch},), batch)
end

function GRBdiscardbatch(batch)
    ccall((:GRBdiscardbatch, libgurobi), Cint, (Ptr{GRBbatch},), batch)
end

function GRBretrybatch(batch)
    ccall((:GRBretrybatch, libgurobi), Cint, (Ptr{GRBbatch},), batch)
end

function GRBfreebatch(batch)
    ccall((:GRBfreebatch, libgurobi), Cint, (Ptr{GRBbatch},), batch)
end

function GRBgetbatch(env, batchID, batchP)
    ccall((:GRBgetbatch, libgurobi), Cint, (Ptr{GRBenv}, Ptr{Cchar}, Ptr{Ptr{GRBbatch}}), env, batchID, batchP)
end

function GRBgetbatchjsonsolution(batch, jsonsolP)
    ccall((:GRBgetbatchjsonsolution, libgurobi), Cint, (Ptr{GRBbatch}, Ptr{Ptr{Cchar}}), batch, jsonsolP)
end

function GRBgetbatchintattr(batch, attrname, valueP)
    ccall((:GRBgetbatchintattr, libgurobi), Cint, (Ptr{GRBbatch}, Ptr{Cchar}, Ptr{Cint}), batch, attrname, valueP)
end

function GRBgetbatchstrattr(batch, attrname, valueP)
    ccall((:GRBgetbatchstrattr, libgurobi), Cint, (Ptr{GRBbatch}, Ptr{Cchar}, Ptr{Ptr{Cchar}}), batch, attrname, valueP)
end

function GRBgetbatchattrname(env, n, attrnameP)
    ccall((:GRBgetbatchattrname, libgurobi), Cint, (Ptr{GRBenv}, Cint, Ptr{Ptr{Cchar}}), env, n, attrnameP)
end

function GRBgetbatchattrflags(batch, attrname, flagsP)
    ccall((:GRBgetbatchattrflags, libgurobi), Cint, (Ptr{GRBbatch}, Ptr{Cchar}, Ptr{UInt32}), batch, attrname, flagsP)
end

function GRBgetbatchattrinfo(batch, attrname, datatypeP, settableP)
    ccall((:GRBgetbatchattrinfo, libgurobi), Cint, (Ptr{GRBbatch}, Ptr{Cchar}, Ptr{Cint}, Ptr{Cint}), batch, attrname, datatypeP, settableP)
end

function GRBupdatebatch(batch)
    ccall((:GRBupdatebatch, libgurobi), Cint, (Ptr{GRBbatch},), batch)
end

function GRBwritebatchjsonsolution(batch, filename)
    ccall((:GRBwritebatchjsonsolution, libgurobi), Cint, (Ptr{GRBbatch}, Ptr{Cchar}), batch, filename)
end

function GRBgetnumbatchattributes(env)
    ccall((:GRBgetnumbatchattributes, libgurobi), Cint, (Ptr{GRBenv},), env)
end

function GRBgetbatchenv(batch)
    ccall((:GRBgetbatchenv, libgurobi), Ptr{GRBenv}, (Ptr{GRBbatch},), batch)
end

function GRBfree(ptr)
    ccall((:GRBfree, libgurobi), Cvoid, (Ptr{Cvoid},), ptr)
end

function GRBsync(model)
    ccall((:GRBsync, libgurobi), Cint, (Ptr{GRBmodel},), model)
end

function GRBpingserver(server, password)
    ccall((:GRBpingserver, libgurobi), Cint, (Ptr{Cchar}, Ptr{Cchar}), server, password)
end

function GRBprefetchattr(model, attrname)
    ccall((:GRBprefetchattr, libgurobi), Cint, (Ptr{GRBmodel}, Ptr{Cchar}), model, attrname)
end


text:
import Pkg;
Pkg.add("CSV")
Pkg.add("DataFrames")
Pkg.add("JLD2")
Pkg.add("FileIO")
Pkg.add("HDF5")


text:
@testset "SymbolicValue" begin
    x = SymbolicValue(1.0)
    @test typeof(x) == SymbolicValue{Float64}
    x = SymbolicValue(1)
    @test typeof(x) == SymbolicValue{Int}
    x = SymbolicValue(true)
    @test typeof(x) == SymbolicValue{Bool}
end

@testset "SymbolicValue2" begin
    x = SymbolicValue(0.0)
    @test iszero(x)
end

@testset "SymbolicVariable" begin
    x = symbolic(:a)
    @test x.var == :a
end

@testset "SymbolicExpression1" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = symbolic(:(x + 1.6))
    println(expr)
    y = seval(expr, env, cache)
    @test y == x + 1.6
end

@testset "SymbolicExpression2" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = symbolic(:(x - 1.6))
    y = seval(expr, env, cache)
    @test y == x - 1.6
end

@testset "SymbolicExpression3" begin
    x = 5.6
    globalenv[:x] = 5.6
    expr = symbolic(:(x * 1.6))
    y = seval(expr, globalenv)
    @test y == x * 1.6
end

@testset "SymbolicExpression4" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = symbolic(:(x / 1.6))
    y = seval(expr, env, cache)
    @test y == x / 1.6
end

@testset "SymbolicExpression5" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = symbolic(:(x ^ 1.6))
    y = seval(expr, env, cache)
    @test y == x ^ 1.6
end

@testset "SymbolicExpression6" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = exp(symbolic(:(-x ^ 1.6)))
    y = seval(expr, env, cache)
    @test y == exp(-x ^ 1.6)
end

@testset "SymbolicExpression7" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = @expr log(x ^ 1.6)
    y = seval(expr, env, cache)
    @test y == log(x ^ 1.6)
end

@testset "SymbolicExpression8" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = log(symbolic(:(x ^ 1.6)))
    y = seval(expr, env, cache)
    @test y == log(x ^ 1.6)
end

@testset "SymbolicExpression9" begin
    env = SymbolicEnv()
    cache = SymbolicCache()
    x = 5.6
    env[:x] = 5.6
    expr = @expr sqrt(x^ 1.6)
    y = seval(expr, env, cache)
    @test y == sqrt(x ^ 1.6)
end


text:
export
    SyncLoopy,
    AsyncLoopy,
    CoherentLoopy

"""
    SyncLoopy(range_size = 10)

A window filter that uses a synchronous window with LoopyBP with the given range size.
"""
SyncLoopy(range_size = 10) = WindowFilter(SyncWindow(), LoopyBP(range_size))

"""
    AsyncLoopy(range_size = 10, T = Float64)

A window filter that uses an asynchronous window with LoopyBP with the given range size.
`T` represents the time type and must be the same as used in creation of the runtime.
"""
AsyncLoopy(range_size = 10, T = Float64)  = WindowFilter(AsyncWindow{T}(), LoopyBP(range_size))

"""
    CoherentLoopy(range_size = 10, T = Float64)

A window filter that uses a coherent window with LoopyBP with the given range size.
`T` represents the time type and must be the same as used in creation of the runtime.
"""
CoherentLoopy(range_size = 10, T = Float64)  = WindowFilter(CoherentWindow{T}(), LoopyBP(range_size))


text:
# Mask deletions
include(Pkg.dir("PseudoGenomes", "src","pseudogenome-deletions.jl"))
mm10path =joinpath(homedir(),"Dropbox/Data/GENOME_DATA/mm10full/mm10.fa")
outpath = joinpath( tempdir(), "mm10.castmaskdeletion.fasta")
SVs_filename = Pkg.dir( "PseudoGenomes","testdata","28strains.REL-1410-SV.sdp.SAMPLE.tab.gz")
mask_fasta_file_with_strain_SV_deletions(mm10path,outpath,SVs_filename,"CAST_EiJ")


text:
using Pkg
using Documenter

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

Pkg.activate(".")
using BioEnergeticFoodWebs

makedocs(
         modules = [BioEnergeticFoodWebs],
         sitename = "BioEnergeticFoodWebs.jl"
         )

deploydocs(
           deps = Deps.pip("pygments", "mkdocs==0.17.5", "mkdocs-material==2.9.4", "python-markdown-math"),
           repo = "github.com/PoisotLab/BioEnergeticFoodWebs.jl.git",
           devbranch = "next"
          )

max_stars_repo_name: SimmonsBI/BioEnergeticFoodWebs

max_issues_repo_name: SimmonsBI/BioEnergeticFoodWebs

max_forks_repo_name: SimmonsBI/BioEnergeticFoodWebs


text:
"""
Rata, S. et al. Two Interlinked Bistable Switches Govern Mitotic Control in
Mammalian Cells. Curr. Biol. 28, 3824-3832.e6 (2018).
https://doi.org/10.1016/j.cub.2018.09.059
"""

include("./name2idx/parameters.jl")
include("./name2idx/species.jl")
include("./set_model.jl")
include("./forwarddiff.jl")

const BP = C.InhCDK     # name(index) of bifurcation parameter

const SN = V.NUM        # num of state variables
const PN = 1            # num of parameters
const VN = SN + PN      # num of variables

function calc_fixed_point_vec(model_path::String)::Tuple{Array,Array}
    fp::Array = []
    ev::Array = []
    br::Array = []

    for i in 1:4
        global p = param_values()
        # i==1 -> Control
        if i == 2 # Wee1 inhibition
            p[C.kweeS] = 0.0
            p[C.kweeF] = 0.0
        elseif i == 3 # Gwl siRNA
            p[C.Gwtot] = 0.0
        elseif i == 4 # Wee1 inhibition & Gwl siRNA
            p[C.kweeS] = 0.0
            p[C.kweeF] = 0.0
            p[C.Gwtot] = 0.0
        end

        new_curve!(
            model_path, p, diffeq, get_derivatives, get_steady_state,
            direction=false, bifparam=BP, n_state=SN
        )
        push!(fp, readdlm(model_path * "/data/fp.dat", '\t', Float64, '\n'))
        push!(ev, readdlm(model_path * "/data/ev.dat", '\t', Float64, '\n'))
        push!(br, get_bistable_regime(ev[i], SN))
    end

    return fp, br
end

function bifurcation_diagram(model_path::String, fp::Array, br::Array)
    rc("figure", figsize=(20, 3))
    rc("font", family="Arial")
    rc("font", size=14)
    rc("axes", linewidth=1.2)
    rc("xtick.major", width=1.2)
    rc("ytick.major", width=1.2)
    rc("lines", linewidth=2)

    for (i, (fixed_point, unstable_ss)) in enumerate(zip(fp, br))
        if length(unstable_ss) > 0
            intermediate_ss = []
            for j = 2:length(unstable_ss)
                if unstable_ss[j] - unstable_ss[j - 1] != 1
                    intermediate_ss = unstable_ss[j - 1]:unstable_ss[j]
                end
            end
        end

        subplot(1, 4, i)
        if i == 1
            plot(
                fixed_point[1:unstable_ss[1] - 1,VN + 1],
                fixed_point[1:unstable_ss[1] - 1,V.Subp + 1],
                color="royalblue"
            )
            plot(
                fixed_point[unstable_ss[1]:intermediate_ss[1] - 1,VN + 1],
                fixed_point[unstable_ss[1]:intermediate_ss[1] - 1,V.Subp + 1],
                color="darkgray","--"
            )
            plot(
                fixed_point[intermediate_ss,VN + 1],
                fixed_point[intermediate_ss,V.Subp + 1],
                color="darkorange"
            )
            plot(
                fixed_point[intermediate_ss[end] + 1:unstable_ss[end],VN + 1],
                fixed_point[intermediate_ss[end] + 1:unstable_ss[end],V.Subp + 1],
                color="darkgray","--"
            )
            plot(
                fixed_point[unstable_ss[end] + 1:end,VN + 1],
                fixed_point[unstable_ss[end] + 1:end,V.Subp + 1],
                color="crimson"
            )
            xlim(0, 0.81)
            xlabel("1NMPP1 (μM)")
            ylim(-0.05, 1.05)
            yticks([0,0.5,1], [0,50,100])
            ylabel("Sub-p (%)")
            title("Control", fontsize=18)
        elseif i == 2
            plot(
                fixed_point[1:unstable_ss[1] - 1,VN + 1],
                fixed_point[1:unstable_ss[1] - 1,V.Subp + 1],
                color="royalblue"
            )
            plot(
                fixed_point[unstable_ss,VN + 1],
                fixed_point[unstable_ss,V.Subp + 1],
                color="darkgray","--"
            )
            plot(
                fixed_point[unstable_ss[end] + 1:end,VN + 1],
                fixed_point[unstable_ss[end] + 1:end,V.Subp + 1],
                color="crimson"
            )
            xlim(0, 0.81)
            xlabel("1NMPP1 (μM)")
            ylim(-0.05, 1.05)
            yticks([0,0.5,1], [0,50,100])
            title("Wee1 inhibition", fontsize=18)
        elseif i == 3
            plot(
                fixed_point[1:unstable_ss[1] - 1,VN + 1],
                fixed_point[1:unstable_ss[1] - 1,V.Subp + 1],
                color="royalblue"
            )
            plot(
                fixed_point[unstable_ss,VN + 1],
                fixed_point[unstable_ss,V.Subp + 1],
                color="darkgray","--"
            )
            plot(
                fixed_point[unstable_ss[end] + 1:end,VN + 1],
                fixed_point[unstable_ss[end] + 1:end,V.Subp + 1],
                color="crimson"
            )
            xlim(0, 0.81)
            xlabel("1NMPP1 (μM)")
            ylim(-0.05, 1.05)
            yticks([0,0.5,1], [0,50,100])
            title("Gwl siRNA", fontsize=18)
        elseif i == 4
            plot(
                fixed_point[:,VN + 1],
                fixed_point[:,V.Subp + 1],
                color="darkorange"
            )
            xlim(0, 0.81)
            xlabel("1NMPP1 (μM)")
            ylim(-0.05, 1.05)
            yticks([0,0.5,1], [0,50,100])
            title("Wee1 inhibition & Gwl siRNA", fontsize=18)
        end
    end
    savefig(model_path * "/bifurcation_diagram.pdf", bbox_inches="tight")
    close()
end