text:
using IntcodeVM;
using DelimitedFiles;
using Sockets;
using OffsetArrays;

const code = vec(readdlm(length(ARGS) >= 1 ? ARGS[1] : "input.txt", ',', Int, '\n'))
const port = length(ARGS) >= 2 ? parse(Int,  ARGS[2]) : 60000
const width = 42
const height = 20
const screen = OffsetArray(Array{Char,2}(undef,20,42), 0:(height-1), 0:(width-1))
#const tiles = OffsetArray([ ' ', '■', '□', '-', '∘' ], 0:4)
const tiles = OffsetArray([ ' ', '■', '▦', '—', '•' ], 0:4)

if length(ARGS) >= 3 && ARGS[3] == "interactive"
    code[1] = 2;
    println("Interactive mode")
    IntcodeVM.run(code, in=stdin, out=stdout)
    exit()
elseif length(ARGS) >= 3 && ARGS[3] == "synchronous"
    code[1] = 2;
    println("Synchronous mode. Use ncat to connect on port $(port).")
    vm_listener = listen(port)
    vm_socket = accept(vm_listener)
    IntcodeVM.run(code, in=vm_socket, out=vm_socket)
    close(vm_listener)
    close(vm_socket)
    exit()
end

function read_screen(s)
    values_read = []

    # This construct is not safe for part 2.
    # For readline() to return "" the socket needs to be closed or an explicit CTRL+Z
    # needs to be sent. This works in part 1 because the machine halts with only 1 coin.
    # For part 2, we need to accept inputs pixel by pixel.
    # Furthermore, the game does not repaint the entire screen for each tick. It only
    # sends the pixels that changed.

    while (value = readline(s)) != ""
        if length(value) > 0
            push!(values_read, parse(Int, value))
        end
    end

    if length(values_read) % 3 != 0
        throw(Exception("Read $(length(values_read)) values"))
    end
    return values_read
end

function parse_screen(values_read)
    for i in 1:3:length(values_read)
        x = values_read[i]
        y = values_read[i+1]
        v = values_read[i+2]
        if x == -1 && y == 0
            global score = v
        else
            screen[y,x] = tiles[v]
        end
    end

    for y in 0:(height-1)
        for x in 0:(width-1)
            print(screen[y,x])
        end
        println()
    end

    return screen
end

@async begin
    vm_listener = listen(port)
    vm_socket = accept(vm_listener)
    IntcodeVM.run(code, in=vm_socket, out=vm_socket)
    close(vm_listener)
    close(vm_socket)
end

client_socket = connect(port)
parse_screen(read_screen(client_socket))
println("Day 13 Part 1: $(count(x -> x == '▦', values(screen)))")
close(client_socket)

### Now for part 2.
score = 0

vm_listener = listen(port + 1)

@async begin
    while true
        # Is this a busy loop? My fans are kind of loud...
        vm_socket = accept(vm_listener)
        @async begin
            s = vm_socket
            code[1] = 2
            println("accepted connection on $(vm_socket)")
            IntcodeVM.run(code, in=s, out=s)
            close(s)
        end
    end
end

println("Connect on port $(port + 1) using the Java GUI app for part 2.")
println("Press any key to exit...")
readline()
exit()
close(vm_listener)


text:
# ## polar plots

#md # ![FILE_NAME.png](images/FILE_NAME.png)

## ref https://jp.mathworks.com/matlabcentral/fileexchange/35285-matlab-plot-gallery-function-polar-plot?focused=6793167&tab=example
r(θ) = 1 + cos(θ) * sin(θ)^2
plot(r, 0, 2π, proj=:polar, lims=(0,1.5))

#-

r(θ) = 1 + cos(θ) * sin(θ)^2
θ = range(0, stop=2π, length=50)
plot(θ, r.(θ), proj=:polar, lims=(0,1.5))

ext: jl


text:
##
# sample test program to produce monthly aggregate count of smileys
# used in tweets between year 2006 to 2009, based on data from infochimps.
#
# As an example, we can use the following commands to determine how happy
# twitter users have been over time by counting smileys.
#
# 1. bring up julia on all hadoop data nodes
#       julia --machinefile ${HADOOP_HOME}/conf/slaves
# 2. load this file (assuming file present in cwd)
#       julia> require("twitter_test_smileys.jl")
# 3. we would use the daily twitter summary data from infochimps
#    data source: http://www.infochimps.com/datasets/twitter-census-conversation-metrics-one-year-of-urls-hashtags-sm--2
#    ensure that the daily summary file is available at /twitter_daily_summary.tsv
#
# 4. run the test function
#    julia> do_smiley_tests("hdfs://host:port/twitter_daily_summary.tsv")
#
#    or, follow the steps below to do it step by step (or if graphics support is not available for plots)
#
# 5. let's count the smiley occurences in stages (monthly, yearly, total).
#    this would demonstrate how we can use results from earlier maps in further map-reduce operations.
#
#    first, get a monthly summary
#    julia> j_mon = dmapreduce(MRHdfsFileInput(["hdfs://host:port/twitter_daily_summary.tsv"], find_smiley), map_monthly, collect_monthly, reduce_smiley)
#
#    next, once the above is done, get a yearly summary from the monthly data
#    julia> j2 = dmap(MRMapInput([j_mon], find_monthly), map_yearly_from_monthly, collect_yearly)
#
#    last, when the obove is done, get the total counts from the yearly data
#    we also have a reduce step here to get the final result on to the master node
#    julia> j_fin = dmapreduce(MRMapInput([j2], find_yearly), map_total_from_yearly, collect_total, reduce_smiley)
#
#    if we didn't need the monthly summary, the yearly summary could have been gotten more efficiently as:
#    julia> j_fin = dmapreduce(MRHdfsFileInput(["hdfs://host:port/twitter_daily_summary.tsv"], find_smiley), map_total, collect_total, reduce_smiley)
#
# 6. get the total result out
#    julia> wait(j_fin)
#    julia> smileys = results(j_fin)[2]
#    julia> happy_smileys = [":)", ":=)", "=)", "-)", ":-)", "(:", "(=:", "(=", "(-", "(-:"]
#    julia> sad_smileys = [":(", ":=(", "=(", "-(", ":-(", "):", ")=:", ")=", ")-", ")-:"]
# 7. count the happy and not_so_happy tweets
#    julia> happy = sum(map(x->get(smileys, x, 0), happy_smileys))
#    julia> sad = sum(map(x->get(smileys, x, 0), sad_smileys))
#    julia> println("people tweet more when they are ", (happy > sad) ? "happy":"sad")
#
# 8. get the monthly result out
#    julia> smileys = results(j_mon)[2]
# 9. count the happy and not_so_happy tweets
#    julia> happy = sum(map(x->get(smileys, x, zeros(Int,12*5)), happy_smileys))
#    julia> sad = sum(map(x->get(smileys, x, zeros(Int,12*5)), sad_smileys))
#    julia> hq = map(x->(sad[x]>0)?(happy[x]/sad[x]):'?', 1:length(happy))
#    julia> println("twitter happiness quotient:")
#    julia> println(hq)
# 10. plot the results

using HDFS
using HDFS.MapReduce
using Gaston

##
# find smiley records from HDFS CSV file
find_smiley(r, next_rec_pos) = HDFS.MapReduce.find_rec(r, next_rec_pos, Vector, '\n', '\t', ("smiley", nothing, nothing, nothing))

##
# reduce smiley counts or array of counts
reduce_smiley(reduced, results...) = HDFS.MapReduce.reduce_dicts(+, reduced, results...)

##
# for finding total counts across all years
function map_total(rec)
    ((nothing == rec) || (length(rec) == 0)) && return []
    [(rec[4], int(rec[3]))]
end

collect_total(results, rec) = (length(rec) == 0) ? results : HDFS.MapReduce.collect_in_dict(+, results, rec)

##
# for finding annual counts
function map_yearly(rec)
    ((nothing == rec) || (length(rec) == 0)) && return []

    ts = rec[2]
    ts_year = int(ts[1:4])
    [(rec[4], (ts_year-2006+1), int(rec[3]))]
end

function collect_yearly(results, rec)
    (length(rec) == 0) && return results
    smiley, year_idx, cnt = rec

    local yearly::Vector{Int}
    try
        yearly = getindex(results, smiley)
    catch
        (nothing == results) && (results = Dict{String, Vector{Int}}())
        yearly = zeros(Int, 5)
        results[smiley] = yearly
    end

    yearly[year_idx] += cnt
    results
end

find_yearly(r::MapResultReader, iter_status) = HDFS.MapReduce.find_rec(r, iter_status)
map_total_from_yearly(rec) = [(rec[1], sum(rec[2]))]

##
# for finding monthly counts
function map_monthly(rec)
    ((nothing == rec) || (length(rec) == 0)) && return []

    ts = rec[2]
    ts_year = int(ts[1:4])
    ts_mon = int(ts[5:6])
    month_idx = 12*(ts_year-2006) + ts_mon  # twitter begun from 2006
    #println("rec: $(rec)")
    #println("sent smiley=$(rec[4]) month_idx=$(month_idx) cnt=$(rec[3])")

    [(rec[4], month_idx, int(rec[3]))]
end

function collect_monthly(results, rec)
    (length(rec) == 0) && return results
    smiley, month_idx, cnt = rec
    #println("got smiley=$(smiley) month_idx=$(month_idx) cnt=$(cnt)")

    local monthly::Vector{Int}
    try
        monthly = getindex(results, smiley)
    catch
        (nothing == results) && (results = Dict{String, Vector{Int}}())
        # represent 5 years worth of monthly data
        monthly = zeros(Int, 12*5)
        results[smiley] = monthly
    end

    monthly[month_idx] += cnt
    results
end

find_monthly(r::MapResultReader, iter_status) = HDFS.MapReduce.find_rec(r, iter_status)
function map_yearly_from_monthly(rec)
    b = rec[2]
    ret = Array(Tuple,0)
    for i in 1:(length(b)/12)
        slice_end = 12*i
        push!(ret, (rec[1], i, sum(b[1+slice_end-12:slice_end])))
    end
    ret
end

function do_smiley_tests(furl::String)
    println("starting dmapreduce jobs...")
    j_mon = dmapreduce(MRHdfsFileInput([furl], find_smiley), map_monthly, collect_monthly, reduce_smiley)
    j2 = dmap(MRMapInput([j_mon], find_monthly), map_yearly_from_monthly, collect_yearly)
    j_fin = dmapreduce(MRMapInput([j2], find_yearly), map_total_from_yearly, collect_total, reduce_smiley)

    println("waiting for jobs to finish...")
    loopstatus = true
    while(loopstatus)
        sleep(2)
        for j in [j_mon, j2, j_fin]
            jstatus,jstatusinfo = status(j,true)
            (j == j_fin) && ((jstatus == "error") || (jstatus == "complete")) && (loopstatus = false)
            (jstatus == "running") && println("$(j): $(jstatusinfo)% complete...")
        end
    end
    wait(j_fin)
    println("time taken (total time, wait time, run time):")
    println("\tdmapreduce daily to monthly: $(times(j_mon))")
    println("\tdmap monthly to yearly:      $(times(j2))")
    println("\tdmapreduce yearly to total:  $(times(j_fin))")
    println("")
    println("results:")
    jstatus,smileys = results(j_fin)

    if(jstatus != "complete")
        println("unsuccessful")
        println("\tdmapreduce daily to monthly: $(status(j_mon, true))")
        println("\tdmap monthly to yearly:      $(status(j2, true))")
        println("\tdmapreduce yearly to total:  $(status(j_fin, true))")
        return
    end

    ss = {}
    for (n,v) in smileys push!(ss,(n,v)) end
    sortby!(ss, x->x[2])
    println("least used smileys:")
    cnt = 1
    while((cnt <= 10) && (cnt <= length(ss))) r = ss[cnt]; println("\t$(r[1]) : $(r[2])"); cnt+=1 end

    println("most used smileys:")
    cnt = 1
    while((cnt <= 10) && (cnt <= length(ss))) r = ss[end-cnt+1]; println("\t$(r[1]) : $(r[2])"); cnt+=1 end

    happy_smileys = [":)", ":=)", "=)", "-)", ":-)", "(:", "(=:", "(=", "(-", "(-:"]
    sad_smileys = [":(", ":=(", "=(", "-(", ":-(", "):", ")=:", ")=", ")-", ")-:"]

    happy = sum(map(x->get(smileys, x, 0), happy_smileys))
    sad = sum(map(x->get(smileys, x, 0), sad_smileys))
    println("people tweet more when they are ", (happy > sad) ? "happy":"sad")

    smileys = results(j_mon)[2]
    happy = sum(map(x->get(smileys, x, zeros(Int,12*5)), happy_smileys))
    sad = sum(map(x->get(smileys, x, zeros(Int,12*5)), sad_smileys))
    hq = map(x->(sad[x]>0)?(happy[x]/sad[x]):0.0, 1:length(happy))
    hq = convert(Array{Float64,1}, hq)
    println("twitter happiness quotient:")
    println(hq[6:46])
    println("plot coming up...")
    set_terminal("x11")
    plot(hq[6:46],
           "color","blue",
           "marker","ecircle",
           "linewidth",2,
           "pointsize",1.1,
           "title","twitter happiness index",
           "xlabel","months",
           "ylabel","): | (:",
           "box","inside horizontal left top")
end


text:
const array_h = """
template<typename T, int N>
struct Array {
    T *data;
    const int dims[N];
    const int strides[N];
    const bool continuous;
public:
    __device__ int length() {
        int n = dims[0];
        for (int i = 1; i < N; i++) n *= dims[i];
        return n;
    }
    __device__ T& operator[](const int idx) { return data[idx]; }
    __device__ T& operator()(int idx0, int idx1) {
        return data[idx0*strides[0] + idx1*strides[1]];
    }
    __device__ T& operator()(int idx0, int idx1, int idx2) {
        return data[idx0*strides[0] + idx1*strides[1] + idx2*strides[2]];
    }
    __device__ T& operator()(int *subs) {
        int idx = 0;
        for (int i = 0; i < N; i++) {
            if (dims[i] > 1) idx += subs[i] * strides[i];
        }
        return data[idx];
    }
    __device__ T& operator()(int idx) {
        if (continuous) return data[idx];
        int cumdims[N];
        cumdims[0] = 1;
        for (int i = 1; i < N; i++) cumdims[i] = cumdims[i-1] * dims[i-1];

        int temp = idx;
        int o = 0;
        for (int i = N-1; i >= 1; i--) {
            int k = temp / cumdims[i];
            o += k * strides[i];
            temp -= k * cumdims[i];
        }
        o += temp * strides[0];
        return data[o];
    }
    __device__ void idx2sub(const int idx, int *subs) {
        int cumdims[N];
        cumdims[0] = 1;
        for (int i = 1; i < N; i++) cumdims[i] = cumdims[i-1] * dims[i-1];

        int temp = idx;
        for (int i = N-1; i >= 1; i--) {
            int k = temp / cumdims[i];
            subs[i] = k;
            temp -= k * cumdims[i];
        }
        subs[0] = temp;
        return;
    }
};
"""


text:
function lin_int(grid,vals)
    function func(x)
        if x<grid[1]
            print("Error")
        elseif x>grid[n]
            print("Error")
        else index=searchsortedlast(grid,x)
            return (vals[index+1]-vals[index])/(grid[index+1]-grid[index])*(x-grid[index])+vals[index]
        end
    end
    return func
end


text:
function value(obj::ParameterFunction, arg0::ParameterDriver)
    return jcall(obj, "value", jdouble, (ParameterDriver,), arg0)
end


text:
# This file solve the line vortex Bio-Savar induced velocity

function bslinev(gama,pointa,pointb,pointiv,t)
  xm = pointiv[1]
  ym = pointiv[2]
  zm = pointiv[3]
  x1 = pointa[1]
  y1 = pointa[2]
  z1 = pointa[3]
  x2 = pointb[1]
  y2 = pointb[2]
  z2 = pointb[3]
  xl = x2-x1
  yl = y2-y1
  zl = z2-z1
  xr1 = xm-x1
  yr1 = ym-y1
  zr1 = zm-z1
  xr2 = xm-x2
  yr2 = ym-y2
  zr2 = zm-z2
  lvec = [xl,yl,zl]
  r1 = [xr1,yr1,zr1]
  r2 = [xr2,yr2,zr2]
  cosα = cosvecang(r1,lvec)
  cosβ = cosvecang(r2,lvec)
  if cosα<=1e-3||cosβ<=1e-3
    return [0.0,0.0,0.0]
  else
    sinα = sqrt(abs(1-cosα^2))
    h = abs(norm(r1)*sinα)
    vvec = [yl*zr1-zl*yr1,
            xl*zr1-zl*xr1,
            xl*yr1-yl*xr1] # the vector direction of induced velocity
    if norm(vvec)<=1e-3
      return [0.0,0.0,0.0]
    else
      vvec_ = vvec/norm(vvec)
    end
    v_θ = vcore(gama,h,t,3)[1]
    vind = v_θ*(cosα-cosβ)*vvec_
    return vind
  end
end

function vcore(Γ_avg,h,t,n=3)  # the vortex core model
  # v_θ(r) = Γ*r/(2*π*(rc^(2*n)+R^(2*n))^(1/n))
  # n is a Int VARIABLE
  # r is the distance between center of vortex to the calculated point
  # rc is the radius of vortex core
  # rc = 1.12*√(4*δ*ν*t)
  # ν is the coefficient of kinematic viscosity
  # t is the wake vortex age time
  # t = ζ/Ω (ζ is the wake vortex age angle)
  # δ = 1+a1*Γ_avg/ν
  # Γ_avg is the mean value of Γ
  # Γ_avg = 1/Nmax*sum(Γ)
  # a1 is an empirical parameter
  # a1 = 0.1

  a1 = 0.1
  δ = 1+a1*abs(Γ_avg)/ν # here I could refer to Tan J's codes for correction
  rc = 0.00855*√(δ*t)
  v_θ = Γ_avg*h/(2*π*(rc^(2*n)+h^(2*n))^(1/n))
  return v_θ,rc
end

function bslinevnocore(gama,pointa,pointb,pointiv)  #Bio-Savar calculate for Bound Vortex
    xm = pointiv[1]
    ym = pointiv[2]
    zm = pointiv[3]
    x1 = pointa[1]
    y1 = pointa[2]
    z1 = pointa[3]
    x2 = pointb[1]
    y2 = pointb[2]
    z2 = pointb[3]
    xl = x2-x1
    yl = y2-y1
    zl = z2-z1
    xr1 = xm-x1
    yr1 = ym-y1
    zr1 = zm-z1
    xr2 = xm-x2
    yr2 = ym-y2
    zr2 = zm-z2
    lvec = [xl,yl,zl]
    r1 = [xr1,yr1,zr1]
    r2 = [xr2,yr2,zr2]
    cosα = cosvecang(r1,lvec)
    cosβ = cosvecang(r2,lvec)
    if abs(cosα)<=1e-3||abs(cosβ)<=1e-3
      return 0.0
    else
      sinα = sqrt(abs(1-cosα^2))
      h = abs(norm(r1)*sinα)
      vvec = [yl*zr1-zl*yr1,
              xl*zr1-zl*xr1,
              xl*yr1-yl*xr1] # the vector direction of induced velocity
      if norm(vvec)<=1e-3
        return 0.0
      else
        vvec_ = vvec/norm(vvec)
      end
      v_θ = gama/(4*π*h)
      vind = v_θ*(cosα-cosβ)*vvec_
      return vind
    end
  end

max_stars_repo_name: dingzhw/RotorTrim

max_issues_repo_name: helicopterliu/RotorTrim

max_forks_repo_name: helicopterliu/RotorTrim


text:
@reexport module BranchMDP

export BranchMDPEnv

using ReinforcementLearningBase

mutable struct BranchMDPEnv <: AbstractEnv
    transition::Array{Int,3}
    rewards::Array{Float64,3}
    current::Int
    termination_prob::Float64
    reward::Float64
    observation_space::DiscreteSpace
    action_space::DiscreteSpace

    BranchMDPEnv(ns::Int, na::Int, b::Int, termination_prob::Float64 = 0.1) =
        new(
            rand(1:ns, ns, na, b),
            randn(ns, na, b),
            1,
            termination_prob,
            0.0,
            DiscreteSpace(ns + 1),
            DiscreteSpace(na),
        )
end

RLBase.get_observation_space(env::BranchMDPEnv) = env.observation_space
RLBase.get_action_space(env::BranchMDPEnv) = env.action_space

function (env::BranchMDPEnv)(a::Int)
    if rand() < env.termination_prob
        env.reward = 0.0
        env.current = size(env.transition, 1) + 1
    else
        b = rand(1:size(env.transition, 3))
        s′ = env.transition[env.current, a, b]
        r = env.rewards[env.current, a, b]
        env.current = s′
        env.reward = r
    end
    nothing
end

RLBase.observe(env::BranchMDPEnv) =
    (
        reward = env.reward,
        terminal = env.current == size(env.transition, 1) + 1,
        state = env.current,
    )

function RLBase.reset!(env::BranchMDPEnv, s::Int = 1)
    env.current = s
    nothing
end

end


text:
# Automatically generated using Clang.jl

const GRB_VERSION_MAJOR = 9
const GRB_VERSION_MINOR = 1
const GRB_VERSION_TECHNICAL = 0
const DEFAULT_CS_PRIORITY = 0
const MAX_CS_PRIORITY = 100
const DEFAULT_CS_PORT = 61000
const DEFAULT_CS_HANGUP = 60
const GRB_ERROR_OUT_OF_MEMORY = 10001
const GRB_ERROR_NULL_ARGUMENT = 10002
const GRB_ERROR_INVALID_ARGUMENT = 10003
const GRB_ERROR_UNKNOWN_ATTRIBUTE = 10004
const GRB_ERROR_DATA_NOT_AVAILABLE = 10005
const GRB_ERROR_INDEX_OUT_OF_RANGE = 10006
const GRB_ERROR_UNKNOWN_PARAMETER = 10007
const GRB_ERROR_VALUE_OUT_OF_RANGE = 10008
const GRB_ERROR_NO_LICENSE = 10009
const GRB_ERROR_SIZE_LIMIT_EXCEEDED = 10010
const GRB_ERROR_CALLBACK = 10011
const GRB_ERROR_FILE_READ = 10012
const GRB_ERROR_FILE_WRITE = 10013
const GRB_ERROR_NUMERIC = 10014
const GRB_ERROR_IIS_NOT_INFEASIBLE = 10015
const GRB_ERROR_NOT_FOR_MIP = 10016
const GRB_ERROR_OPTIMIZATION_IN_PROGRESS = 10017
const GRB_ERROR_DUPLICATES = 10018
const GRB_ERROR_NODEFILE = 10019
const GRB_ERROR_Q_NOT_PSD = 10020
const GRB_ERROR_QCP_EQUALITY_CONSTRAINT = 10021
const GRB_ERROR_NETWORK = 10022
const GRB_ERROR_JOB_REJECTED = 10023
const GRB_ERROR_NOT_SUPPORTED = 10024
const GRB_ERROR_EXCEED_2B_NONZEROS = 10025
const GRB_ERROR_INVALID_PIECEWISE_OBJ = 10026
const GRB_ERROR_UPDATEMODE_CHANGE = 10027
const GRB_ERROR_CLOUD = 10028
const GRB_ERROR_MODEL_MODIFICATION = 10029
const GRB_ERROR_CSWORKER = 10030
const GRB_ERROR_TUNE_MODEL_TYPES = 10031
const GRB_ERROR_SECURITY = 10032
const GRB_LESS_EQUAL = '<'
const GRB_GREATER_EQUAL = '>'
const GRB_EQUAL = '='
const GRB_CONTINUOUS = 'C'
const GRB_BINARY = 'B'
const GRB_INTEGER = 'I'
const GRB_SEMICONT = 'S'
const GRB_SEMIINT = 'N'
const GRB_MINIMIZE = 1
const GRB_MAXIMIZE = -1
const GRB_SOS_TYPE1 = 1
const GRB_SOS_TYPE2 = 2
const GRB_INFINITY = 1.0e100
const GRB_UNDEFINED = 1.0e101
const GRB_MAXINT = 2000000000
const GRB_MAX_NAMELEN = 255
const GRB_MAX_STRLEN = 512
const GRB_MAX_TAGLEN = 10240
const GRB_MAX_CONCURRENT = 64

# Skipping MacroDefinition: CB_ARGS GRBmodel * model , void * cbdata , int where , void * usrdata

const GRB_INT_ATTR_NUMCONSTRS = "NumConstrs"
const GRB_INT_ATTR_NUMVARS = "NumVars"
const GRB_INT_ATTR_NUMSOS = "NumSOS"
const GRB_INT_ATTR_NUMQCONSTRS = "NumQConstrs"
const GRB_INT_ATTR_NUMGENCONSTRS = "NumGenConstrs"
const GRB_INT_ATTR_NUMNZS = "NumNZs"
const GRB_DBL_ATTR_DNUMNZS = "DNumNZs"
const GRB_INT_ATTR_NUMQNZS = "NumQNZs"
const GRB_INT_ATTR_NUMQCNZS = "NumQCNZs"
const GRB_INT_ATTR_NUMINTVARS = "NumIntVars"
const GRB_INT_ATTR_NUMBINVARS = "NumBinVars"
const GRB_INT_ATTR_NUMPWLOBJVARS = "NumPWLObjVars"
const GRB_STR_ATTR_MODELNAME = "ModelName"
const GRB_INT_ATTR_MODELSENSE = "ModelSense"
const GRB_DBL_ATTR_OBJCON = "ObjCon"
const GRB_INT_ATTR_IS_MIP = "IsMIP"
const GRB_INT_ATTR_IS_QP = "IsQP"
const GRB_INT_ATTR_IS_QCP = "IsQCP"
const GRB_INT_ATTR_IS_MULTIOBJ = "IsMultiObj"
const GRB_STR_ATTR_SERVER = "Server"
const GRB_STR_ATTR_JOBID = "JobID"
const GRB_INT_ATTR_LICENSE_EXPIRATION = "LicenseExpiration"
const GRB_INT_ATTR_NUMTAGGED = "NumTagged"
const GRB_INT_ATTR_FINGERPRINT = "Fingerprint"
const GRB_INT_ATTR_BATCHERRORCODE = "BatchErrorCode"
const GRB_STR_ATTR_BATCHERRORMESSAGE = "BatchErrorMessage"
const GRB_STR_ATTR_BATCHID = "BatchID"
const GRB_INT_ATTR_BATCHSTATUS = "BatchStatus"
const GRB_DBL_ATTR_LB = "LB"
const GRB_DBL_ATTR_UB = "UB"
const GRB_DBL_ATTR_OBJ = "Obj"
const GRB_CHAR_ATTR_VTYPE = "VType"
const GRB_DBL_ATTR_START = "Start"
const GRB_DBL_ATTR_PSTART = "PStart"
const GRB_INT_ATTR_BRANCHPRIORITY = "BranchPriority"
const GRB_STR_ATTR_VARNAME = "VarName"
const GRB_INT_ATTR_PWLOBJCVX = "PWLObjCvx"
const GRB_DBL_ATTR_VARHINTVAL = "VarHintVal"
const GRB_INT_ATTR_VARHINTPRI = "VarHintPri"
const GRB_INT_ATTR_PARTITION = "Partition"
const GRB_STR_ATTR_VTAG = "VTag"
const GRB_STR_ATTR_CTAG = "CTag"
const GRB_DBL_ATTR_RHS = "RHS"
const GRB_DBL_ATTR_DSTART = "DStart"
const GRB_CHAR_ATTR_SENSE = "Sense"
const GRB_STR_ATTR_CONSTRNAME = "ConstrName"
const GRB_INT_ATTR_LAZY = "Lazy"
const GRB_STR_ATTR_QCTAG = "QCTag"
const GRB_DBL_ATTR_QCRHS = "QCRHS"
const GRB_CHAR_ATTR_QCSENSE = "QCSense"
const GRB_STR_ATTR_QCNAME = "QCName"
const GRB_INT_ATTR_GENCONSTRTYPE = "GenConstrType"
const GRB_STR_ATTR_GENCONSTRNAME = "GenConstrName"
const GRB_INT_ATTR_FUNCPIECES = "FuncPieces"
const GRB_DBL_ATTR_FUNCPIECEERROR = "FuncPieceError"
const GRB_DBL_ATTR_FUNCPIECELENGTH = "FuncPieceLength"
const GRB_DBL_ATTR_FUNCPIECERATIO = "FuncPieceRatio"
const GRB_DBL_ATTR_MAX_COEFF = "MaxCoeff"
const GRB_DBL_ATTR_MIN_COEFF = "MinCoeff"
const GRB_DBL_ATTR_MAX_BOUND = "MaxBound"
const GRB_DBL_ATTR_MIN_BOUND = "MinBound"
const GRB_DBL_ATTR_MAX_OBJ_COEFF = "MaxObjCoeff"
const GRB_DBL_ATTR_MIN_OBJ_COEFF = "MinObjCoeff"
const GRB_DBL_ATTR_MAX_RHS = "MaxRHS"
const GRB_DBL_ATTR_MIN_RHS = "MinRHS"
const GRB_DBL_ATTR_MAX_QCCOEFF = "MaxQCCoeff"
const GRB_DBL_ATTR_MIN_QCCOEFF = "MinQCCoeff"
const GRB_DBL_ATTR_MAX_QOBJ_COEFF = "MaxQObjCoeff"
const GRB_DBL_ATTR_MIN_QOBJ_COEFF = "MinQObjCoeff"
const GRB_DBL_ATTR_MAX_QCLCOEFF = "MaxQCLCoeff"
const GRB_DBL_ATTR_MIN_QCLCOEFF = "MinQCLCoeff"
const GRB_DBL_ATTR_MAX_QCRHS = "MaxQCRHS"
const GRB_DBL_ATTR_MIN_QCRHS = "MinQCRHS"
const GRB_DBL_ATTR_RUNTIME = "Runtime"
const GRB_INT_ATTR_STATUS = "Status"
const GRB_DBL_ATTR_OBJVAL = "ObjVal"
const GRB_DBL_ATTR_OBJBOUND = "ObjBound"
const GRB_DBL_ATTR_OBJBOUNDC = "ObjBoundC"
const GRB_DBL_ATTR_POOLOBJBOUND = "PoolObjBound"
const GRB_DBL_ATTR_POOLOBJVAL = "PoolObjVal"
const GRB_DBL_ATTR_MIPGAP = "MIPGap"
const GRB_INT_ATTR_SOLCOUNT = "SolCount"
const GRB_DBL_ATTR_ITERCOUNT = "IterCount"
const GRB_INT_ATTR_BARITERCOUNT = "BarIterCount"
const GRB_DBL_ATTR_NODECOUNT = "NodeCount"
const GRB_DBL_ATTR_OPENNODECOUNT = "OpenNodeCount"
const GRB_INT_ATTR_HASDUALNORM = "HasDualNorm"
const GRB_DBL_ATTR_X = "X"
const GRB_DBL_ATTR_XN = "Xn"
const GRB_DBL_ATTR_BARX = "BarX"
const GRB_DBL_ATTR_RC = "RC"
const GRB_DBL_ATTR_VDUALNORM = "VDualNorm"
const GRB_INT_ATTR_VBASIS = "VBasis"
const GRB_DBL_ATTR_PI = "Pi"
const GRB_DBL_ATTR_QCPI = "QCPi"
const GRB_DBL_ATTR_SLACK = "Slack"
const GRB_DBL_ATTR_QCSLACK = "QCSlack"
const GRB_DBL_ATTR_CDUALNORM = "CDualNorm"
const GRB_INT_ATTR_CBASIS = "CBasis"
const GRB_DBL_ATTR_BOUND_VIO = "BoundVio"
const GRB_DBL_ATTR_BOUND_SVIO = "BoundSVio"
const GRB_INT_ATTR_BOUND_VIO_INDEX = "BoundVioIndex"
const GRB_INT_ATTR_BOUND_SVIO_INDEX = "BoundSVioIndex"
const GRB_DBL_ATTR_BOUND_VIO_SUM = "BoundVioSum"
const GRB_DBL_ATTR_BOUND_SVIO_SUM = "BoundSVioSum"
const GRB_DBL_ATTR_CONSTR_VIO = "ConstrVio"
const GRB_DBL_ATTR_CONSTR_SVIO = "ConstrSVio"
const GRB_INT_ATTR_CONSTR_VIO_INDEX = "ConstrVioIndex"
const GRB_INT_ATTR_CONSTR_SVIO_INDEX = "ConstrSVioIndex"
const GRB_DBL_ATTR_CONSTR_VIO_SUM = "ConstrVioSum"
const GRB_DBL_ATTR_CONSTR_SVIO_SUM = "ConstrSVioSum"
const GRB_DBL_ATTR_CONSTR_RESIDUAL = "ConstrResidual"
const GRB_DBL_ATTR_CONSTR_SRESIDUAL = "ConstrSResidual"
const GRB_INT_ATTR_CONSTR_RESIDUAL_INDEX = "ConstrResidualIndex"
const GRB_INT_ATTR_CONSTR_SRESIDUAL_INDEX = "ConstrSResidualIndex"
const GRB_DBL_ATTR_CONSTR_RESIDUAL_SUM = "ConstrResidualSum"
const GRB_DBL_ATTR_CONSTR_SRESIDUAL_SUM = "ConstrSResidualSum"
const GRB_DBL_ATTR_DUAL_VIO = "DualVio"
const GRB_DBL_ATTR_DUAL_SVIO = "DualSVio"
const GRB_INT_ATTR_DUAL_VIO_INDEX = "DualVioIndex"
const GRB_INT_ATTR_DUAL_SVIO_INDEX = "DualSVioIndex"
const GRB_DBL_ATTR_DUAL_VIO_SUM = "DualVioSum"
const GRB_DBL_ATTR_DUAL_SVIO_SUM = "DualSVioSum"
const GRB_DBL_ATTR_DUAL_RESIDUAL = "DualResidual"
const GRB_DBL_ATTR_DUAL_SRESIDUAL = "DualSResidual"
const GRB_INT_ATTR_DUAL_RESIDUAL_INDEX = "DualResidualIndex"
const GRB_INT_ATTR_DUAL_SRESIDUAL_INDEX = "DualSResidualIndex"
const GRB_DBL_ATTR_DUAL_RESIDUAL_SUM = "DualResidualSum"
const GRB_DBL_ATTR_DUAL_SRESIDUAL_SUM = "DualSResidualSum"
const GRB_DBL_ATTR_INT_VIO = "IntVio"
const GRB_INT_ATTR_INT_VIO_INDEX = "IntVioIndex"
const GRB_DBL_ATTR_INT_VIO_SUM = "IntVioSum"
const GRB_DBL_ATTR_COMPL_VIO = "ComplVio"
const GRB_INT_ATTR_COMPL_VIO_INDEX = "ComplVioIndex"
const GRB_DBL_ATTR_COMPL_VIO_SUM = "ComplVioSum"
const GRB_DBL_ATTR_KAPPA = "Kappa"
const GRB_DBL_ATTR_KAPPA_EXACT = "KappaExact"
const GRB_DBL_ATTR_N2KAPPA = "N2Kappa"
const GRB_DBL_ATTR_SA_OBJLOW = "SAObjLow"
const GRB_DBL_ATTR_SA_OBJUP = "SAObjUp"
const GRB_DBL_ATTR_SA_LBLOW = "SALBLow"
const GRB_DBL_ATTR_SA_LBUP = "SALBUp"
const GRB_DBL_ATTR_SA_UBLOW = "SAUBLow"
const GRB_DBL_ATTR_SA_UBUP = "SAUBUp"
const GRB_DBL_ATTR_SA_RHSLOW = "SARHSLow"
const GRB_DBL_ATTR_SA_RHSUP = "SARHSUp"
const GRB_INT_ATTR_IIS_MINIMAL = "IISMinimal"
const GRB_INT_ATTR_IIS_LB = "IISLB"
const GRB_INT_ATTR_IIS_UB = "IISUB"
const GRB_INT_ATTR_IIS_CONSTR = "IISConstr"
const GRB_INT_ATTR_IIS_SOS = "IISSOS"
const GRB_INT_ATTR_IIS_QCONSTR = "IISQConstr"
const GRB_INT_ATTR_IIS_GENCONSTR = "IISGenConstr"
const GRB_INT_ATTR_TUNE_RESULTCOUNT = "TuneResultCount"
const GRB_DBL_ATTR_FARKASDUAL = "FarkasDual"
const GRB_DBL_ATTR_FARKASPROOF = "FarkasProof"
const GRB_DBL_ATTR_UNBDRAY = "UnbdRay"
const GRB_INT_ATTR_INFEASVAR = "InfeasVar"
const GRB_INT_ATTR_UNBDVAR = "UnbdVar"
const GRB_INT_ATTR_VARPRESTAT = "VarPreStat"
const GRB_DBL_ATTR_PREFIXVAL = "PreFixVal"
const GRB_DBL_ATTR_OBJN = "ObjN"
const GRB_DBL_ATTR_OBJNVAL = "ObjNVal"
const GRB_DBL_ATTR_OBJNCON = "ObjNCon"
const GRB_DBL_ATTR_OBJNWEIGHT = "ObjNWeight"
const GRB_INT_ATTR_OBJNPRIORITY = "ObjNPriority"
const GRB_DBL_ATTR_OBJNRELTOL = "ObjNRelTol"
const GRB_DBL_ATTR_OBJNABSTOL = "ObjNAbsTol"
const GRB_STR_ATTR_OBJNNAME = "ObjNName"
const GRB_DBL_ATTR_SCENNLB = "ScenNLB"
const GRB_DBL_ATTR_SCENNUB = "ScenNUB"
const GRB_DBL_ATTR_SCENNOBJ = "ScenNObj"
const GRB_DBL_ATTR_SCENNRHS = "ScenNRHS"
const GRB_STR_ATTR_SCENNNAME = "ScenNName"
const GRB_DBL_ATTR_SCENNX = "ScenNX"
const GRB_DBL_ATTR_SCENNOBJBOUND = "ScenNObjBound"
const GRB_DBL_ATTR_SCENNOBJVAL = "ScenNObjVal"
const GRB_INT_ATTR_NUMOBJ = "NumObj"
const GRB_INT_ATTR_NUMSCENARIOS = "NumScenarios"
const GRB_INT_ATTR_NUMSTART = "NumStart"
const GRB_DBL_ATTR_Xn = "Xn"
const GRB_GENCONSTR_MAX = 0
const GRB_GENCONSTR_MIN = 1
const GRB_GENCONSTR_ABS = 2
const GRB_GENCONSTR_AND = 3
const GRB_GENCONSTR_OR = 4
const GRB_GENCONSTR_INDICATOR = 5
const GRB_GENCONSTR_PWL = 6
const GRB_GENCONSTR_POLY = 7
const GRB_GENCONSTR_EXP = 8
const GRB_GENCONSTR_EXPA = 9
const GRB_GENCONSTR_LOG = 10
const GRB_GENCONSTR_LOGA = 11
const GRB_GENCONSTR_POW = 12
const GRB_GENCONSTR_SIN = 13
const GRB_GENCONSTR_COS = 14
const GRB_GENCONSTR_TAN = 15
const GRB_CB_POLLING = 0
const GRB_CB_PRESOLVE = 1
const GRB_CB_SIMPLEX = 2
const GRB_CB_MIP = 3
const GRB_CB_MIPSOL = 4
const GRB_CB_MIPNODE = 5
const GRB_CB_MESSAGE = 6
const GRB_CB_BARRIER = 7
const GRB_CB_MULTIOBJ = 8
const GRB_CB_PRE_COLDEL = 1000
const GRB_CB_PRE_ROWDEL = 1001
const GRB_CB_PRE_SENCHG = 1002
const GRB_CB_PRE_BNDCHG = 1003
const GRB_CB_PRE_COECHG = 1004
const GRB_CB_SPX_ITRCNT = 2000
const GRB_CB_SPX_OBJVAL = 2001
const GRB_CB_SPX_PRIMINF = 2002
const GRB_CB_SPX_DUALINF = 2003
const GRB_CB_SPX_ISPERT = 2004
const GRB_CB_MIP_OBJBST = 3000
const GRB_CB_MIP_OBJBND = 3001
const GRB_CB_MIP_NODCNT = 3002
const GRB_CB_MIP_SOLCNT = 3003
const GRB_CB_MIP_CUTCNT = 3004
const GRB_CB_MIP_NODLFT = 3005
const GRB_CB_MIP_ITRCNT = 3006
const GRB_CB_MIP_OBJBNDC = 3007
const GRB_CB_MIPSOL_SOL = 4001
const GRB_CB_MIPSOL_OBJ = 4002
const GRB_CB_MIPSOL_OBJBST = 4003
const GRB_CB_MIPSOL_OBJBND = 4004
const GRB_CB_MIPSOL_NODCNT = 4005
const GRB_CB_MIPSOL_SOLCNT = 4006
const GRB_CB_MIPSOL_OBJBNDC = 4007
const GRB_CB_MIPNODE_STATUS = 5001
const GRB_CB_MIPNODE_REL = 5002
const GRB_CB_MIPNODE_OBJBST = 5003
const GRB_CB_MIPNODE_OBJBND = 5004
const GRB_CB_MIPNODE_NODCNT = 5005
const GRB_CB_MIPNODE_SOLCNT = 5006
const GRB_CB_MIPNODE_BRVAR = 5007
const GRB_CB_MIPNODE_OBJBNDC = 5008
const GRB_CB_MSG_STRING = 6001
const GRB_CB_RUNTIME = 6002
const GRB_CB_BARRIER_ITRCNT = 7001
const GRB_CB_BARRIER_PRIMOBJ = 7002
const GRB_CB_BARRIER_DUALOBJ = 7003
const GRB_CB_BARRIER_PRIMINF = 7004
const GRB_CB_BARRIER_DUALINF = 7005
const GRB_CB_BARRIER_COMPL = 7006
const GRB_CB_MULTIOBJ_OBJCNT = 8001
const GRB_CB_MULTIOBJ_SOLCNT = 8002
const GRB_CB_MULTIOBJ_SOL = 8003
const GRB_FEASRELAX_LINEAR = 0
const GRB_FEASRELAX_QUADRATIC = 1
const GRB_FEASRELAX_CARDINALITY = 2

# Skipping MacroDefinition: MALLOCCB_ARGS size_t size , void * syscbusrdata
# Skipping MacroDefinition: CALLOCCB_ARGS size_t nmemb , size_t size , void * syscbusrdata
# Skipping MacroDefinition: REALLOCCB_ARGS void * ptr , size_t size , void * syscbusrdata
# Skipping MacroDefinition: FREECB_ARGS void * ptr , void * syscbusrdata
# Skipping MacroDefinition: THREADCREATECB_ARGS void * * threadP , void ( * start_routine ) ( void * ) , void * arg , void * syscbusrdata
# Skipping MacroDefinition: THREADJOINCB_ARGS void * thread , void * syscbusrdata

const GRB_LOADED = 1
const GRB_OPTIMAL = 2
const GRB_INFEASIBLE = 3
const GRB_INF_OR_UNBD = 4
const GRB_UNBOUNDED = 5
const GRB_CUTOFF = 6
const GRB_ITERATION_LIMIT = 7
const GRB_NODE_LIMIT = 8
const GRB_TIME_LIMIT = 9
const GRB_SOLUTION_LIMIT = 10
const GRB_INTERRUPTED = 11
const GRB_NUMERIC = 12
const GRB_SUBOPTIMAL = 13
const GRB_INPROGRESS = 14
const GRB_USER_OBJ_LIMIT = 15
const GRB_BASIC = 0
const GRB_NONBASIC_LOWER = -1
const GRB_NONBASIC_UPPER = -2
const GRB_SUPERBASIC = -3
const GRB_INT_PAR_BARITERLIMIT = "BarIterLimit"
const GRB_DBL_PAR_CUTOFF = "Cutoff"
const GRB_DBL_PAR_ITERATIONLIMIT = "IterationLimit"
const GRB_DBL_PAR_NODELIMIT = "NodeLimit"
const GRB_INT_PAR_SOLUTIONLIMIT = "SolutionLimit"
const GRB_DBL_PAR_TIMELIMIT = "TimeLimit"
const GRB_DBL_PAR_BESTOBJSTOP = "BestObjStop"
const GRB_DBL_PAR_BESTBDSTOP = "BestBdStop"
const GRB_DBL_PAR_FEASIBILITYTOL = "FeasibilityTol"
const GRB_DBL_PAR_INTFEASTOL = "IntFeasTol"
const GRB_DBL_PAR_MARKOWITZTOL = "MarkowitzTol"
const GRB_DBL_PAR_MIPGAP = "MIPGap"
const GRB_DBL_PAR_MIPGAPABS = "MIPGapAbs"
const GRB_DBL_PAR_OPTIMALITYTOL = "OptimalityTol"
const GRB_DBL_PAR_PSDTOL = "PSDTol"
const GRB_INT_PAR_METHOD = "Method"
const GRB_DBL_PAR_PERTURBVALUE = "PerturbValue"
const GRB_DBL_PAR_OBJSCALE = "ObjScale"
const GRB_INT_PAR_SCALEFLAG = "ScaleFlag"
const GRB_INT_PAR_SIMPLEXPRICING = "SimplexPricing"
const GRB_INT_PAR_QUAD = "Quad"
const GRB_INT_PAR_NORMADJUST = "NormAdjust"
const GRB_INT_PAR_SIFTING = "Sifting"
const GRB_INT_PAR_SIFTMETHOD = "SiftMethod"
const GRB_DBL_PAR_BARCONVTOL = "BarConvTol"
const GRB_INT_PAR_BARCORRECTORS = "BarCorrectors"
const GRB_INT_PAR_BARHOMOGENEOUS = "BarHomogeneous"
const GRB_INT_PAR_BARORDER = "BarOrder"
const GRB_DBL_PAR_BARQCPCONVTOL = "BarQCPConvTol"
const GRB_INT_PAR_CROSSOVER = "Crossover"
const GRB_INT_PAR_CROSSOVERBASIS = "CrossoverBasis"
const GRB_INT_PAR_BRANCHDIR = "BranchDir"
const GRB_INT_PAR_DEGENMOVES = "DegenMoves"
const GRB_INT_PAR_DISCONNECTED = "Disconnected"
const GRB_DBL_PAR_HEURISTICS = "Heuristics"
const GRB_DBL_PAR_IMPROVESTARTGAP = "ImproveStartGap"
const GRB_DBL_PAR_IMPROVESTARTTIME = "ImproveStartTime"
const GRB_DBL_PAR_IMPROVESTARTNODES = "ImproveStartNodes"
const GRB_INT_PAR_INTEGRALITYFOCUS = "IntegralityFocus"
const GRB_INT_PAR_MINRELNODES = "MinRelNodes"
const GRB_INT_PAR_MIPFOCUS = "MIPFocus"
const GRB_STR_PAR_NODEFILEDIR = "NodefileDir"
const GRB_DBL_PAR_NODEFILESTART = "NodefileStart"
const GRB_INT_PAR_NODEMETHOD = "NodeMethod"
const GRB_DBL_PAR_NORELHEURTIME = "NoRelHeurTime"
const GRB_DBL_PAR_NORELHEURWORK = "NoRelHeurWork"
const GRB_INT_PAR_PUMPPASSES = "PumpPasses"
const GRB_INT_PAR_RINS = "RINS"
const GRB_STR_PAR_SOLFILES = "SolFiles"
const GRB_INT_PAR_STARTNODELIMIT = "StartNodeLimit"
const GRB_INT_PAR_SUBMIPNODES = "SubMIPNodes"
const GRB_INT_PAR_SYMMETRY = "Symmetry"
const GRB_INT_PAR_VARBRANCH = "VarBranch"
const GRB_INT_PAR_SOLUTIONNUMBER = "SolutionNumber"
const GRB_INT_PAR_ZEROOBJNODES = "ZeroObjNodes"
const GRB_INT_PAR_CUTS = "Cuts"
const GRB_INT_PAR_CLIQUECUTS = "CliqueCuts"
const GRB_INT_PAR_COVERCUTS = "CoverCuts"
const GRB_INT_PAR_FLOWCOVERCUTS = "FlowCoverCuts"
const GRB_INT_PAR_FLOWPATHCUTS = "FlowPathCuts"
const GRB_INT_PAR_GUBCOVERCUTS = "GUBCoverCuts"
const GRB_INT_PAR_IMPLIEDCUTS = "ImpliedCuts"
const GRB_INT_PAR_PROJIMPLIEDCUTS = "ProjImpliedCuts"
const GRB_INT_PAR_MIPSEPCUTS = "MIPSepCuts"
const GRB_INT_PAR_MIRCUTS = "MIRCuts"
const GRB_INT_PAR_STRONGCGCUTS = "StrongCGCuts"
const GRB_INT_PAR_MODKCUTS = "ModKCuts"
const GRB_INT_PAR_ZEROHALFCUTS = "ZeroHalfCuts"
const GRB_INT_PAR_NETWORKCUTS = "NetworkCuts"
const GRB_INT_PAR_SUBMIPCUTS = "SubMIPCuts"
const GRB_INT_PAR_INFPROOFCUTS = "InfProofCuts"
const GRB_INT_PAR_RLTCUTS = "RLTCuts"
const GRB_INT_PAR_RELAXLIFTCUTS = "RelaxLiftCuts"
const GRB_INT_PAR_BQPCUTS = "BQPCuts"
const GRB_INT_PAR_PSDCUTS = "PSDCuts"
const GRB_INT_PAR_CUTAGGPASSES = "CutAggPasses"
const GRB_INT_PAR_CUTPASSES = "CutPasses"
const GRB_INT_PAR_GOMORYPASSES = "GomoryPasses"
const GRB_STR_PAR_WORKERPOOL = "WorkerPool"
const GRB_STR_PAR_WORKERPASSWORD = "WorkerPassword"
const GRB_STR_PAR_COMPUTESERVER = "ComputeServer"
const GRB_STR_PAR_TOKENSERVER = "TokenServer"
const GRB_STR_PAR_SERVERPASSWORD = "ServerPassword"
const GRB_INT_PAR_SERVERTIMEOUT = "ServerTimeout"
const GRB_STR_PAR_CSROUTER = "CSRouter"
const GRB_STR_PAR_CSGROUP = "CSGroup"
const GRB_DBL_PAR_CSQUEUETIMEOUT = "CSQueueTimeout"
const GRB_INT_PAR_CSPRIORITY = "CSPriority"
const GRB_INT_PAR_CSIDLETIMEOUT = "CSIdleTimeout"
const GRB_INT_PAR_CSTLSINSECURE = "CSTLSInsecure"
const GRB_INT_PAR_TSPORT = "TSPort"
const GRB_STR_PAR_CLOUDACCESSID = "CloudAccessID"
const GRB_STR_PAR_CLOUDSECRETKEY = "CloudSecretKey"
const GRB_STR_PAR_CLOUDPOOL = "CloudPool"
const GRB_STR_PAR_CLOUDHOST = "CloudHost"
const GRB_STR_PAR_CSMANAGER = "CSManager"
const GRB_STR_PAR_CSAUTHTOKEN = "CSAuthToken"
const GRB_STR_PAR_CSAPIACCESSID = "CSAPIAccessID"
const GRB_STR_PAR_CSAPISECRET = "CSAPISecret"
const GRB_INT_PAR_CSBATCHMODE = "CSBatchMode"
const GRB_STR_PAR_USERNAME = "Username"
const GRB_STR_PAR_CSAPPNAME = "CSAppName"
const GRB_INT_PAR_CSCLIENTLOG = "CSClientLog"
const GRB_INT_PAR_AGGREGATE = "Aggregate"
const GRB_INT_PAR_AGGFILL = "AggFill"
const GRB_INT_PAR_CONCURRENTMIP = "ConcurrentMIP"
const GRB_INT_PAR_CONCURRENTJOBS = "ConcurrentJobs"
const GRB_INT_PAR_DISPLAYINTERVAL = "DisplayInterval"
const GRB_INT_PAR_DISTRIBUTEDMIPJOBS = "DistributedMIPJobs"
const GRB_INT_PAR_DUALREDUCTIONS = "DualReductions"
const GRB_DBL_PAR_FEASRELAXBIGM = "FeasRelaxBigM"
const GRB_INT_PAR_IISMETHOD = "IISMethod"
const GRB_INT_PAR_INFUNBDINFO = "InfUnbdInfo"
const GRB_INT_PAR_JSONSOLDETAIL = "JSONSolDetail"
const GRB_INT_PAR_LAZYCONSTRAINTS = "LazyConstraints"
const GRB_STR_PAR_LOGFILE = "LogFile"
const GRB_INT_PAR_LOGTOCONSOLE = "LogToConsole"
const GRB_INT_PAR_MIQCPMETHOD = "MIQCPMethod"
const GRB_INT_PAR_NONCONVEX = "NonConvex"
const GRB_INT_PAR_NUMERICFOCUS = "NumericFocus"
const GRB_INT_PAR_OUTPUTFLAG = "OutputFlag"
const GRB_INT_PAR_PRECRUSH = "PreCrush"
const GRB_INT_PAR_PREDEPROW = "PreDepRow"
const GRB_INT_PAR_PREDUAL = "PreDual"
const GRB_INT_PAR_PREPASSES = "PrePasses"
const GRB_INT_PAR_PREQLINEARIZE = "PreQLinearize"
const GRB_INT_PAR_PRESOLVE = "Presolve"
const GRB_DBL_PAR_PRESOS1BIGM = "PreSOS1BigM"
const GRB_DBL_PAR_PRESOS2BIGM = "PreSOS2BigM"
const GRB_INT_PAR_PRESPARSIFY = "PreSparsify"
const GRB_INT_PAR_PREMIQCPFORM = "PreMIQCPForm"
const GRB_INT_PAR_QCPDUAL = "QCPDual"
const GRB_INT_PAR_RECORD = "Record"
const GRB_STR_PAR_RESULTFILE = "ResultFile"
const GRB_INT_PAR_SEED = "Seed"
const GRB_INT_PAR_THREADS = "Threads"
const GRB_DBL_PAR_TUNETIMELIMIT = "TuneTimeLimit"
const GRB_INT_PAR_TUNERESULTS = "TuneResults"
const GRB_INT_PAR_TUNECRITERION = "TuneCriterion"
const GRB_INT_PAR_TUNETRIALS = "TuneTrials"
const GRB_INT_PAR_TUNEOUTPUT = "TuneOutput"
const GRB_INT_PAR_TUNEJOBS = "TuneJobs"
const GRB_DBL_PAR_TUNECLEANUP = "TuneCleanup"
const GRB_INT_PAR_UPDATEMODE = "UpdateMode"
const GRB_INT_PAR_OBJNUMBER = "ObjNumber"
const GRB_INT_PAR_MULTIOBJMETHOD = "MultiObjMethod"
const GRB_INT_PAR_MULTIOBJPRE = "MultiObjPre"
const GRB_INT_PAR_SCENARIONUMBER = "ScenarioNumber"
const GRB_INT_PAR_POOLSOLUTIONS = "PoolSolutions"
const GRB_DBL_PAR_POOLGAP = "PoolGap"
const GRB_DBL_PAR_POOLGAPABS = "PoolGapAbs"
const GRB_INT_PAR_POOLSEARCHMODE = "PoolSearchMode"
const GRB_INT_PAR_IGNORENAMES = "IgnoreNames"
const GRB_INT_PAR_STARTNUMBER = "StartNumber"
const GRB_INT_PAR_PARTITIONPLACE = "PartitionPlace"
const GRB_INT_PAR_FUNCPIECES = "FuncPieces"
const GRB_DBL_PAR_FUNCPIECELENGTH = "FuncPieceLength"
const GRB_DBL_PAR_FUNCPIECEERROR = "FuncPieceError"
const GRB_DBL_PAR_FUNCPIECERATIO = "FuncPieceRatio"
const GRB_DBL_PAR_FUNCMAXVAL = "FuncMaxVal"
const GRB_STR_PAR_DUMMY = "Dummy"
const GRB_STR_PAR_JOBID = "JobID"
const GRB_CUTS_AUTO = -1
const GRB_CUTS_OFF = 0
const GRB_CUTS_CONSERVATIVE = 1
const GRB_CUTS_AGGRESSIVE = 2
const GRB_CUTS_VERYAGGRESSIVE = 3
const GRB_PRESOLVE_AUTO = -1
const GRB_PRESOLVE_OFF = 0
const GRB_PRESOLVE_CONSERVATIVE = 1
const GRB_PRESOLVE_AGGRESSIVE = 2
const GRB_METHOD_AUTO = -1
const GRB_METHOD_PRIMAL = 0
const GRB_METHOD_DUAL = 1
const GRB_METHOD_BARRIER = 2
const GRB_METHOD_CONCURRENT = 3
const GRB_METHOD_DETERMINISTIC_CONCURRENT = 4
const GRB_METHOD_DETERMINISTIC_CONCURRENT_SIMPLEX = 5
const GRB_BARHOMOGENEOUS_AUTO = -1
const GRB_BARHOMOGENEOUS_OFF = 0
const GRB_BARHOMOGENEOUS_ON = 1
const GRB_MIPFOCUS_BALANCED = 0
const GRB_MIPFOCUS_FEASIBILITY = 1
const GRB_MIPFOCUS_OPTIMALITY = 2
const GRB_MIPFOCUS_BESTBOUND = 3
const GRB_BARORDER_AUTOMATIC = -1
const GRB_BARORDER_AMD = 0
const GRB_BARORDER_NESTEDDISSECTION = 1
const GRB_SIMPLEXPRICING_AUTO = -1
const GRB_SIMPLEXPRICING_PARTIAL = 0
const GRB_SIMPLEXPRICING_STEEPEST_EDGE = 1
const GRB_SIMPLEXPRICING_DEVEX = 2
const GRB_SIMPLEXPRICING_STEEPEST_QUICK = 3
const GRB_VARBRANCH_AUTO = -1
const GRB_VARBRANCH_PSEUDO_REDUCED = 0
const GRB_VARBRANCH_PSEUDO_SHADOW = 1
const GRB_VARBRANCH_MAX_INFEAS = 2
const GRB_VARBRANCH_STRONG = 3
const GRB_PARTITION_EARLY = 16
const GRB_PARTITION_ROOTSTART = 8
const GRB_PARTITION_ROOTEND = 4
const GRB_PARTITION_NODES = 2
const GRB_PARTITION_CLEANUP = 1
const GRB_BATCH_STATUS_UNKNOWN = 0
const GRB_BATCH_CREATED = 1
const GRB_BATCH_SUBMITTED = 2
const GRB_BATCH_ABORTED = 3
const GRB_BATCH_FAILED = 4
const GRB_BATCH_COMPLETED = 5
const _GRBbatch = Cvoid
const GRBbatch = _GRBbatch
const _GRBmodel = Cvoid
const GRBmodel = _GRBmodel
const _GRBenv = Cvoid
const GRBenv = _GRBenv

struct _GRBsvec
    len::Cint
    ind::Ptr{Cint}
    val::Ptr{Cdouble}
end

const GRBsvec = _GRBsvec


text:
@testset "Bipartiteness" begin
    g6 = smallgraph(:house)
    for g in testgraphs(g6)
        @test @inferred(!is_bipartite(g))
    end

    gx = SimpleGraph(5)
    add_edge!(gx, 1, 2); add_edge!(gx, 1, 4)
    add_edge!(gx, 2, 3); add_edge!(gx, 2, 5)
    add_edge!(gx, 3, 4)

    for g in testgraphs(gx)
        @test @inferred(is_bipartite(g))
    end

    g10 = CompleteGraph(10)
    for g in testgraphs(g10)
        @test @inferred(bipartite_map(g)) == Vector{eltype(g)}()
    end

    g10 = CompleteBipartiteGraph(10, 10)
    for g in testgraphs(g10)
        T = eltype(g)
        @test @inferred(bipartite_map(g)) == Vector{T}([ones(T, 10); 2 * ones(T, 10)])

        h = blockdiag(g, g)
        @test @inferred(bipartite_map(h)) == Vector{T}([ones(T, 10); 2 * ones(T, 10); ones(T, 10); 2 * ones(T, 10)])
    end

    g2 = CompleteGraph(2)
    for g in testgraphs(g2)
        @test @inferred(bipartite_map(g)) == Vector{eltype(g)}([1, 2])
    end

    g2 = Graph(2)
    for g in testgraphs(g2)
        @test @inferred(bipartite_map(g)) == Vector{eltype(g)}([1, 1])
    end

    g2 = DiGraph(2)
    for g in testdigraphs(g2)
        @test @inferred(bipartite_map(g)) == Vector{eltype(g)}([1, 1])
    end

    g2 = PathDiGraph(2)
    for g in testdigraphs(g2)
        @test @inferred(bipartite_map(g)) == Vector{eltype(g)}([1, 2])
    end
end


text:
# EFTfitter.jl - Empty Template
using EFTfitter
using BAT            # for sampling
using IntervalSets   # for specifying the prior
using Distributions  # for specifying the prior
using Plots # for plotting

# include definitions of observables, measurements,
# uncertainties and correlations from the inputs file:
include("inputs.jl")

# create an `EFTfitterModel` object:
model = EFTfitterModel(parameters, measurements, correlations)
# create posterior distribution:
posterior = PosteriorDensity(model);

# sample the posterior distribution with BAT.jl:
algorithm = MCMCSampling(mcalg = MetropolisHastings(), nsteps = 10^5, nchains = 4)
samples = bat_sample(posterior, algorithm).result;

# create and display a `SampledDensity` object for a quick overview of results:
sd = SampledDensity(posterior, samples)
display(sd)

#  plot the posterior distribution:
p = plot(samples)
savefig(p, "plot.pdf")

# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl


text:
using DelimitedFiles
using StatsBase

input = joinpath(@__DIR__, "input")
fish = readdlm(input, ',', Int)

function advance(fish, days)
    for _ in 1:days
        next = Dict()
        for (age, n) in fish
            if age == 0
                haskey(next, 6) ? next[6] += n : next[6] = n
                next[8] = n
            else
                haskey(next, age - 1) ? next[age - 1] += n : next[age - 1] = n
            end
        end
        fish = next
    end
    return fish
end

fish = countmap(vec(fish))

p1 = sum(map(fishes -> last(fishes), collect(advance(fish, 80))))
p2 = sum(map(fishes -> last(fishes), collect(advance(fish, 256))))

println("-----------------------------------------------------------------------")
println("lanternfish -- part one :: $p1")
println("lanternfish -- part two :: $p2")
println("-----------------------------------------------------------------------")

@assert(p1 == 383160)
@assert(p2 == 1721148811504)


text:
using LinearAlgebra

@testset "bipartite_matching_test" begin
    W = sprand(10,8,0.5)
    bipartite_matching(W)
    bipartite_matching([10;12;13],[1;2;3],[3;2;4])

    A = [5 1 1 1 1;
     1 5 1 1 1;
     1 1 5 1 1;
     1 1 1 5 1;
     1 1 1 1 5;
     1 1 1 1 1]
    A = sparse(A)
    M1 = bipartite_matching(A)
    (m1,m2) = edge_list(M1)

    @test M1.weight == 25/maximum(abs.(A)) && isequal(m1,m2)

    A = ones(Int64,6,5) - Matrix(I,6,5)
    A = sparse(A')
    (ei,ej,ev) = csr_to_sparse(A.colptr,A.rowval,A.nzval)
    ai = [1;2;3;4;5;ei]
    aj = [1;2;3;4;5;ej]
    av = [5;5;5;5;5;ev]

    M2 = bipartite_matching(av,ai,aj)
    mi = MatrixNetworks.edge_indicator(M2,ai,aj)
    mitrue = zeros(Int64,length(av))
    mitrue[1:5] .= 1

    @test M2.weight == 25/maximum(abs.(av)) && isequal(m1,m2) && sum(mi) ==5 && isequal(mi,mitrue)

    M2 = bipartite_matching(av,ai,aj,maximum(ai),maximum(aj))
    mi = MatrixNetworks.edge_indicator(M2,ai,aj)
    mitrue = zeros(Int64,length(av))
    mitrue[1:5] .= 1

    @test M2.weight == 25/maximum(abs.(av)) && isequal(m1,m2) && sum(mi) ==5 && isequal(mi,mitrue)
end


text:
module BayesianIntegral

using Distributions
using LinearAlgebra
using Random
using Optim

# Basic operation of Kriging model
include("kriging_structs.jl")
export KrigingModel, GaussianKernelHyperparameters
include("making_covariances.jl")
export gaussian_kernel, marginal_gaussian_kernel, K_matrix
export marginal_likelihood_gaussian_derivatives, log_likelihood
export correlation_vector_of_a_point
include("evaluate_kriging_model.jl")
export evaluate, predicted_error
# Integration of Kriging Model
include("integrate_given_hyperparameters.jl")
export integrate
# Calibration of Kriging Model
include("calibrate_weights.jl")
export calibrate_by_ML_with_SGD, RProp_params, calibrate_by_ML_with_Rprop

# Searching for Optima.
include("Expected_improvement_optimisation.jl")
export expected_improvement, get_next_query_point_through_expected_improvement, get_predicted_minimum

end


text:
@testset "likelihood" begin
    struct NewLikelihood{T} <: AGP.AbstractLikelihood{T} end
    @test_throws ErrorException NewLikelihood{Float64}()(rand(), rand())
    @test length(NewLikelihood{Float64}()) == 1
end


text:
# This file was generated, do not modify it. # hide
avg = @from_network MyAverageTwo(regressor1=model1,
                                 regressor2=model2) <= yhat

max_stars_repo_name: ven-k/MLJTutorials

max_issues_repo_name: ven-k/MLJTutorials

max_forks_repo_name: ven-k/MLJTutorials


text:
export Xavier

doc"""
    Xavier()

Xavier initialization.
"""
struct Xavier
end

function (::Xavier)(::Type{T}, dims::Int...) where T
    v = 2 / sum(dims)
    Normal(0,v)(T, dims...)
end


text:
module DScribe

using ASE
using JuLIP
using PyCall

py_dscribe = pyimport("dscribe")
py_dsd = pyimport("dscribe.descriptors")

export dscribe_cm, dscribe_sm, dscribe_em
export dscribe_soap, dscribe_mbtr, dscribe_acsf, set_Behler2011

# This function is part of ACSF.jl package
function set_Behler2011()
    unit_BOHR = 0.52917721067
    cutoff = 6.5
    Gpack = [
        [   9.0,  100.0,  200.0,  350.0,  600.0, 1000.0, 2000.0, 4000.0], #G2_etas
        [   1.0,    1.0,    1.0,    1.0,   30.0,   30.0,   30.0,   30.0,
           80.0,   80.0,   80.0,   80.0,  150.0,  150.0,  150.0,  150.0,
          150.0,  150.0,  150.0,  150.0,  250.0,  250.0,  250.0,  250.0,
          250.0,  250.0,  250.0,  250.0,  450.0,  450.0,  450.0,  450.0,
          450.0,  450.0,  450.0,  450.0,  800.0,  800.0,  800.0,  800.0,
          800.0,  800.0,  800.0], #G4_etas
        [  -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,
           -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,
           -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,
           -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,
           -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,   -1.0,    1.0,
           -1.0,    1.0,    1.0], #G4_lambdas
        [   1.0,    1.0,    2.0,    2.0,    1.0,    1.0,    2.0,    2.0,
            1.0,    1.0,    2.0,    2.0,    1.0,    1.0,    2.0,    2.0,
            4.0,    4.0,   16.0,   16.0,    1.0,    1.0,    2.0,    2.0,
            4.0,    4.0,   16.0,   16.0,    1.0,    1.0,    2.0,    2.0,
            4.0,    4.0,   16.0,   16.0,    1.0,    1.0,    2.0,    2.0,
            4.0,    4.0,   16.0] #G4_zetas
    ]
    Gpack[1] ./= 10000.0 * unit_BOHR^2
    Gpack[2] ./= 10000.0 * unit_BOHR^2
    return Dict("G2" => [cutoff,Gpack[1],[ 0.0 for i=1:length(Gpack[1])]],
                "G4" => [cutoff,Gpack[2],Gpack[3],Gpack[4]])
end

function dscribe_matdesc(at; mattyp="cm",
                         n_atoms_max=nothing,
                         permutation="sorted_l2",
                         sigma=nothing,
                         seed=nothing,
                         flatten=true,
                         sparse=false)
    """
        permutation = sorted_l2 (default), none, random, or eigenspectrum
    """
    if n_atoms_max == nothing
        n_atoms_max = length(at.Z)
    end

    #Setting Dscribe matrix descriptor
    if mattyp == "sm"
        mat_desc = py_dsd.SineMatrix(n_atoms_max=n_atoms_max,
                                     permutation=permutation,
                                     sigma=sigma,
                                     seed=seed,
                                     flatten=flatten,
                                     sparse=sparse)
    elseif matype == "em"
        mat_desc = py_dsd.EwaldSumMatrix(n_atoms_max=n_atoms_max,
                                         permutation=permutation,
                                         sigma=sigma,
                                         seed=seed,
                                         flatten=flatten,
                                         sparse=sparse)
    else
        mat_desc = py_dsd.CoulombMatrix(n_atoms_max=n_atoms_max,
                                        permutation=permutation,
                                        sigma=sigma,
                                        seed=seed,
                                        flatten=flatten,
                                        sparse=sparse)
    end

    # Calculate descriptor
    atom_struct = ASEAtoms(at)
    mat_rtn_desc = mat_desc.create(atom_struct.po)
    return mat_rtn_desc
end

dscribe_cm(at; kwargs...) = dscribe_matdesc(at; mattyp="cm", kwargs...)
dscribe_sm(at; kwargs...) = dscribe_matdesc(at; mattyp="sm", kwargs...)
dscribe_em(at; kwargs...) = dscribe_matdesc(at; mattyp="em", kwargs...)

function dscribe_acsf(at; cutoff=nothing,
                          species=nothing,
                          periodic=false,
                          sparse=false,
                          g2_params="Behler2011",
                          g3_params=nothing,
                          g4_params="Behler2011",
                          g5_params=nothing)

all_unique_nums = unique(collect(at.Z))
all_unique_species = unique(chemical_symbols(at))

if species == nothing
 species = all_unique_species
end

if g2_params == "Behler2011" || g4_params == "Behler2011"
    G = set_Behler2011()
    if g2_params == "Behler2011"
        g2_params = hcat(G["G2"][2], G["G2"][3])
        cutoff = maximum(G["G2"][1])
    end
    if g4_params == "Behler2011"
        g4_params = hcat(G["G4"][2] ,G["G4"][4] ,G["G4"][3])
        cutoff = maximum(G["G4"][1])
    end
end

acsf_desc = py_dsd.ACSF(species=species,
                        rcut=cutoff,
                        g2_params=g2_params,
                        g3_params=g3_params,
                        g4_params=g4_params,
                        g5_params=g5_params,
                        periodic=periodic,
                        sparse=sparse)

# Calculate descriptor
atom_struct = ASEAtoms(at)
acsf_rtn_desc = acsf_desc.create(atom_struct.po)
return acsf_rtn_desc
end

dscribe_acsf(at, cutoff; kwargs...) = dscribe_acsf(at; cutoff=cutoff, kwargs...)

function dscribe_soap(at, cutoff; n_max=1, l_max=1, sigma=0.5,
                      rbf="gto", species=nothing,
                      periodic=true, crossover=true,
                      average="off", sparse=false)

if species == nothing
    species = unique(collect(at.Z))
end

#Setting Dscribe SOAP Descriptor
soap_desc = py_dsd.SOAP(cutoff, n_max, l_max,
                        sigma=sigma, rbf=rbf,
                        species=species,
                        periodic=periodic,
                        crossover=crossover,
                        average=average,
                        sparse=sparse)

# Calculate descriptor
atom_struct = ASEAtoms(at)
soap_rtn_desc = soap_desc.create(atom_struct.po)

return soap_rtn_desc
end

function dscribe_mbtr(at, periodic; species=nothing,
                      k1=nothing, k2=nothing, k3=nothing,
                      normalize_gaussians=true,
                      normalization="none",
                      flatten=true, sparse=false)

all_unique_nums = unique(collect(at.Z))
all_unique_species = unique(chemical_symbols(at))

if species == nothing
    species = all_unique_species
end

if k1 ==nothing && k2 == nothing && k3 == nothing
    k2 = Dict()
    k2["geometry"] = Dict()
    k2["geometry"]["function"] = "inverse_distance"
    k2["grid"] = Dict()
    k2["grid"]["min"] = 0.1
    k2["grid"]["max"] = 1.1
    k2["grid"]["n"] = 100
    k2["grid"]["sigma"] = 0.0
    #k2["weighting"] = Dict()
    #k2["weighting"]["function"] = "exponential"
    #k2["weighting"]["scale"] = 0.5
    #k2["weighting"]["cutoff"] = 1e-3

    k3 = Dict()
    k3["geometry"] = Dict()
    k3["geometry"]["function"] = "angle"
    k3["grid"] = Dict()
    k3["grid"]["min"] = 0.15
    k3["grid"]["max"] = 3.45575
    k3["grid"]["n"] = 100
    k3["grid"]["sigma"] = 0.0
    #k3["weighting"] = Dict()
    #k3["weighting"]["function"] = "exponential"
    #k3["weighting"]["scale"] = 0.5
    #k3["weighting"]["cutoff"] = 1e-3
end

#Setting Dscribe MBTR Descriptor
mbtr_desc = py_dsd.MBTR(periodic, species,
                        k1=k1, k2=k2, k3=k3,
                        normalize_gaussians=normalize_gaussians,
                        normalization=normalization,
                        flatten=flatten,
                        sparse=sparse)

# Calculate descriptor
atom_struct = ASEAtoms(at)
mbtr_rtn_desc = mbtr_desc.create(atom_struct.po)
return mbtr_rtn_desc
end

end # module


text:
using Libdl

rrlib = Libdl.dlopen("roadrunner_c_api.dll")

struct RRVector
end

struct RRDoubleMatrix
end

struct RRStringArray
end

struct RRCData
end

function disableLoggingToConsole()
    ccall(dlsym(rrlib, :disableLoggingToConsole), cdecl, Bool, ())
end

function setConfigBool(key::String, value::Int64)
    ccall(dlsym(rrlib, :setConfigBool), cdecl, Int64, (Ptr{UInt8}, Cint), key, value)
end

function createRRInstance()
  val = ccall(dlsym(rrlib, :createRRInstance), cdecl, Ptr{Nothing}, ())
  if val == C_NULL
    error("Failed to start up roadRunner")
  end
  return val
end

function addCompartment(rr, cid::String, initVolume::Float64, regen::Bool)
  status = false
  if regen == true
    status = ccall(dlsym(rrlib, :addCompartment), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Cdouble), rr, cid, initVolume)
  else
    status = ccall(dlsym(rrlib, :addCompartmentNoRegen), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Cdouble), rr, cid, initVolume)
  end
  if status == false
    error(getLastError())
  end
end

function addParameter(rr::Ptr{Nothing}, pid::String, value::Float64, forceRegen::Bool)
  status = false
  if forceRegen == true
     status = ccall(dlsym(rrlib, :addParameter), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Cdouble), rr, pid, value)
  else
    status = ccall(dlsym(rrlib, :addParameterNoRegen), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Cdouble), rr, pid, value)
  end
  if status == false
    error(getLastError())
  end
end

function addSpecies(rr::Ptr{Nothing}, sid::String, compartment::String, initialAmount::Float64, substanceUnit::String, regen::Bool)
  status = false
  if regen == true
    status = ccall(Libdl.dlsym(rrlib, :addSpecies), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Ptr{UInt8}, Cdouble, Ptr{UInt8}), rr, sid, compartment, initialAmount, substanceUnit)
  else
    status = ccall(Libdl.dlsym(rrlib, :addSpeciesNoRegen), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Ptr{UInt8}, Cdouble, Ptr{UInt8}), rr, sid, compartment, initialAmount, substanceUnit)
  end
  if status == false
    error(getLastError())
  end
end

function addReaction(rr::Ptr{Nothing}, rid::String, reactants::Array{String}, products::Array{String}, kineticLaw::String, regen::Bool)
  numReactants = length(reactants)
  numProducts = length(products)
  status = false
  if regen == true
    status = ccall(dlsym(rrlib, :addReaction), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Ptr{Ptr{UInt8}}, Cint, Ptr{Ptr{UInt8}}, Cint, Ptr{UInt8}), rr, rid, reactants, numReactants, products, numProducts, kineticLaw)
  else
    status = ccall(dlsym(rrlib, :addReactionNoRegen), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Ptr{Ptr{UInt8}}, Cint, Ptr{Ptr{UInt8}}, Cint, Ptr{UInt8}), rr, rid, reactants, numReactants, products, numProducts, kineticLaw)
  end
  if status == false
    error(getLastError())
  end
end

function removeReaction(rr::Ptr{Nothing}, rid::String, regen::Bool)
  status = false
  if regen == true
    status = ccall(dlsym(rrlib, :removeReaction), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}), rr, rid)
  else
    status = ccall(dlsym(rrlib, :removeReactionNoRegen), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}), rr, rid)
  end
  if status == false
    error(getLastError())
  end
end

function getNumberOfReactions(rr::Ptr{Nothing})
  return ccall(dlsym(rrlib, :getNumberOfReactions), cdecl, Int64, (Ptr{Nothing},), rr)
end

function getReactionIds(rr)
  return ccall(dlsym(rrlib, :getReactionIds), cdecl, Ptr{RRStringArray}, (Ptr{Nothing},), rr)
end

function getSBML(rr)
  char_pointer=ccall(dlsym(rrlib, :getSBML), cdecl, Ptr{UInt8}, (Ptr{Nothing},), rr)
  julia_str=unsafe_string(char_pointer)
  freeText(char_pointer)
  return julia_str
end

function getCurrentSBML(rr)
  char_pointer=ccall(dlsym(rrlib, :getCurrentSBML), cdecl, Ptr{UInt8}, (Ptr{Nothing},), rr)
  julia_str=unsafe_string(char_pointer)
  freeText(char_pointer)
  return julia_str
end

function loadSBML(rr::Ptr{Nothing}, sbml::String)
  return ccall(dlsym(rrlib, :loadSBML), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}), rr, sbml)
end

function getNumberOfGlobalParameters(rr)
  return ccall(dlsym(rrlib, :getNumberOfGlobalParameters), cdecl, Int64, (Ptr{Nothing},), rr)
end

function getNumberOfFloatingSpecies(rr)
  return ccall(dlsym(rrlib, :getNumberOfFloatingSpecies), cdecl, Int64, (Ptr{Nothing},), rr)
end

function setFloatingSpeciesInitialConcentrationByIndex(rr, index::Int64, value::Float64)
  return ccall(dlsym(rrlib, :setFloatingSpeciesInitialConcentrationByIndex), cdecl, Bool, (Ptr{Nothing}, Int64, Float64), rr, index, value)
end

function setFloatingSpeciesByIndex(rr::Ptr{Nothing}, index::Int64, value::Float64)
  status = ccall(dlsym(rrlib, :setFloatingSpeciesByIndex), cdecl, Bool, (Ptr{Nothing}, Int64, Float64), rr, index, value)
  if status == false
    error(getLastError())
  end
end

function setGlobalParameterByIndex(rr, index::Int64, value::Float64)
  return ccall(dlsym(rrlib, :setGlobalParameterByIndex), cdecl, Bool, (Ptr{Nothing}, Int64, Float64), rr, index, value)
end

function setConfigInt(key::String, value::Int64)
    ccall(dlsym(rrlib, :setConfigInt), cdecl, Int64, (Ptr{UInt8}, Cint), key, value)
end

function steadyState(rr)
  value = Array{Float64}(undef, 1)
  status = ccall(dlsym(rrlib, :steadyState), cdecl, Bool, (Ptr{Nothing}, Ptr{Float64}), rr, value)
  if status == false
    error(getLastError())
  end
  return value[1]
end

function getFloatingSpeciesConcentrations(rr)
  return ccall(dlsym(rrlib, :getFloatingSpeciesConcentrations), cdecl, Ptr{RRVector}, (Ptr{Nothing},), rr)
end

function getVectorElement(vector::Ptr{RRVector}, index::Int64)
  value = Array{Float64}(undef,1)
  ccall(dlsym(rrlib, :getVectorElement), cdecl, Bool, (Ptr{RRVector}, Int64, Ptr{Cdouble}), vector, index, value)
  return value[1]
end

function freeVector(vector::Ptr{RRVector})
  status = ccall(dlsym(rrlib, :freeVector), cdecl, Bool, (Ptr{RRVector},), vector)
  if status == false
    (error(getLastError()))
  end
end

function getScaledConcentrationControlCoefficientMatrix(rr)
  return ccall(dlsym(rrlib, :getScaledConcentrationControlCoefficientMatrix), cdecl, Ptr{RRDoubleMatrix}, (Ptr{Nothing},), rr)
end

function getMatrixElement(m::Ptr{RRDoubleMatrix}, r::Int64, c::Int64)
  value = Array{Float64}(undef,1)
  status = ccall(dlsym(rrlib, :getMatrixElement), cdecl, Bool, (Ptr{RRDoubleMatrix}, Int64, Int64, Ptr{Cdouble}), m, r, c, value)
  if status == false
    error(getLastError())
  end
  return value[1]
end

function setMatrixElement(m::Ptr{RRDoubleMatrix}, r::Int64, c::Int64, value::Float64)
  status = ccall(dlsym(rrlib, :setMatrixElement), cdecl, Bool, (Ptr{RRDoubleMatrix}, Int64, Int64, Float64), m, r, c, value)
  if status == false
    error(getLastError())
  end
end

function getGlobalParameterIds(rr)
  return ccall(dlsym(rrlib, :getGlobalParameterIds), cdecl, Ptr{RRStringArray}, (Ptr{Nothing},), rr)
end

function getStringElement(list::Ptr{RRStringArray}, index::Int64)
  char_pointer=ccall(dlsym(rrlib, :getStringElement), cdecl, Ptr{UInt8}, (Ptr{RRStringArray}, Int64), list, index)
  julia_str=unsafe_string(char_pointer)
  freeText(char_pointer)
  return julia_str
end

function freeRRInstance(rr::Ptr{Nothing})
  free_status = ccall(dlsym(rrlib, :freeRRInstance), cdecl, Bool, (Ptr{Nothing},), rr)
  if free_status == false
    error(getLastError())
  end
end

function freeMatrix(matrix::Ptr{RRDoubleMatrix})
  status = ccall(dlsym(rrlib, :freeMatrix), cdecl, Bool, (Ptr{RRDoubleMatrix},), matrix)
  if status == false
    (error(getLastError()))
  end
end

function getLastError()
  char_pointer = ccall(dlsym(rrlib, :getLastError), cdecl, Ptr{UInt8}, ())
  julia_str = unsafe_string(char_pointer)
  #freeText(char_pointer)
  return julia_str
end

function simulate(rr::Ptr{Nothing})
  return ccall(dlsym(rrlib, :simulate), cdecl, Ptr{RRCData}, (Ptr{Nothing},), rr)
end

function getRateOfChange(rr, index::Int64)
  value = Array{Float64}(undef,1)
  ccall(dlsym(rrlib, :getRateOfChange), cdecl, Bool, (Ptr{Nothing}, Int64, Ptr{Float64}), rr, index, value)
  return value[1]
end

function freeRRCData(handle::Ptr{RRCData})
  status = ccall(dlsym(rrlib, :freeRRCData), cdecl, Bool, (Ptr{RRCData},), handle)
  if status == false
    error(getLastError())
  end
end

function freeText(text::Ptr{UInt8})
  status = ccall(dlsym(rrlib, :freeText), cdecl, Bool, (Ptr{UInt8},), text)
  if status == false
    error(getLastError())
  end
end

function freeStringArray(sl::Ptr{RRStringArray})
  status =  ccall(dlsym(rrlib, :freeStringArray), cdecl, Bool, (Ptr{RRStringArray},), sl)
  if status == false
    error(getLastError())
  end
end

function getFloatingSpeciesIds(rr)
  return ccall(dlsym(rrlib, :getFloatingSpeciesIds), cdecl, Ptr{RRStringArray}, (Ptr{Nothing},), rr)
end

function getBoundarySpeciesIds(rr)
  return ccall(dlsym(rrlib, :getBoundarySpeciesIds), cdecl, Ptr{RRStringArray}, (Ptr{Nothing},), rr)
end

function getNumberOfBoundarySpecies(rr)
  return ccall(dlsym(rrlib, :getNumberOfBoundarySpecies), cdecl, Int64, (Ptr{Nothing},), rr)
end

function getBoundarySpeciesConcentrations(rr)
  return ccall(dlsym(rrlib, :getBoundarySpeciesConcentrations), cdecl, Ptr{RRVector}, (Ptr{Nothing},), rr)
end

function setBoundarySpeciesByIndex(rr::Ptr{Nothing}, index::Int64, value::Float64)
  status = ccall(dlsym(rrlib, :setBoundarySpeciesByIndex), cdecl, Bool, (Ptr{Nothing}, Int64, Float64), rr, index, value)
  if status == false
    error(getLastError())
  end
end

function resetRR(rr)
  return ccall(dlsym(rrlib, :reset), cdecl, Bool, (Ptr{Nothing},), rr)
end

function resetAllRR(rr::Ptr{Nothing})
  return ccall(dlsym(rrlib, :resetAll), cdecl, Bool, (Ptr{Nothing},), rr)
  if status == false
    error(getLastError())
  end
end

function setBoundary(rr::Ptr{Nothing}, sid::String, boundaryCondition::Bool, forceRegen::Bool)
  status = false
  if forceRegen == true
    status = ccall(dlsym(rrlib, :setBoundary), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Bool), rr, sid, boundaryCondition)
  else
    status = ccall(dlsym(rrlib, :setBoundaryNoRegen), cdecl, Bool, (Ptr{Nothing}, Ptr{UInt8}, Bool), rr, sid, boundaryCondition)
  end
  if status == false
    error(getLastError())
  end
end


text:
using Documenter, Phonetics

makedocs(sitename = "Phonetics.jl",
         pages = ["index.md", "vowelplot.md", "acd.md", "lc.md", "textvptree.md"],
         repo = "https://github.com/maetshju/Phonetics.jl")

deploydocs(
repo = "github.com/maetshju/Phonetics.jl.git"
)


text:
export
dsblend,
LP_norm,
radon_linear_robust,
tgenerator
include("dsblend.jl")
include("LP_norm.jl")
include("radon_linear_robust.jl")
include("tgenerator.jl")

max_stars_repo_name: Ji-seismic/SeisTest

max_issues_repo_name: Ji-seismic/SeisTest

max_forks_repo_name: Ji-seismic/SeisTest


text:
#=
StateSpace.jl

    Provides methods for a linear Gaussian State Space model such as filtering
    (Kalman filter), smoothing (Kalman smoother), forecasting, likelihood
    evaluation, and estimation of hyperparameters (Maximum Likelihood,
	Expectation-Maximization (EM), and Expectation-Conditional Maximization
	(ECM), w/ and w/o penalization)

@author: Quint Wiersma <q.wiersma@vu.nl>

@date: 2021/12/06
=#

module StateSpace

using 	LinearAlgebra,
		Statistics,
		Optim,
		ProximalMethods,
		FiniteDifferences,
        MultivariateStats

export
# Structs
	# filters and smoother
	MultivariateFilter,
	WoodburyFilter,
	UnivariateFilter,
	Smoother,
	# system
	LinearTimeInvariant,
	LinearTimeVariant,
	# penalization
	NoPen,
	Lasso,
	GroupLasso,
	SparseGroupLasso,
	# models
	Independent, Idiosyncratic, SpatialErrorModel, SpatialMovingAverageModel,
	NoConstant, Constant, Exogeneous,
	DynamicFactorModel,
    DynamicNelsonSiegelModel,
# State space system
    create_system,
    init_system!,
    fix_system!,
# Filter
	kalman_filter!,
# Smoother
	kalman_smoother!,
	kalman_smoother_cov!,
# Forecast
	forecast, forecast!,
# Log Likelihood
	loglik,
# Estimation
	maximum_likelihood!,
	em!,
	ecm!

# Types
"""
    KalmanFilter

Abstract type for Kalman filters.
"""
abstract type KalmanFilter end

"""
    KalmanSmoother

Abstract type for Kalman smoothers.
"""
abstract type KalmanSmoother end

"""
    StateSpaceModel

Abstract type for state space models.
"""
abstract type StateSpaceModel end

# Include programs
# System
include("system.jl")

# Filters
include("filters/multivariate_filter.jl")
include("filters/univariate_filter.jl")

# Smoother
include("smoother.jl")

# Forecast
include("forecast.jl")

# Log-likelihood
include("loglik.jl")

# Estimation
include("estim/estim.jl")
# ML
include("estim/ml/ml.jl")
# EM
include("estim/em/em.jl")
include("estim/em/mstep.jl")
include("estim/em/estep.jl")

# Models
include("models/state_space.jl")
# error models
include("models/error_model.jl")
# mean models
include("models/mean_model.jl")
# Dynamic factor models
include("models/dynamic_factor_model.jl")
include("models/dynamic_nelson_siegel_model.jl")

end