text:
import Blosc
import CodecZlib
import JSON

abstract type Compressor end
getCompressor(compdict::Dict) = getCompressor(compressortypes[compdict["id"]],compdict)
getCompressor(::Nothing) = NoCompressor()

#Compression when no filter is given
zcompress!(compressed,data,c,::Nothing) = zcompress!(compressed,data,c)
zuncompress!(data,compressed,c,::Nothing) = zuncompress!(data,compressed,c)

#Fallback definition of mutating form of compress and uncompress
function zcompress!(compressed, data, c)
    empty!(compressed)
    append!(compressed,zcompress(data, c))
end
zuncompress!(data, compressed, c) = copyto!(data, zuncompress(compressed, c, eltype(data)))

#Function given a filter stack
function zcompress!(compressed, data, c, f)
    a2 = foldl(f, init=data) do anow, fnow
        zencode(anow,fnow)
    end
    zcompress!(compressed, a2, c)
end

function zuncompress!(data, compressed, c, f)
    data2 = zuncompress(compressed, c, desttype(last(f)))
    a2 = foldr(f, init = data2) do fnow, anow
        zdecode(anow, fnow)
    end
    copyto!(data, a2)
end

struct BloscCompressor <: Compressor
    blocksize::Int
    clevel::Int
    cname::String
    shuffle::Bool
end

"""
    BloscCompressor(;blocksize=0, clevel=5, cname="lz4", shuffle=true)

Returns a `BloscCompressor` struct that can serve as a Zarr array compressor. Keyword arguments are:

* `clevel=5` the compression level, number between 0 (no compression) and 9 (max compression)
* `cname="lz4"` compressor name, can be one of `"blosclz"`, `"lz4"`, and `"lz4hc"`
* `shuffle=true` enables/disables bit-shuffling
"""
BloscCompressor(;blocksize=0, clevel=5, cname="lz4", shuffle=true) =
    BloscCompressor(blocksize, clevel, cname, shuffle)

function getCompressor(::Type{BloscCompressor}, d::Dict)
    BloscCompressor(d["blocksize"], d["clevel"], d["cname"], d["shuffle"] > 0)
end

zuncompress(a, ::BloscCompressor, T) = Blosc.decompress(Base.nonmissingtype(T), a)

function zcompress(a, c::BloscCompressor)
    Blosc.set_compressor(c.cname)
    Blosc.compress(a, level=c.clevel, shuffle=c.shuffle)
end

JSON.lower(c::BloscCompressor) = Dict("id"=>"blosc", "cname"=>c.cname,
    "clevel"=>c.clevel, "shuffle"=>c.shuffle ? 1 : 0, "blocksize"=>c.blocksize)

"""
    NoCompressor()

Creates an object that can be passed to ZArray constructors without compression.
"""
struct NoCompressor <: Compressor end

function zuncompress(a, ::NoCompressor, T)
  reinterpret(T,a)
end

function zcompress(a, ::NoCompressor)
  reinterpret(UInt8,a)
end

JSON.lower(::NoCompressor) = nothing

compressortypes = Dict("blosc"=>BloscCompressor, nothing=>NoCompressor)

"""
    ZlibCompressor(clevel=-1)
Returns a `ZlibCompressor` struct that can serve as a Zarr array compressor. Keyword arguments are:
* `clevel=-1` the compression level, number between -1 (Default), 0 (no compression) and 9 (max compression)
*  default is -1 compromise between speed and compression (currently equivalent to level 6).
"""
struct ZlibCompressor <: Compressor
    clevel::Int
end

ZlibCompressor(;clevel=-1) = ZlibCompressor(clevel)

function getCompressor(::Type{ZlibCompressor}, d::Dict)
    ZlibCompressor(d["level"])
end

function zuncompress(a, ::ZlibCompressor, T)
    result = transcode(CodecZlib.ZlibDecompressor,a)
    reinterpret(Base.nonmissingtype(T),result)
end

function zcompress(a, ::ZlibCompressor)
    a_uint8 = reinterpret(UInt8,a)[:]
    transcode(CodecZlib.ZlibCompressor, a_uint8)
end

JSON.lower(z::ZlibCompressor) = Dict("id"=>"zlib", "level" => z.clevel)

Zarr.compressortypes["zlib"] = ZlibCompressor


text:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Description
#
#   Tests related to general functions.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

@testset "Back-ends" begin
    include("./general/backend.jl")
end

@testset "Configurations" begin
    include("./general/configurations.jl")
end

@testset "Compact types" begin
    include("./general/compact_types.jl")
end

@testset "Errors" begin
    include("./general/errors.jl")
end

@testset "Table to file" begin
    include("./general/files.jl")
end

@testset "Table to string" begin
    include("./general/string.jl")
end

@testset "Tables.jl API" begin
    include("./general/tables.jl")
end

ext: jl


text:
module Latency

using CUDA
using BenchmarkTools

function main()
    results = BenchmarkGroup()

    base_cmd = Base.julia_cmd()
    if Base.JLOptions().project != C_NULL
        base_cmd = `$base_cmd --project=$(unsafe_string(Base.JLOptions().project))`
    end

    # make sure all artifacts are downloaded
    CUDA.version()

    # time to precompile the package and its dependencies
    precompile_cmd =
        `$base_cmd -e "uuid = Base.UUID(\"052768ef-5323-5732-b1bb-66c8b64840ba\")
                    id = Base.PkgId(uuid, \"CUDA\")
                    Base.compilecache(id)"`
    results["precompile"] = @benchmark run($precompile_cmd) evals=1 seconds=60

    # time to actually import the package
    import_cmd =
        `$base_cmd -e "using CUDA"`
    results["import"] = @benchmark run($import_cmd) evals=1 seconds=30

    # time to initialize CUDA and all other libraries
    initialize_time =
        `$base_cmd -e "using CUDA
                    CUDA.version()"`
    results["initialize"] = @benchmark run($initialize_time) evals=1 seconds=30

    # time to actually compile a kernel
    ttfp_cmd =
        `$base_cmd -e "using CUDA
                    kernel() = return
                    CUDA.code_ptx(devnull, kernel, Tuple{}; kernel=true)"`
    results["ttfp"] = @benchmark run($ttfp_cmd) evals=1 seconds=60

    results
end

end

Latency.main()


text:
module TemplateMatching

using StatsBase
using LinearAlgebra
using OffsetArrays
using Interpolations
using Optim

export crosscorrelate, maxfilter, stack, correlatetemplate, findpeaks,
       magnitude, findmax_window, subsampleshift, estimatetoa, residue_rms,
       locate

include("crosscorrelation.jl")
include("processing.jl")
include("utils.jl")

end


text:
import Base.sign
export partialtranspose, PartialTransposeAtom
export sign, curvature, monotonicity, evaluate, conic_form!

struct PartialTransposeAtom <: AbstractExpr
    head::Symbol
    id_hash::UInt64
    children::Tuple{AbstractExpr}
    size::Tuple{Int, Int}
    sys::Int
    dims::Vector

    function PartialTransposeAtom(x::AbstractExpr, sys::Int, dims::Vector)
        if x.size[1] ≠ x.size[2]
            throw(ArgumentError("Only square matrices are supported"))
        end
        if ! (1 ≤ sys ≤ length(dims))
            throw(ArgumentError("Invalid system, should between 1 and ", length(dims), "; got ", sys))
        end
        if x.size[1] ≠ prod(dims)
            throw(ArgumentError("Dimension of system doesn't correspond to dimension of subsystems"))
        end
        children = (x, )
        return new(:partialtranspose, hash(children), children, x.size, sys, dims)
    end
end

function sign(x::PartialTransposeAtom)
    return sign(x.children[1])
end

function curvature(x::PartialTransposeAtom)
    return ConstVexity()
end

function monotonicity(x::PartialTransposeAtom)
    return (Nondecreasing(),)
end

function evaluate(x::PartialTransposeAtom)
    return partialtranspose( evaluate( x.children[1] ))
end

"""
    partialtranspose(x, sys::Int, dims::Vector)

Returns the partial transpose of `x` over the `sys`th system, where `dims` is a vector of integers encoding the dimensions of each subsystem.
"""
function partialtranspose(x::AbstractMatrix, sys::Int, dims::Vector)
    if size(x,1) ≠ size(x,2)
            throw(ArgumentError("Only square matrices are supported"))
    end
    if ! (1 ≤ sys ≤ length(dims))
            throw(ArgumentError("Invalid system, should between 1 and $(length(dims)); got $sys"))
    end
    if size(x,1) ≠ prod(dims)
            throw(ArgumentError("Dimension of system doesn't correspond to dimension of subsystems"))
    end
    n = length(dims)
    d = prod(dims)
    s = n - sys + 1
    p = collect(1:2n)
    p[s] = n + s
    p[n + s] = s

    rdims = reverse(dims)
    r = reshape(x, (rdims..., rdims...))
    return reshape(permutedims(r,p),(d,d))
end

"""
    permutedims_matrix(dims, p)
Returns a matrix `M` so that for any vector `v` of length `prod(dims)`,
    M*v == vec(permutedims(reshape(v, dims), p))
"""
function permutedims_matrix(dims, p)
    d = prod(dims)
    n = length(dims)
    sparse(reshape(PermutedDimsArray(reshape(Matrix(I,d,d), (dims..., dims...)), (p..., (n + 1:2n)...)), (d, d)))
end

# borrowing this from transpose.jl:
# Since everything is vectorized, we simply need to multiply x by a permutation
# matrix such that coeff * vectorized(x) - vectorized(x') = 0
function conic_form!(x::PartialTransposeAtom, unique_conic_forms::UniqueConicForms)
    if !has_conic_form(unique_conic_forms, x)
        objective = conic_form!(x.children[1], unique_conic_forms)

        n = length(x.dims)
        d = prod(x.dims)
        s = n - x.sys + 1
        p = collect(1:2n)
        p[s] = n + s
        p[n + s] = s

        rdims = reverse(x.dims)

        partialtranspose_matrix = permutedims_matrix((rdims...,rdims...),p)

        objective = partialtranspose_matrix * objective
        cache_conic_form!(unique_conic_forms, x, objective)
    end
    return get_conic_form(unique_conic_forms, x)
end

partialtranspose(x::AbstractExpr,sys::Int, dim::Vector) = PartialTransposeAtom(x,sys,dim)


text:
module RulesBIFMInTest

using Test
using ReactiveMP
using Random
import ReactiveMP: @test_rules

@testset "rules:BIFM:in" begin

     @testset "Belief Propagation: (m_out::MultivariateNormalDistributionsFamily, m_zprev::ProdFinal{<:MultivariateNormalDistributionsFamily}, m_znext::MultivariateNormalDistributionsFamily, meta::BIFMMeta)" begin

        meta = BIFMMeta([2 0; 0 1], # A
                        [3 0; 0 2], # B
                        [4 0; 0 3], # C
                        [5 0; 0 4], # H
                        [6 0; 0 5], # BHBt
                        [1, 2],     # ξz
                        [7 0; 0 6], # Λz
                        [2, 3],     # ξztilde
                        [8 0; 0 7], # Λztilde
                        [3, 4],     # μu
                        [9 0; 0 8]  # Σu
                        )

        @test_rules [ with_float_conversions = true, float32_atol = 1e-2, bigfloat_atol = 1e-8 ] BIFM(:in, Marginalisation) [
            (input = (m_out = MvNormalMeanPrecision([1,2], [2 0; 0 1]),     m_zprev = ProdFinal(MvNormalMeanPrecision([1,2], [1 0; 0 2])), m_znext = MvNormalMeanPrecision([1,2], [1 0; 0 2]), meta = meta),
                output = ProdFinal(MvNormalMeanCovariance([-375, -172], [180801 0.0; 0.0 4487.999999999998]))),
            (input = (m_out = MvNormalMeanPrecision([3,4], [6 0; 0 1]),     m_zprev = ProdFinal(MvNormalMeanPrecision([1,6], [2 0; 0 2])), m_znext = MvNormalMeanPrecision([8,2], [2 0; 0 2]), meta = meta),
                output = ProdFinal(MvNormalMeanCovariance([-375, -620], [87488.99999999997 0.0; 0.0 4487.999999999998]))),
            (input = (m_out = MvNormalMeanPrecision([5,6], [2 0; 0 5]),     m_zprev = ProdFinal(MvNormalMeanPrecision([6,2], [1 0; 0 1])), m_znext = MvNormalMeanPrecision([1,9], [1 0; 0 1]), meta = meta),
                output = ProdFinal(MvNormalMeanCovariance([-2535, -172], [180801 0.0; 0.0 10760.0])))
        ]

    end

end

end


text:
export
    PrimalsMT

# For Minimum Time DIRCOL
function PartedArrays.create_partition(n::Int,m::Int,q::Int,N::Int,uN::Int,hN::Int)
    @assert hN <= uN
    @assert uN <= N
    Nx = N*n
    Nu = uN*m
    Nh = hN*q
    Nz = Nx+Nu+Nh
    ind_x = zeros(Int,n,N)
    ind_u = zeros(Int,m,uN)
    ind_h = zeros(Int,q,hN)
    ix = 1:n
    iu = n .+ (1:m)
    ih = (n+m) .+ (1:q)
    for k = 1:uN
        ind_x[:,k] = ix .+ (k-1)*(n+m+q)
        ind_u[:,k] = iu .+ (k-1)*(n+m+q)
        if k <= hN
            ind_h[:,k] = ih .+ (k-1)*(n+m+q)
        end
    end
    if uN == N-1
        ind_x[:,N] = ix .+ (N-1)*(n+m+q)
    end
    return (X=ind_x, U=ind_u, H=ind_h)
end

struct PrimalsMT{T<:Real}
    Z::Vector{T}
    X::Vector{SubArray{T,1,Vector{T},Tuple{Vector{Int}},false}}
    U::Vector{SubArray{T,1,Vector{T},Tuple{Vector{Int}},false}}
    H
    equal::Bool
end

function PrimalsMT(Z,part_z::NamedTuple)
    N, uN, hN = size(part_z.X,2), size(part_z.U,2), size(part_z.H,2)
    X = [view(Z,part_z.X[:,k]) for k = 1:N]
    U = [view(Z,part_z.U[:,k]) for k = 1:uN]
    H = [view(Z,part_z.H[:,k])[1] for k = 1:hN]

    PrimalsMT(Z,X,U,H, N==uN)
end

"""Create a Primals from vectors of SubArrays.
This is the fastest method to convert a vector Z to subarrays X,U. This will overwrite X and U!
"""
function PrimalsMT(Z::Vector{T},X::Vector{S},U::Vector{S}, H::Vector{T}) where {T,S<:SubArray}
    N = length(X)
    uN = length(U)
    hN = length(H)
    for k = 1:uN
        X[k] = view(Z,X[k].indices[1])
        U[k] = view(Z,U[k].indices[1])
        if k <= hN
            H[k] = view(Z,H[k].indices[1])[1]
        end
    end
    if uN == N-1
        X[N] = view(Z,X[N].indices)
    end
    PrimalsMT(Z,X,U,H, N==uN)
end

function PrimalsMT(Z::Vector{T},Z0::Primals{T}) where T
    X = deepcopy(Z0.X)
    U = deepcopy(Z0.U)
    H = deepcopy(Z0.H)
    uN = length(U)
    hN = length(H)
    N = length(X)
    for k = 1:uN
        X[k] = view(Z,X[k].indices[1])
        U[k] = view(Z,U[k].indices[1])
        if k <= hN
            H[k] = view(Z,H[k].indices[1])[1]
        end
    end
    if uN == N-1
        X[N] = view(Z,X[N].indices)
    end
    PrimalsMT(Z,X,U,H, Z0.equal)
end

""" $(TYPEDSIGNATURES)
Combine state and control trajectories.
This is a little slow and less memory efficient than converting from a the combined vector to individual trajectories.
"""
function PrimalsMT(X::VectorTrajectory{T}, U::VectorTrajectory{T}, H::Vector{T}) where T
    N,uN,hN = length(X), length(U), length(H)
    n,m = length(X[1]), length(U[1])
    NN = N*n + uN*m + hN
    Z = zeros(T,NN)
    part_z = create_partition(n,m,1,N,uN,hN)
    Z[part_z.X] = to_array(X)
    Z[part_z.U] = to_array(U)
    Z[part_z.H] = to_array(H)

    PrimalsMT(Z,part_z)
end

function PrimalsMT(prob::Problem{T}, equal::Bool=false) where T
    U = copy(prob.U)
    if equal
        U = push!(U, U[end])
    end
    PrimalsMT(prob.X, U, get_dt_traj(prob))
end

function packMT(prob::Problem{T}) where T
    n,m,N = size(prob)
    part_z = create_partition(n,m,1,N,N,N-1)
    NN = N*(n+m) + (N-1)
    Z = PartedVector(zeros(T,NN),part_z)
    copyto!(Z.X, prob.X)
    copyto!(Z.U, prob.U)
    copyto!(Z.H, get_dt_traj(prob))
    return Z
end

function unpackMT(Z::Vector{<:Real}, part_z::NamedTuple)
    N, uN, hN = size(part_z.X,2), size(part_z.U,2), size(part_z.H,2)
    X = [view(Z,part_z.X[:,k]) for k = 1:N]
    U = [view(Z,part_z.U[:,k]) for k = 1:uN]
    H = [view(Z,part_z.H[:,k])[1] for k = 1:hN]

    return X, U, H
end

function packMT(X,U,H, part_z)
    n,m = length(X[1]), length(U[1])
    N, uN, hN = length(X), length(U), length(H)
    Z = zeros(eltype(X[1]), N*n + uN*m + hN)
    for k = 1:N
        Z[part_z.X[:,k]] = X[k]
        Z[part_z.U[:,k]] = U[k]
        if k <= hN
            Z[part_z.H[:,k]] = H[k]
        end
    end
    return Z
end

function packMT(X,U,H)
    n = length(X[1])
    m = length(U[1])
    N = length(X)
    uN = length(U)
    hN = length(H)
    part_z = create_partition(n,m,1,N,uN,hN)
    Z = packMT(X,U,H,part_z)
end

max_issues_repo_name: MehrdadZareian/GMARA

max_forks_repo_name: MehrdadZareian/GMARA


text:
module Day12

using DataStructures: counter

export day12

TESTINPUT = """start-A
start-b
A-c
A-b
b-d
A-end
b-end"""

TESTINPUT2 = """dc-end
HN-start
start-kj
dc-start
dc-HN
LN-dc
HN-end
kj-sa
kj-HN
kj-dc"""

TESTINPUT3 = """fs-end
he-DX
fs-he
start-DX
pj-DX
end-zg
zg-sl
zg-pj
pj-he
RW-he
fs-DX
pj-RW
zg-RW
start-pj
he-WI
zg-he
pj-fs
start-RW"""

function readInput(inputfile="inputs/input12.txt")
    edges = Dict{String,Set{String}}()
    for line in eachline(inputfile)
        a,b = split(line,"-")
        b != "start" && (edges[a] = push!(get(edges, a, Set{String}()), b))
        a != "start" && (edges[b] = push!(get(edges, b, Set{String}()), a))
    end
    #delete!(edges, "end")
    smallcavemap = _replace_big_caves(edges)
    return Dict([a=>counter(b) for (a,b) in smallcavemap]) # reduce edges by counting
end

isbigcave(cavename) = all(isuppercase, cavename)

function _replace_big_caves(cavegraph)
    newgraph = Dict{String,Vector{String}}()
    addedge(a,b) = b != "start" && (newgraph[a] = push!(get(newgraph, a, Vector{String}()), b))
    for cave in keys(cavegraph)
        if !isbigcave(cave)
            # small cave
            for b in cavegraph[cave]
                if isbigcave(b)
                    for c in cavegraph[b]
                        addedge(cave, c)
                    end
                else
                    addedge(cave, b)
                end
            end
        end
    end
    return newgraph
end

function day12(cavegraph = readInput("inputs/input12.txt"))
    return (day12Part1(cavegraph), day12Part2(cavegraph))
end

function day12Part1(cavegraph)
    _walk(cavegraph, "start", true)
end

## mutating version 2: edges have multiplicities ~ 30x faster
function _walk(cavegraph, at, visited_twice=false, seen=Vector{String}())
    at == "end" && return 1
    addToSeen = !in(at, seen)
    addToSeen && push!(seen, at) # only remember lowercase nodes
    adjacent = cavegraph[at]

    paths = 0
    for (adj, count) in adjacent
        if adj in seen
            visited_twice && continue
            paths += count * _walk(cavegraph, adj, true, seen)
        else
            paths += count * _walk(cavegraph, adj, visited_twice, seen)
        end
    end
    # addToSeen && delete!(seen, at)
    addToSeen && pop!(seen)
    return paths
end

######## prior versions ########

## mutating version ~ 4x faster then non-mutating but a bit more complex
## also switch to Vector from Set - for these small problem sizes the overhead of the set is not worth it
function _walk2(cavegraph, at, visited_twice=false, seen=Vector{String}())
    at == "end" && return 1
    addToSeen = !(in(at, seen) || isbigcave(at))
    addToSeen && push!(seen, at) # only remember lowercase nodes
    adjacent = cavegraph[at]

    paths = 0
    for adj in adjacent
        if adj in seen
            visited_twice && continue
            paths += _walk(cavegraph, adj, true, seen)
        else
            paths += _walk(cavegraph, adj, visited_twice, seen)
        end
    end
    # addToSeen && delete!(seen, at)
    addToSeen && pop!(seen)
    return paths
end

## non mutating version
function _walk1(cavegraph, at, visited_twice=false, seen=Set{String}())
    at == "end" && return 1
    isbigcave(at) || (seen = union(seen, Ref(at))) # only remember lowercase nodes
    adjacent = cavegraph[at]

    paths = 0
    for adj in adjacent
        if adj in seen
            visited_twice && continue
            paths += _walk(cavegraph, adj, true, seen)
        else
            paths += _walk(cavegraph, adj, visited_twice, seen)
        end
    end
    return paths
end

function day12Part2(cavegraph)
    _walk(cavegraph, "start", false)
end

end #module


text:
function readPassports(lines)
    passports = Dict{AbstractString, AbstractString}[]
    item = Dict{AbstractString, AbstractString}()
    for line in lines
        if isempty(line)
            push!(passports, item)
            item = Dict{AbstractString, AbstractString}()
        else
            keys = Dict(map(x -> split(x, ":"), split(line)))
            merge!(item, keys)
        end
    end
    push!(passports, item)
    passports
end

function count_valid_passports(passports)
    function valid_year(str, lower_bound, upper_bound)
        year = tryparse(Int64, str)
        length(str) == 4 && year !==nothing && lower_bound <= year <= upper_bound
    end

    valid_byr(str) = valid_year(str, 1920, 2002)

    valid_iyr(str) = valid_year(str, 2010, 2020)

    valid_eyr(str) = valid_year(str, 2020, 2030)

    valid_pid(str) = length(str) == 9 && tryparse(Int64, str) !== nothing

    valid_ecl(str) = str in Set(["amb", "blu", "brn", "gry", "grn", "hzl", "oth"])

    valid_hcl(str) = startswith(str, "#") && tryparse(Int64, str[2:end], base = 16) !== nothing

    function valid_hgt(str)
        if endswith(str, "in")
            n = tryparse(Int64, str[1:end-2])
            n !== nothing && 59 <= n <= 76
        elseif endswith(str, "cm")
            n = tryparse(Int64, str[1:end-2])
            n !== nothing && 150 <= n <= 193
        else
            false
        end
    end

    validators = Dict("byr" => valid_byr, "iyr" => valid_iyr, "eyr" => valid_eyr, "hgt" => valid_hgt,
                      "hcl" => valid_hcl, "ecl" => valid_ecl, "pid" => valid_pid)
    cnt = 0
    for passport in passports
        if keys(validators) ⊆ keys(passport) && all(is_valid(passport[k]) for (k, is_valid) in pairs(validators))
            cnt += 1
        end
    end
    cnt
end

function main()
    lines = readlines("../resources/input_04.txt")
    passports = readPassports(lines)
    result = count_valid_passports(passports)
    println(result)
end

main()


text:
# Automatically generated using Clang.jl

const XPRS_PLUSINFINITY = 1.0e20
const XPRS_MINUSINFINITY = -1.0e20
const XPRS_MAXINT = 2147483647
const XPVERSION = 29
const XPRS_MPSRHSNAME = 6001
const XPRS_MPSOBJNAME = 6002
const XPRS_MPSRANGENAME = 6003
const XPRS_MPSBOUNDNAME = 6004
const XPRS_OUTPUTMASK = 6005
const XPRS_MATRIXTOL = 7001
const XPRS_PIVOTTOL = 7002
const XPRS_FEASTOL = 7003
const XPRS_OUTPUTTOL = 7004
const XPRS_SOSREFTOL = 7005
const XPRS_OPTIMALITYTOL = 7006
const XPRS_ETATOL = 7007
const XPRS_RELPIVOTTOL = 7008
const XPRS_MIPTOL = 7009
const XPRS_MIPTOLTARGET = 7010
const XPRS_MIPADDCUTOFF = 7012
const XPRS_MIPABSCUTOFF = 7013
const XPRS_MIPRELCUTOFF = 7014
const XPRS_PSEUDOCOST = 7015
const XPRS_PENALTY = 7016
const XPRS_BIGM = 7018
const XPRS_MIPABSSTOP = 7019
const XPRS_MIPRELSTOP = 7020
const XPRS_CROSSOVERACCURACYTOL = 7023
const XPRS_BAROBJSCALE = 7026
const XPRS_BARRHSSCALE = 7027
const XPRS_CHOLESKYTOL = 7032
const XPRS_BARGAPSTOP = 7033
const XPRS_BARDUALSTOP = 7034
const XPRS_BARPRIMALSTOP = 7035
const XPRS_BARSTEPSTOP = 7036
const XPRS_ELIMTOL = 7042
const XPRS_PERTURB = 7044
const XPRS_MARKOWITZTOL = 7047
const XPRS_MIPABSGAPNOTIFY = 7064
const XPRS_MIPRELGAPNOTIFY = 7065
const XPRS_PPFACTOR = 7069
const XPRS_REPAIRINDEFINITEQMAX = 7071
const XPRS_BARGAPTARGET = 7073
const XPRS_SBEFFORT = 7086
const XPRS_HEURDIVERANDOMIZE = 7089
const XPRS_HEURSEARCHEFFORT = 7090
const XPRS_CUTFACTOR = 7091
const XPRS_EIGENVALUETOL = 7097
const XPRS_INDLINBIGM = 7099
const XPRS_TREEMEMORYSAVINGTARGET = 7100
const XPRS_GLOBALFILEBIAS = 7101
const XPRS_INDPRELINBIGM = 7102
const XPRS_RELAXTREEMEMORYLIMIT = 7105
const XPRS_MIPABSGAPNOTIFYOBJ = 7108
const XPRS_MIPABSGAPNOTIFYBOUND = 7109
const XPRS_PRESOLVEMAXGROW = 7110
const XPRS_HEURSEARCHTARGETSIZE = 7112
const XPRS_CROSSOVERRELPIVOTTOL = 7113
const XPRS_CROSSOVERRELPIVOTTOLSAFE = 7114
const XPRS_DETLOGFREQ = 7116
const XPRS_MAXIMPLIEDBOUND = 7120
const XPRS_FEASTOLTARGET = 7121
const XPRS_OPTIMALITYTOLTARGET = 7122
const XPRS_PRECOMPONENTSEFFORT = 7124
const XPRS_EXTRAROWS = 8004
const XPRS_EXTRACOLS = 8005
const XPRS_LPITERLIMIT = 8007
const XPRS_LPLOG = 8009
const XPRS_SCALING = 8010
const XPRS_PRESOLVE = 8011
const XPRS_CRASH = 8012
const XPRS_PRICINGALG = 8013
const XPRS_INVERTFREQ = 8014
const XPRS_INVERTMIN = 8015
const XPRS_MAXNODE = 8018
const XPRS_MAXTIME = 8020
const XPRS_MAXMIPSOL = 8021
const XPRS_DEFAULTALG = 8023
const XPRS_VARSELECTION = 8025
const XPRS_NODESELECTION = 8026
const XPRS_BACKTRACK = 8027
const XPRS_MIPLOG = 8028
const XPRS_KEEPNROWS = 8030
const XPRS_MPSECHO = 8032
const XPRS_MAXPAGELINES = 8034
const XPRS_OUTPUTLOG = 8035
const XPRS_BARSOLUTION = 8038
const XPRS_CACHESIZE = 8043
const XPRS_CROSSOVER = 8044
const XPRS_BARITERLIMIT = 8045
const XPRS_CHOLESKYALG = 8046
const XPRS_BAROUTPUT = 8047
const XPRS_CSTYLE = 8050
const XPRS_EXTRAMIPENTS = 8051
const XPRS_REFACTOR = 8052
const XPRS_BARTHREADS = 8053
const XPRS_KEEPBASIS = 8054
const XPRS_VERSION = 8061
const XPRS_BIGMMETHOD = 8068
const XPRS_MPSNAMELENGTH = 8071
const XPRS_PRESOLVEOPS = 8077
const XPRS_MIPPRESOLVE = 8078
const XPRS_MIPTHREADS = 8079
const XPRS_BARORDER = 8080
const XPRS_BREADTHFIRST = 8082
const XPRS_AUTOPERTURB = 8084
const XPRS_DENSECOLLIMIT = 8086
const XPRS_CALLBACKFROMMASTERTHREAD = 8090
const XPRS_MAXMCOEFFBUFFERELEMS = 8091
const XPRS_REFINEOPS = 8093
const XPRS_LPREFINEITERLIMIT = 8094
const XPRS_MIPREFINEITERLIMIT = 8095
const XPRS_DUALIZEOPS = 8097
const XPRS_PRESORT = 8107
const XPRS_PREPERMUTE = 8108
const XPRS_PREPERMUTESEED = 8109
const XPRS_MAXMEMORY = 8112
const XPRS_CUTFREQ = 8116
const XPRS_SYMSELECT = 8117
const XPRS_SYMMETRY = 8118
const XPRS_LPTHREADS = 8124
const XPRS_MIQCPALG = 8125
const XPRS_QCCUTS = 8126
const XPRS_QCROOTALG = 8127
const XPRS_ALGAFTERNETWORK = 8129
const XPRS_TRACE = 8130
const XPRS_MAXIIS = 8131
const XPRS_CPUTIME = 8133
const XPRS_COVERCUTS = 8134
const XPRS_GOMCUTS = 8135
const XPRS_MPSFORMAT = 8137
const XPRS_CUTSTRATEGY = 8138
const XPRS_CUTDEPTH = 8139
const XPRS_TREECOVERCUTS = 8140
const XPRS_TREEGOMCUTS = 8141
const XPRS_CUTSELECT = 8142
const XPRS_TREECUTSELECT = 8143
const XPRS_DUALIZE = 8144
const XPRS_DUALGRADIENT = 8145
const XPRS_SBITERLIMIT = 8146
const XPRS_SBBEST = 8147
const XPRS_MAXCUTTIME = 8149
const XPRS_ACTIVESET = 8152
const XPRS_BARINDEFLIMIT = 8153
const XPRS_HEURSTRATEGY = 8154
const XPRS_HEURFREQ = 8155
const XPRS_HEURDEPTH = 8156
const XPRS_HEURMAXSOL = 8157
const XPRS_HEURNODES = 8158
const XPRS_LNPBEST = 8160
const XPRS_LNPITERLIMIT = 8161
const XPRS_BRANCHCHOICE = 8162
const XPRS_BARREGULARIZE = 8163
const XPRS_SBSELECT = 8164
const XPRS_LOCALCHOICE = 8170
const XPRS_LOCALBACKTRACK = 8171
const XPRS_DUALSTRATEGY = 8174
const XPRS_L1CACHE = 8175
const XPRS_HEURDIVESTRATEGY = 8177
const XPRS_HEURSELECT = 8178
const XPRS_BARSTART = 8180
const XPRS_BARNUMSTABILITY = 8186
const XPRS_BARORDERTHREADS = 8187
const XPRS_EXTRASETS = 8190
const XPRS_FEASIBILITYPUMP = 8193
const XPRS_PRECOEFELIM = 8194
const XPRS_PREDOMCOL = 8195
const XPRS_HEURSEARCHFREQ = 8196
const XPRS_HEURDIVESPEEDUP = 8197
const XPRS_SBESTIMATE = 8198
const XPRS_BARCORES = 8202
const XPRS_MAXCHECKSONMAXTIME = 8203
const XPRS_MAXCHECKSONMAXCUTTIME = 8204
const XPRS_HISTORYCOSTS = 8206
const XPRS_ALGAFTERCROSSOVER = 8208
const XPRS_LINELENGTH = 8209
const XPRS_MUTEXCALLBACKS = 8210
const XPRS_BARCRASH = 8211
const XPRS_HEURDIVESOFTROUNDING = 8215
const XPRS_HEURSEARCHROOTSELECT = 8216
const XPRS_HEURSEARCHTREESELECT = 8217
const XPRS_MPS18COMPATIBLE = 8223
const XPRS_ROOTPRESOLVE = 8224
const XPRS_CROSSOVERDRP = 8227
const XPRS_FORCEOUTPUT = 8229
const XPRS_DETERMINISTIC = 8232
const XPRS_PREPROBING = 8238
const XPRS_EXTRAQCELEMENTS = 8240
const XPRS_EXTRAQCROWS = 8241
const XPRS_TREEMEMORYLIMIT = 8242
const XPRS_TREECOMPRESSION = 8243
const XPRS_TREEDIAGNOSTICS = 8244
const XPRS_MAXGLOBALFILESIZE = 8245
const XPRS_TEMPBOUNDS = 8250
const XPRS_IFCHECKCONVEXITY = 8251
const XPRS_PRIMALUNSHIFT = 8252
const XPRS_REPAIRINDEFINITEQ = 8254
const XPRS_MAXLOCALBACKTRACK = 8257
const XPRS_USERSOLHEURISTIC = 8258
const XPRS_FORCEPARALLELDUAL = 8265
const XPRS_BACKTRACKTIE = 8266
const XPRS_BRANCHDISJ = 8267
const XPRS_MIPFRACREDUCE = 8270
const XPRS_CONCURRENTTHREADS = 8274
const XPRS_MAXSCALEFACTOR = 8275
const XPRS_HEURTHREADS = 8276
const XPRS_THREADS = 8278
const XPRS_HEURBEFORELP = 8280
const XPRS_PREDOMROW = 8281
const XPRS_BRANCHSTRUCTURAL = 8282
const XPRS_QUADRATICUNSHIFT = 8284
const XPRS_BARPRESOLVEOPS = 8286
const XPRS_QSIMPLEXOPS = 8288
const XPRS_CONFLICTCUTS = 8292
const XPRS_PREPROTECTDUAL = 8293
const XPRS_CORESPERCPU = 8296
const XPRS_SLEEPONTHREADWAIT = 8302
const XPRS_PREDUPROW = 8307
const XPRS_CPUPLATFORM = 8312
const XPRS_BARALG = 8315
const XPRS_TREEPRESOLVE = 8320
const XPRS_TREEPRESOLVE_KEEPBASIS = 8321
const XPRS_TREEPRESOLVEOPS = 8322
const XPRS_LPLOGSTYLE = 8326
const XPRS_RANDOMSEED = 8328
const XPRS_TREEQCCUTS = 8331
const XPRS_PRELINDEP = 8333
const XPRS_DUALTHREADS = 8334
const XPRS_PREOBJCUTDETECT = 8336
const XPRS_PREBNDREDQUAD = 8337
const XPRS_PREBNDREDCONE = 8338
const XPRS_PRECOMPONENTS = 8339
const XPRS_MAXMIPTASKS = 8347
const XPRS_MIPTERMINATIONMETHOD = 8348
const XPRS_PRECONEDECOMP = 8349
const XPRS_HEURSEARCHROOTCUTFREQ = 8351
const XPRS_EXTRAELEMS = 8006
const XPRS_EXTRAPRESOLVE = 8037
const XPRS_EXTRASETELEMS = 8191
const XPRS_MATRIXNAME = 3001
const XPRS_BOUNDNAME = 3002
const XPRS_OBJNAME = 3003
const XPRS_RHSNAME = 3004
const XPRS_RANGENAME = 3005
const XPRS_LPOBJVAL = 2001
const XPRS_SUMPRIMALINF = 2002
const XPRS_MIPOBJVAL = 2003
const XPRS_BESTBOUND = 2004
const XPRS_OBJRHS = 2005
const XPRS_MIPBESTOBJVAL = 2006
const XPRS_OBJSENSE = 2008
const XPRS_BRANCHVALUE = 2009
const XPRS_PENALTYVALUE = 2061
const XPRS_CURRMIPCUTOFF = 2062
const XPRS_BARCONDA = 2063
const XPRS_BARCONDD = 2064
const XPRS_MAXABSPRIMALINFEAS = 2073
const XPRS_MAXRELPRIMALINFEAS = 2074
const XPRS_MAXABSDUALINFEAS = 2075
const XPRS_MAXRELDUALINFEAS = 2076
const XPRS_PRIMALDUALINTEGRAL = 2079
const XPRS_BARPRIMALOBJ = 4001
const XPRS_BARDUALOBJ = 4002
const XPRS_BARPRIMALINF = 4003
const XPRS_BARDUALINF = 4004
const XPRS_BARCGAP = 4005
const XPRS_ROWS = 1001
const XPRS_SETS = 1004
const XPRS_PRIMALINFEAS = 1007
const XPRS_DUALINFEAS = 1008
const XPRS_SIMPLEXITER = 1009
const XPRS_LPSTATUS = 1010
const XPRS_MIPSTATUS = 1011
const XPRS_CUTS = 1012
const XPRS_NODES = 1013
const XPRS_NODEDEPTH = 1014
const XPRS_ACTIVENODES = 1015
const XPRS_MIPSOLNODE = 1016
const XPRS_MIPSOLS = 1017
const XPRS_COLS = 1018
const XPRS_SPAREROWS = 1019
const XPRS_SPARECOLS = 1020
const XPRS_SPAREMIPENTS = 1022
const XPRS_ERRORCODE = 1023
const XPRS_MIPINFEAS = 1024
const XPRS_PRESOLVESTATE = 1026
const XPRS_PARENTNODE = 1027
const XPRS_NAMELENGTH = 1028
const XPRS_QELEMS = 1030
const XPRS_NUMIIS = 1031
const XPRS_MIPENTS = 1032
const XPRS_BRANCHVAR = 1036
const XPRS_MIPTHREADID = 1037
const XPRS_ALGORITHM = 1049
const XPRS_TIME = 1122
const XPRS_ORIGINALROWS = 1124
const XPRS_CALLBACKCOUNT_OPTNODE = 1136
const XPRS_CALLBACKCOUNT_CUTMGR = 1137
const XPRS_ORIGINALQELEMS = 1157
const XPRS_MAXPROBNAMELENGTH = 1158
const XPRS_STOPSTATUS = 1179
const XPRS_ORIGINALMIPENTS = 1191
const XPRS_ORIGINALSETS = 1194
const XPRS_SPARESETS = 1203
const XPRS_CHECKSONMAXTIME = 1208
const XPRS_CHECKSONMAXCUTTIME = 1209
const XPRS_ORIGINALCOLS = 1214
const XPRS_QCELEMS = 1232
const XPRS_QCONSTRAINTS = 1234
const XPRS_ORIGINALQCELEMS = 1237
const XPRS_ORIGINALQCONSTRAINTS = 1239
const XPRS_PEAKTOTALTREEMEMORYUSAGE = 1240
const XPRS_CURRENTNODE = 1248
const XPRS_TREEMEMORYUSAGE = 1251
const XPRS_GLOBALFILESIZE = 1252
const XPRS_GLOBALFILEUSAGE = 1253
const XPRS_INDICATORS = 1254
const XPRS_ORIGINALINDICATORS = 1255
const XPRS_CORESDETECTED = 1260
const XPRS_BARSING = 1281
const XPRS_BARSINGR = 1282
const XPRS_PRESOLVEINDEX = 1284
const XPRS_CONES = 1307
const XPRS_CONEELEMS = 1308
const XPRS_BARITER = 5001
const XPRS_BARAASIZE = 5002
const XPRS_BARLSIZE = 5003
const XPRS_BARDENSECOL = 5004
const XPRS_BARCROSSOVER = 5005
const XPRS_IIS = XPRS_NUMIIS
const XPRS_SETMEMBERS = 1005
const XPRS_ELEMS = 1006
const XPRS_SPAREELEMS = 1021
const XPRS_ORIGINALSETMEMBERS = 1195
const XPRS_SPARESETELEMS = 1204
const XPRS_MSP_DEFAULTUSERSOLFEASTOL = 6209
const XPRS_MSP_DEFAULTUSERSOLMIPTOL = 6210
const XPRS_MSP_SOL_FEASTOL = 6402
const XPRS_MSP_SOL_MIPTOL = 6403
const XPRS_MSP_DUPLICATESOLUTIONSPOLICY = 6203
const XPRS_MSP_INCLUDEPROBNAMEINLOGGING = 6211
const XPRS_MSP_WRITESLXSOLLOGGING = 6212
const XPRS_MSP_ENABLESLACKSTORAGE = 6213
const XPRS_MSP_OUTPUTLOG = 6214
const XPRS_MSP_SOL_BITFIELDSUSR = 6406
const XPRS_MSP_SOLPRB_OBJ = 6500
const XPRS_MSP_SOLPRB_INFSUM_PRIMAL = 6502
const XPRS_MSP_SOLPRB_INFSUM_MIP = 6504
const XPRS_MSP_SOLUTIONS = 6208
const XPRS_MSP_PRB_VALIDSOLS = 6300
const XPRS_MSP_PRB_FEASIBLESOLS = 6301
const XPRS_MSP_SOL_COLS = 6400
const XPRS_MSP_SOL_NONZEROS = 6401
const XPRS_MSP_SOL_ISUSERSOLUTION = 6404
const XPRS_MSP_SOL_ISREPROCESSEDUSERSOLUTION = 6405
const XPRS_MSP_SOL_BITFIELDSSYS = 6407
const XPRS_MSP_SOLPRB_INFEASCOUNT = 6501
const XPRS_MSP_SOLPRB_INFCNT_PRIMAL = 6503
const XPRS_MSP_SOLPRB_INFCNT_MIP = 6505
const XPRS_MSE_OUTPUTTOL = 6609
const XPRS_MSE_CALLBACKCULLSOLS_MIPOBJECT = 6601
const XPRS_MSE_CALLBACKCULLSOLS_DIVERSITY = 6602
const XPRS_MSE_CALLBACKCULLSOLS_MODOBJECT = 6603
const XPRS_MSE_OPTIMIZEDIVERSITY = 6607
const XPRS_MSE_OUTPUTLOG = 6610
const XPRS_MSE_DIVERSITYSUM = 6608
const XPRS_MSE_SOLUTIONS = 6600
const XPRS_MSE_METRIC_MIPOBJECT = 6604
const XPRS_MSE_METRIC_DIVERSITY = 6605
const XPRS_MSE_METRIC_MODOBJECT = 6606
const XPRS_PTB_PERMUTE_INTENSITY_ROW = 6702
const XPRS_PTB_PERMUTE_INTENSITY_COL = 6703
const XPRS_PTB_SHIFTSCALE_COLS_INTENSITY = 6722
const XPRS_PTB_SHIFTSCALE_COLS_MAXRANGEFORCOMPLEMENTING = 6729
const XPRS_PTB_SHIFTSCALE_ROWS_INTENSITY = 6762
const XPRS_PTB_PERMUTE_ACTIVE = 6700
const XPRS_PTB_PERMUTE_SEEDLAST = 6701
const XPRS_PTB_PERTURB_COST2_ACTIVE = 6710
const XPRS_PTB_PERTURB_COST2_SEEDLAST = 6711
const XPRS_PTB_SHIFTSCALE_COLS_ACTIVE = 6720
const XPRS_PTB_SHIFTSCALE_COLS_SEEDLAST = 6721
const XPRS_PTB_SHIFTSCALE_COLS_SHIFT_ACTIVE_I = 6725
const XPRS_PTB_SHIFTSCALE_COLS_NEGATE_ACTIVE_I = 6726
const XPRS_PTB_SHIFTSCALE_COLS_COMPLEMENT_ACTIVE_I = 6727
const XPRS_PTB_SHIFTSCALE_COLS_COMPLEMENT_ACTIVE_B = 6728
const XPRS_PTB_SHIFTSCALE_ROWS_ACTIVE = 6760
const XPRS_PTB_SHIFTSCALE_ROWS_SEEDLAST = 6761
const XPRS_PTB_PERTURB_COST2_TOTALABSCOSTCHANGE = 6713
const XPRS_PTB_SHIFTSCALE_COLS_FIXEDOBJDELTA = 6724
const XPRS_PTB_PERMUTE_PERMCOUNT_ROW = 6704
const XPRS_PTB_PERMUTE_PERMCOUNT_COL = 6705
const XPRS_PTB_PERTURB_COST2_CHANGEDCOLCOUNT = 6712
const XPRS_PTB_SHIFTSCALE_COLS_CHANGEDCOLCOUNT = 6723
const XPRS_LP_UNSTARTED = 0
const XPRS_LP_OPTIMAL = 1
const XPRS_LP_INFEAS = 2
const XPRS_LP_CUTOFF = 3
const XPRS_LP_UNFINISHED = 4
const XPRS_LP_UNBOUNDED = 5
const XPRS_LP_CUTOFF_IN_DUAL = 6
const XPRS_LP_UNSOLVED = 7
const XPRS_LP_NONCONVEX = 8
const XPRS_MIP_NOT_LOADED = 0
const XPRS_MIP_LP_NOT_OPTIMAL = 1
const XPRS_MIP_LP_OPTIMAL = 2
const XPRS_MIP_NO_SOL_FOUND = 3
const XPRS_MIP_SOLUTION = 4
const XPRS_MIP_INFEAS = 5
const XPRS_MIP_OPTIMAL = 6
const XPRS_MIP_UNBOUNDED = 7
const XPRS_BAR_DEFAULT = 0
const XPRS_BAR_MIN_DEGREE = 1
const XPRS_BAR_MIN_LOCAL_FILL = 2
const XPRS_BAR_NESTED_DISSECTION = 3
const XPRS_ALG_DEFAULT = 1
const XPRS_ALG_DUAL = 2
const XPRS_ALG_PRIMAL = 3
const XPRS_ALG_BARRIER = 4
const XPRS_ALG_NETWORK = 5
const XPRS_STOP_NONE = 0
const XPRS_STOP_TIMELIMIT = 1
const XPRS_STOP_CTRLC = 2
const XPRS_STOP_NODELIMIT = 3
const XPRS_STOP_ITERLIMIT = 4
const XPRS_STOP_MIPGAP = 5
const XPRS_STOP_SOLLIMIT = 6
const XPRS_STOP_USER = 9
const XPRS_ANA_AUTOMATIC = -1
const XPRS_ANA_NEVER = 0
const XPRS_ANA_ALWAYS = 1
const XPRS_BOOL_OFF = 0
const XPRS_BOOL_ON = 1
const XPRS_BACKTRACKALG_BEST_ESTIMATE = 2
const XPRS_BACKTRACKALG_BEST_BOUND = 3
const XPRS_BACKTRACKALG_DEEPEST_NODE = 4
const XPRS_BACKTRACKALG_HIGHEST_NODE = 5
const XPRS_BACKTRACKALG_EARLIEST_NODE = 6
const XPRS_BACKTRACKALG_LATEST_NODE = 7
const XPRS_BACKTRACKALG_RANDOM = 8
const XPRS_BACKTRACKALG_MIN_INFEAS = 9
const XPRS_BACKTRACKALG_BEST_ESTIMATE_MIN_INFEAS = 10
const XPRS_BACKTRACKALG_DEEPEST_BEST_ESTIMATE = 11
const XPRS_BRANCH_MIN_EST_FIRST = 0
const XPRS_BRANCH_MAX_EST_FIRST = 1
const XPRS_ALG_PULL_CHOLESKY = 0
const XPRS_ALG_PUSH_CHOLESKY = 1
const XPRS_XDRPBEFORE_CROSSOVER = 1
const XPRS_XDRPINSIDE_CROSSOVER = 2
const XPRS_XDRPAGGRESSIVE_BEFORE_CROSSOVER = 4
const XPRS_DUALGRADIENT_AUTOMATIC = -1
const XPRS_DUALGRADIENT_DEVEX = 0
const XPRS_DUALGRADIENT_STEEPESTEDGE = 1
const XPRS_DUALSTRATEGY_REMOVE_INFEAS_WITH_PRIMAL = 0
const XPRS_DUALSTRATEGY_REMOVE_INFEAS_WITH_DUAL = 1
const XPRS_FEASIBILITYPUMP_AUTOMATIC = -1
const XPRS_FEASIBILITYPUMP_NEVER = 0
const XPRS_FEASIBILITYPUMP_ALWAYS = 1
const XPRS_FEASIBILITYPUMP_LASTRESORT = 2
const XPRS_HEURSEARCH_LOCAL_SEARCH_LARGE_NEIGHBOURHOOD = 0
const XPRS_HEURSEARCH_LOCAL_SEARCH_NODE_NEIGHBOURHOOD = 1
const XPRS_HEURSEARCH_LOCAL_SEARCH_SOLUTION_NEIGHBOURHOOD = 2
const XPRS_HEURSTRATEGY_AUTOMATIC = -1
const XPRS_HEURSTRATEGY_NONE = 0
const XPRS_HEURSTRATEGY_BASIC = 1
const XPRS_HEURSTRATEGY_ENHANCED = 2
const XPRS_HEURSTRATEGY_EXTENSIVE = 3
const XPRS_NODESELECTION_LOCAL_FIRST = 1
const XPRS_NODESELECTION_BEST_FIRST = 2
const XPRS_NODESELECTION_LOCAL_DEPTH_FIRST = 3
const XPRS_NODESELECTION_BEST_FIRST_THEN_LOCAL_FIRST = 4
const XPRS_NODESELECTION_DEPTH_FIRST = 5
const XPRS_OUTPUTLOG_NO_OUTPUT = 0
const XPRS_OUTPUTLOG_FULL_OUTPUT = 1
const XPRS_OUTPUTLOG_ERRORS_AND_WARNINGS = 2
const XPRS_OUTPUTLOG_ERRORS = 3
const XPRS_PREPROBING_AUTOMATIC = -1
const XPRS_PREPROBING_DISABLED = 0
const XPRS_PREPROBING_LIGHT = 1
const XPRS_PREPROBING_FULL = 2
const XPRS_PREPROBING_FULL_AND_REPEAT = 3
const XPRS_PRESOLVEOPS_SINGLETONCOLUMNREMOVAL = 1
const XPRS_PRESOLVEOPS_SINGLETONROWREMOVAL = 2
const XPRS_PRESOLVEOPS_FORCINGROWREMOVAL = 4
const XPRS_PRESOLVEOPS_DUALREDUCTIONS = 8
const XPRS_PRESOLVEOPS_REDUNDANTROWREMOVAL = 16
const XPRS_PRESOLVEOPS_DUPLICATECOLUMNREMOVAL = 32
const XPRS_PRESOLVEOPS_DUPLICATEROWREMOVAL = 64
const XPRS_PRESOLVEOPS_STRONGDUALREDUCTIONS = 128
const XPRS_PRESOLVEOPS_VARIABLEELIMINATIONS = 256
const XPRS_PRESOLVEOPS_NOIPREDUCTIONS = 512
const XPRS_PRESOLVEOPS_NOADVANCEDIPREDUCTIONS = 2048
const XPRS_PRESOLVEOPS_LINEARLYDEPENDANTROWREMOVAL = 16384
const XPRS_PRESOLVEOPS_NOINTEGERVARIABLEANDSOSDETECTION = 32768
const XPRS_PRESOLVESTATE_PROBLEMLOADED = 1 << 0
const XPRS_PRESOLVESTATE_PROBLEMLPPRESOLVED = 1 << 1
const XPRS_PRESOLVESTATE_PROBLEMMIPPRESOLVED = 1 << 2
const XPRS_PRESOLVESTATE_SOLUTIONVALID = 1 << 7
const XPRS_MIPPRESOLVE_REDUCED_COST_FIXING = 1
const XPRS_MIPPRESOLVE_LOGIC_PREPROCESSING = 2
const XPRS_MIPPRESOLVE_ALLOW_CHANGE_BOUNDS = 8
const XPRS_PRESOLVE_NOPRIMALINFEASIBILITY = -1
const XPRS_PRESOLVE_NONE = 0
const XPRS_PRESOLVE_DEFAULT = 1
const XPRS_PRESOLVE_KEEPREDUNDANTBOUNDS = 2
const XPRS_PRICING_PARTIAL = -1
const XPRS_PRICING_DEFAULT = 0
const XPRS_PRICING_DEVEX = 1
const XPRS_CUTSTRATEGY_DEFAULT = -1
const XPRS_CUTSTRATEGY_NONE = 0
const XPRS_CUTSTRATEGY_CONSERVATIVE = 1
const XPRS_CUTSTRATEGY_MODERATE = 2
const XPRS_CUTSTRATEGY_AGGRESSIVE = 3
const XPRS_VARSELECTION_AUTOMATIC = -1
const XPRS_VARSELECTION_MIN_UPDOWN_PSEUDO_COSTS = 1
const XPRS_VARSELECTION_SUM_UPDOWN_PSEUDO_COSTS = 2
const XPRS_VARSELECTION_MAX_UPDOWN_PSEUDO_COSTS_PLUS_TWICE_MIN = 3
const XPRS_VARSELECTION_MAX_UPDOWN_PSEUDO_COSTS = 4
const XPRS_VARSELECTION_DOWN_PSEUDO_COST = 5
const XPRS_VARSELECTION_UP_PSEUDO_COST = 6
const XPRS_SCALING_ROW_SCALING = 1
const XPRS_SCALING_COLUMN_SCALING = 2
const XPRS_SCALING_ROW_SCALING_AGAIN = 4
const XPRS_SCALING_MAXIMUM = 8
const XPRS_SCALING_CURTIS_REID = 16
const XPRS_SCALING_BY_MAX_ELEM_NOT_GEO_MEAN = 32
const XPRS_SCALING_OBJECTIVE_SCALING = 64
const XPRS_SCALING_EXCLUDE_QUADRATIC_FROM_SCALE_FACTOR = 128
const XPRS_SCALING_IGNORE_QUADRATIC_ROW_PART = 256
const XPRS_SCALING_BEFORE_PRESOLVE = 512
const XPRS_SCALING_NO_SCALING_ROWS_UP = 1024
const XPRS_SCALING_NO_SCALING_COLUMNS_DOWN = 2048
const XPRS_SCALING_SIMPLEX_OBJECTIVE_SCALING = 4096
const XPRS_SCALING_RHS_SCALING = 8192
const XPRS_SCALING_NO_AGGRESSIVE_Q_SCALING = 16384
const XPRS_SCALING_SLACK_SCALING = 32768
const XPRS_CUTSELECT_CLIQUE = 32 + 1823
const XPRS_CUTSELECT_MIR = 64 + 1823
const XPRS_CUTSELECT_COVER = 128 + 1823
const XPRS_CUTSELECT_FLOWPATH = 2048 + 1823
const XPRS_CUTSELECT_IMPLICATION = 4096 + 1823
const XPRS_CUTSELECT_LIFT_AND_PROJECT = 8192 + 1823
const XPRS_CUTSELECT_DISABLE_CUT_ROWS = 16384 + 1823
const XPRS_CUTSELECT_GUB_COVER = 32768 + 1823
const XPRS_CUTSELECT_DEFAULT = -1
const XPRS_REFINEOPS_LPOPTIMAL = 1
const XPRS_REFINEOPS_MIPSOLUTION = 2
const XPRS_REFINEOPS_MIPOPTIMAL = 4
const XPRS_REFINEOPS_MIPNODELP = 8
const XPRS_REFINEOPS_LPPRESOLVE = 16
const XPRS_DUALIZEOPS_SWITCHALGORITHM = 1
const XPRS_TREEDIAGNOSTICS_MEMORY_USAGE_SUMMARIES = 1
const XPRS_TREEDIAGNOSTICS_MEMORY_SAVED_REPORTS = 2
const XPRS_BARPRESOLVEOPS_STANDARD_PRESOLVE = 0
const XPRS_BARPRESOLVEOPS_EXTRA_BARRIER_PRESOLVE = 1
const XPRS_PRECOEFELIM_DISABLED = 0
const XPRS_PRECOEFELIM_AGGRESSIVE = 1
const XPRS_PRECOEFELIM_CAUTIOUS = 2
const XPRS_PREDOMROW_AUTOMATIC = -1
const XPRS_PREDOMROW_DISABLED = 0
const XPRS_PREDOMROW_CAUTIOUS = 1
const XPRS_PREDOMROW_MEDIUM = 2
const XPRS_PREDOMROW_AGGRESSIVE = 3
const XPRS_PREDOMCOL_AUTOMATIC = -1
const XPRS_PREDOMCOL_DISABLED = 0
const XPRS_PREDOMCOL_CAUTIOUS = 1
const XPRS_PREDOMCOL_AGGRESSIVE = 2
const XPRS_PRIMALUNSHIFT_ALLOW_DUAL_UNSHIFT = 0
const XPRS_PRIMALUNSHIFT_NO_DUAL_UNSHIFT = 1
const XPRS_REPAIRINDEFINITEQ_REPAIR_IF_POSSIBLE = 0
const XPRS_REPAIRINDEFINITEQ_NO_REPAIR = 1
const XPRS_OBJ_MINIMIZE = 1
const XPRS_OBJ_MAXIMIZE = -1
const XPRS_TYPE_NOTDEFINED = 0
const XPRS_TYPE_INT = 1
const XPRS_TYPE_INT64 = 2
const XPRS_TYPE_DOUBLE = 3
const XPRS_TYPE_STRING = 4
const XPRS_QCONVEXITY_UNKNOWN = -1
const XPRS_QCONVEXITY_NONCONVEX = 0
const XPRS_QCONVEXITY_CONVEX = 1
const XPRS_QCONVEXITY_REPAIRABLE = 2
const XPRS_QCONVEXITY_CONVEXCONE = 3
const XPRS_QCONVEXITY_CONECONVERTABLE = 4
const XPRS_SOLINFO_ABSPRIMALINFEAS = 0
const XPRS_SOLINFO_RELPRIMALINFEAS = 1
const XPRS_SOLINFO_ABSDUALINFEAS = 2
const XPRS_SOLINFO_RELDUALINFEAS = 3
const XPRS_SOLINFO_MAXMIPFRACTIONAL = 4
const XPRS_ISUSERSOLUTION = 0x01
const XPRS_ISREPROCESSEDUSERSOLUTION = 0x02
const XPRSobject_s = Cvoid
const XPRSobject = Ptr{XPRSobject_s}
const xo_prob_struct = Cvoid
const XPRSprob = Ptr{xo_prob_struct}
const XPRSglobalenv_s = Cvoid
const XPRSglobalenv = Ptr{XPRSglobalenv_s}
const XPRSmipsolpool_s = Cvoid
const XPRSmipsolpool = Ptr{XPRSmipsolpool_s}
const XPRSmessagingadmin_s = Cvoid
const XPRSmessagingadmin = Ptr{XPRSmessagingadmin_s}
const xo_NameList = Cvoid
const XPRSnamelist = Ptr{xo_NameList}
const XPRSmipsolenum_s = Cvoid
const XPRSmipsolenum = Ptr{XPRSmipsolenum_s}
const XPRSprobperturber_s = Cvoid
const XPRSprobperturber = Ptr{XPRSprobperturber_s}
const xo_user_branch_entity_s = Cvoid
const XPRSbranchobject = Ptr{xo_user_branch_entity_s}
const pwq_parman_s = Cvoid
const XPRSparman = Ptr{pwq_parman_s}
const PoolCut = Cvoid
const XPRScut = Ptr{PoolCut}
const xo_TreeNode_s = Cvoid
const XPRSnode = Ptr{xo_TreeNode_s}


text:
function _train(states, target_data, svr::LIBSVM.AbstractSVR)
    out_size = size(target_data, 1)
    output_matrix = []

    for i in 1:out_size
        out_size == 1 ? target = vec(target_data) : target = target_data[i,:]
        push!(output_matrix, LIBSVM.fit!(svr, states', target_data[i,:]))
    end

    return OutputLayer(svr, output_matrix, out_size, target_data[:,end])
end

max_stars_repo_name: MartinuzziFrancesco/EchoStateNetwork

max_issues_repo_name: MartinuzziFrancesco/EchoStateNetwork

max_forks_repo_name: MartinuzziFrancesco/EchoStateNetwork


text:
module Francy

export canvas, graph, node, link, menu, callback, message, Trigger, chart,
       dataset
import Base.push!, Base.show

using JSON, IJulia

const FrancyMimeString = "application/vnd.francy+json"
const FrancyMime = MIME"application/vnd.francy+json"

function __init__()
  #once..
  IJulia.register_mime(MIME(FrancyMimeString))

  #useful for debugging Trigger...
  #IJulia.set_verbose(true)
end

Base.istextmime(::FrancyMime) = true

id_cnt = 0
function create_id()
  global id_cnt += 1
  return "id$id_cnt"
end

abstract type FrancyType end

mutable struct Canvas <: FrancyType
  c::Dict
end

mutable struct Graph <: FrancyType
  g::Dict
end

mutable struct Message <: FrancyType
  m::Dict
end

mutable struct Menu <: FrancyType
  m::Dict
end

mutable struct Chart <: FrancyType
  c::Dict
end

mutable struct Dataset <: FrancyType
  d::Dict
end

mutable struct Callback <: FrancyType
  c::Dict
end

mutable struct Node <: FrancyType
  s::Dict
end

mutable struct Link <: FrancyType
  l::Dict
end

function show(io::IO, t::FrancyMime, c::Canvas)
  C = Dict(:version => "1.0.4",
       :mime => FrancyMimeString,
       :canvas => c.c
       )
  print(io, JSON.json(C))
end

canvas_cache = Dict{String, WeakRef}()

function canvas(t::String; width = 800, height = 600)
  C = Canvas(Dict(:width => width,
         :id => create_id(),
         :height => height,
         :title => t,
         :zoomToFit => true,
         :texTypesetting => false,
         :menus => Dict(),
         :messages => Dict(),
         :graph => Dict(),
         :chart => Dict()
    ))

  global canvas_cache
  canvas_cache[C.c[:id]] = WeakRef(C)
  return C
end

#= type can be
  :directed
  :tree
  :undirected
=#
const graph_types = [:directed, :tree, :undirected]
function graph(type = :directed)
  type in graph_types || error("type has to be one of ", graph_types)
  return Graph(Dict(:type => type,
              :id => create_id(),
              :simulation => false,
              :collapsed => true,
              :links => Dict(),
              :nodes => Dict(),
              :messages => Dict(),
              :drag => true,
              :showNeighbours => false
              ))
end

function push!(C::Canvas, G::Graph)
  if length(C.c[:graph]) > 0
    error("Graph already present")
  end
  if length(C.c[:chart]) > 0
    error("Chart already present")
  end
  C.c[:graph] = G.g
end

function push!(C::Canvas, c::Chart)
  if length(C.c[:graph]) > 0
    error("Graph already present")
  end
  if length(C.c[:chart]) > 0
    error("Chart already present")
  end
  C.c[:chart] = c.c
end

#= type can be
 :triangle
 :diamond
 :circle
 :square
 :cross
 :star
 :wye
=#
const node_types = [:triangle, :diamond, :circle, :square, :cross, :star, :wye]
function node(n::String, type::Symbol = :circle)
  type in node_types || error("type has to be one of ", node_types)
  return Node(Dict(:type => type,
              :id => create_id(),
              :size => 10,
              :x => 0,
              :y => 0,
              :title => n,
              :layer => 0,
              :color => "",
              :parent => "",
              :menus => Dict(),
              :messages => Dict(),
              :callbacks => Dict()
              ))
end

function link(s::Node, t::Node; title = "", length = 0, weight = 0)
  return Link(Dict(:id => create_id(),
              :source => s.s[:id],
              :target => t.s[:id],
              :length => length,
              :weight => weight,
              :color => "",
              :title => title,
              :invisible => false
              ))
end

function push!(G::Graph, S::Node)
  G.g[:nodes][S.s[:id]] = S.s
end

function push!(G::Graph, L::Link)
  G.g[:links][L.l[:id]] = L.l
end

#= trigger can be
  :click  -> mouse event, left click in js
  :context -> mouse event, right click or context-menu
  :dblclick -> mouse event, double click
=#
const trigger_types = [:click, :context, :dblclick]
function callback(f::String, a::String, t = :click)
  t in trigger_types || error("Trigger can only be one of ", trigger_types)
  return Callback(Dict(:id => create_id(),
              :func => f,
              :trigger => t,
              :knownArgs => a,
              :requiredArgs => Dict()
              ))
end

function menu(t::String, C::Callback)
  return Menu(Dict(:id => create_id(),
              :title => t,
              :callback => C.c))
end

function add(k::Symbol, a::Dict, m::Dict)
  a[k][m[:id]] = m
end

push!(C::Canvas, M::Menu) = add(:menus, C.c, M.m)
push!(G::Graph, M::Menu) = add(:menus, G.g, M.m)
push!(S::Node, M::Menu) = add(:menus, S.s, M.m)

push!(C::Canvas, M::Message) = add(:messages, C.c, M.m)
push!(G::Graph, M::Message) = add(:messages, G.g, M.m)
push!(S::Node, M::Message) = add(:messages, S.s, M.m)

push!(S::Node, C::Callback) = add(:callbacks, S.s, C.c)

#= type can be
  :info
  :error
  :success
  :warning
  :default
=#
const message_types = [:info, :error, :success, :warning, :default]
function message(s::String, t::Symbol = :default)
  t in message_types || error("type must be one of ", message_types)
  return Message(Dict(:id => create_id(),
              :type => t,
              :title => s,
              :value => "v:$s"
              ))
end

function id(C::Canvas)
  return C.c[:id]
end

function canvas(id::Symbol)
  global canvas_cache
  return canvas_cache[string(id)].value
end

#= scale can be :linear, :band
=#
const axis_type = [:linear, :band]

function axis(dom::Array, title::String, scale::Symbol = :linear)
  scale in axis_type || error("scale must be one of ", axis_type)
  return Dict(:domain => dom,
              :title => title,
              :scale => scale
              )
end

#= type can be :line, :bar, :scatter
  =#

const chart_types = [:line, :bar, :scatter]
function chart(type::Symbol = :linel)
  type in chart_types || error("type must be one of ", chart_types)
  return Chart(Dict(
    :id => create_id(),
    :data => Dict(),
    :axis => Dict(:x => axis([], "x", :linear),
                  :y => axis([], "y", :linear)),
    :type => type,
    :labels => false,
    :legend => ""
    ))
end

function dataset(t::String, d::Array)
  return Dataset(Dict(:title => t, :data => d))
end

add_data(d::Dict, e::Dict) = d[:data][e[:title]] = e[:data]
push!(c::Chart, d::Dataset) = add_data(c.c, d.d)
push!(c::Chart, d::Tuple{String, Array}) = add_data(c.c, dataset(d[1], d[2]).d)

#=
 THE MAGIC!
Trigger from java script when a call back is executed...
it gets a string in json which is composed of the info.
Experimentally, the above works, the interface needs more work...
=#

function Trigger(a::String)  #needs to be in global scope
  # incomplete: there can be more args.
  b = JSON.parse(a)
  c = b["func"] * "(" * b["knownArgs"] * ")"
  res = Core.eval(Main, Meta.parse(c))
end

#= TODO
 maybe
   replace the functions by id and store the actual functions in
   a dictionary
   the fun will be to make it memory safe.
=#

end

max_stars_repo_name: fieker/Francy

max_issues_repo_name: fieker/Francy

max_forks_repo_name: fieker/Francy


text:
using Test, QBase

@testset "./src/Nonlocality/optimize_measurements.jl" begin

using BellScenario

@testset "Nonlocality.optimize_measurement(LocalSignaling)" begin
    @testset "non State types" begin
        scenario = LocalSignaling(3,3,2)
        game = BellGame([1 0 0;0 1 0;0 0 1], 2)
        ρ_states = [[1 0;0 0],[0 0;0 1],[0 0;0 1]]

        dict = Nonlocality.optimize_measurement(scenario, game, ρ_states)

        @test isapprox(dict["violation"], 0.0, atol=1e-6)
        @test dict["povm"] ≈ [[1 0;0 0],[0 0;0 0.5],[0 0;0 0.5]]
    end

    @testset "trine states" begin
        scenario = LocalSignaling(3,3,2)
        game = BellGame([1 0 0;0 1 0;0 0 1], 2)
        ρ_states = trine_qubit_states()

        dict = Nonlocality.optimize_measurement(scenario, game, ρ_states)

        @test isapprox(dict["violation"], 0.0, atol=1e-6)
        @test all(isapprox.(dict["povm"][1], 2/3*ρ_states[1], atol=1e-6))
        @test all(isapprox.(dict["povm"][2], 2/3*ρ_states[2], atol=1e-6))
        @test all(isapprox.(dict["povm"][3], 2/3*ρ_states[3], atol=1e-6))

        @test dict["states"] == ρ_states
        @test dict["game"] == game
        @test dict["scenario"] == scenario
    end

    @testset "bb84 states" begin
        scenario = LocalSignaling(4,4,2)
        game = BellGame([1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1], 2)
        ρ_states = bb84_qubit_states()

        dict = Nonlocality.optimize_measurement(scenario, game, ρ_states)

        @test isapprox(dict["violation"], 0.0, atol=1e-6)
        @test all(isapprox.(dict["povm"][1], 1/2*ρ_states[1], atol=1e-3))
        @test all(isapprox.(dict["povm"][2], 1/2*ρ_states[2], atol=1e-3))
        @test all(isapprox.(dict["povm"][3], 1/2*ρ_states[3], atol=1e-3))
        @test all(isapprox.(dict["povm"][4], 1/2*ρ_states[4], atol=1e-3))
    end

    @testset "sic qubit states" begin
        scenario = LocalSignaling(4,4,2)
        game = BellGame([1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1], 2)
        ρ_states = sic_qubit_states()

        dict = Nonlocality.optimize_measurement(scenario, game, ρ_states)

        @test isapprox(dict["violation"], 0.0, atol=1e-5)
        @test all(isapprox.(dict["povm"][1], 1/2*ρ_states[1], atol=1e-5))
        @test all(isapprox.(dict["povm"][2], 1/2*ρ_states[2], atol=1e-5))
        @test all(isapprox.(dict["povm"][3], 1/2*ρ_states[3], atol=1e-5))
        @test all(isapprox.(dict["povm"][4], 1/2*ρ_states[4], atol=1e-5))
    end

    @testset "Errors" begin
        scenario = LocalSignaling(3,3,2)
        states = bb84_qubit_states()
        game = BellGame([1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1], 2)

        @test_throws DomainError Nonlocality.optimize_measurement(scenario, game, states)

        scenario = LocalSignaling(4,4,3)
        @test_throws DomainError  Nonlocality.optimize_measurement(scenario, game, states)

        scenario = LocalSignaling(3,3,2)
        game = BellGame([1 0 0;0 1 0;0 0 1],2)
        states = [[1 0;0 1],[0 0;0 1],[0.5 0;0 0.5]]
        @test_throws DomainError Nonlocality.optimize_measurement(scenario, game, states)
    end
end

@testset "Nonlocality.optimize_measurement(::BipartiteNonSignaling)" begin
    @testset "matrix states and povms" begin
        scenario = BipartiteNonSignaling(2,2,2,2)
        game = BellGame([0 1 1 0;0 0 0 1;0 0 0 1;1 0 0 1],2)
        ρ_AB = [1 0 0 1;0 0 0 0;0 0 0 0;1 0 0 1]/2
        POVMs = [
            [[1 0;0 0],[0 0;0 1]],
            [[0.5 0.5;0.5 0.5],[0.5 -0.5;-0.5 0.5]]
        ]

        opt_dictA = Nonlocality.optimize_measurement(scenario, game, ρ_AB, A_POVMs=POVMs)
        opt_dictB = Nonlocality.optimize_measurement(scenario, game, ρ_AB, B_POVMs=POVMs)

        @test opt_dictA["score"] ≈ 2.20710279
        @test opt_dictA["violation"] ≈ 0.207102796
        @test opt_dictA["A_POVMs"] isa Vector{<:POVM}
        @test opt_dictA["state"] isa State

        @test opt_dictB["score"] ≈ 2.20710279
        @test opt_dictB["violation"] ≈ 0.207102796
        @test opt_dictB["B_POVMs"] isa Vector{<:POVM}
        @test opt_dictB["state"] isa State
    end

    @testset "CHSH inequality" begin
        scenario = BipartiteNonSignaling(2,2,2,2)
        game = BellGame([0 1 1 0;0 0 0 1;0 0 0 1;1 0 0 1],2)
        ρ_AB = bell_states()[1]
        POVMs = [
            POVM([[1 0;0 0],[0 0;0 1]]),
            POVM([[0.5 0.5;0.5 0.5],[0.5 -0.5;-0.5 0.5]])
        ]

        @test game.β == 2

        opt_dictA = Nonlocality.optimize_measurement(scenario, game, ρ_AB, A_POVMs=POVMs)
        opt_dictB = Nonlocality.optimize_measurement(scenario, game, ρ_AB, B_POVMs=POVMs)

        @test length(keys(opt_dictA)) == 7
        @test opt_dictA["scenario"] == scenario
        @test opt_dictA["game"] == game
        @test opt_dictA["game"].β == 2
        @test opt_dictA["score"] ≈ 2.20710279
        @test opt_dictA["violation"] ≈ 0.207102796
        @test opt_dictA["state"] == ρ_AB
        @test opt_dictA["A_POVMs"] == POVMs
        @test isapprox(
            opt_dictA["B_POVMs"],
            [
                [bloch_qubit_state(π/4,0), bloch_qubit_state(5π/4,0)],
                [bloch_qubit_state(7π/4,0), bloch_qubit_state(3π/4,0)]
            ],
            atol=1e-5
        )

        @test length(keys(opt_dictB)) == 7
        @test opt_dictB["scenario"] == scenario
        @test opt_dictB["game"] == game
        @test opt_dictB["game"].β == 2
        @test opt_dictB["score"] ≈ 2.2071028
        @test opt_dictB["violation"] ≈ 0.207102796
        @test opt_dictB["state"] == ρ_AB
        @test opt_dictB["B_POVMs"] == POVMs
        @test isapprox(
            opt_dictB["A_POVMs"],
            [
                [bloch_qubit_state(π/4,0), bloch_qubit_state(5π/4,0)],
                [bloch_qubit_state(7π/4,0),bloch_qubit_state(3π/4,0)]
            ],
            atol=1e-5
        )
    end

    @testset "Domain Errors" begin
        scenario = BipartiteNonSignaling(2,2,2,2)
        scenarioA = BipartiteNonSignaling(3,2,3,2)
        scenarioB = BipartiteNonSignaling(2,3,2,3)
        game = BellGame([0 1 1 0;0 0 0 1;0 0 0 1;1 0 0 1],2)
        ρ_AB = bell_states()[1]
        POVMs = [
            POVM([[1 0;0 0],[0 0;0 1]]),
            POVM([[0.5 0.5;0.5 0.5],[0.5 -0.5;-0.5 0.5]])
        ]

        @test_throws DomainError Nonlocality.optimize_measurement(scenario, game, ρ_AB)

        @test_throws DomainError Nonlocality.optimize_measurement(scenarioA, game, ρ_AB, A_POVMs=POVMs)
        @test_throws DomainError Nonlocality.optimize_measurement(scenarioB, game, ρ_AB, B_POVMs=POVMs)

        @test_throws DomainError Nonlocality.optimize_measurement(
            scenario, game, [1 0 0 1;0 0 0 0;0 0 0 0;1 0 0 1],A_POVMs=POVMs
        )
        @test_throws DomainError Nonlocality.optimize_measurement(
            scenario, game, ρ_AB, A_POVMs = [[[1 0;0 1],[1 0;0 1]],[[1 0;0 0],[1 0;0 0]]]
        )
        @test_throws DomainError Nonlocality.optimize_measurement(
            scenario, game, ρ_AB, B_POVMs = [[[1 0;0 1],[1 0;0 1]],[[1 0;0 0],[1 0;0 0]]]
        )
    end
end

end


text:
"""
    LatentGP(f<:GP, lik)

 - `fx` is a `FiniteGP`.
 - `lik` is the log likelihood function which maps sample from f to corresposing
 conditional likelihood distributions.

"""
struct LatentGP{T<:AbstractGPs.FiniteGP, S}
    fx::T
    lik::S
end

function Distributions.rand(rng::AbstractRNG, lgp::LatentGP)
    f = rand(rng, lgp.fx)
    y = rand(rng, lgp.lik(f))
    return (f=f, y=y)
end

"""
    logpdf(lgp::LatentGP, y::NamedTuple{(:f, :y)})

```math
    log p(y, f; x)
```
Returns the joint log density of the gaussian process output `f` and real output `y`.
"""
function Distributions.logpdf(lgp::LatentGP, y::NamedTuple{(:f, :y)})
    return logpdf(lgp.fx, y.f) + logpdf(lgp.lik(y.f), y.y)
end


text:
# return the i-th bit
@inline bitat(chunk::UInt64, i::Int) = (chunk >>> (64 - i)) & 0x01 == 0x01
@inline bitat{T<:Unsigned}(::Type{T}, chunk::T, i::Int) = (chunk >>> (sizeof(T) * 8 - i)) & 1 == 1

# assume 1 byte = 8 bits
@inline bitsof{T<:Unsigned}(::Type{T}) = sizeof(T) * 8

@inline mod64(i) = i & 63

# make a bit mask
@inline lmask{T<:Unsigned}(typ::Type{T}, n::Int) = typemax(typ) << (bitsof(typ) - n)
@inline rmask{T<:Unsigned}(typ::Type{T}, n::Int) = typemax(typ) >> (bitsof(typ) - n)


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule p7zip_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("p7zip")
JLLWrappers.@generate_main_file("p7zip", UUID("3f19e933-33d8-53b3-aaab-bd5110c3b7a0"))
end  # module p7zip_jll


text:
module Neural
    using Random
    using Plots
    include("functions.jl")

    mutable struct Layer
        W::AbstractArray{Float64} # weights
        b::Vector{Float64} # bias

        afun::Function     # activaion function
        dafun::Function    # derivative of the activation function

        z::Vector{Float64} # W*x+b
        a::Vector{Float64} # afun(z)

        dCda::Vector{Float64}
        dCdW::AbstractArray{Float64}
        dCdb::Vector{Float64}

        function Layer(inlen::Int64, outlen::Int64, afun::Function, dafun::Function)
            σ = 2/(inlen + outlen)

            new(rand(outlen, inlen) * σ, rand(outlen) * σ, afun, dafun, [zeros(outlen) for i in 1:3]..., zeros(outlen, inlen), zeros(outlen))
        end
    end

    mutable struct Net
        layers::Vector{Layer}
        C::Function
        dC::Function

        function Net(inlength::Int64, sizes::Vector{Int64}, activations::Vector; # activations can be eighter vector of symbols or vector of
                                                                                # Tuple{Function, Function} where the 2nd function is derivative of the 1st
                    C::Function = softmaxLikelihood, dC::Function = dSoftmaxLikelihood)

            layers = Vector{Layer}()
            ilen = inlength
            for (size, id) in zip(sizes, activations)
                push!(layers, Layer(ilen, size, getFunctions(id)...))
                ilen = size
            end

            new(layers, C, dC)
        end
    end

    @views function makechunks(X::AbstractArray, n::Integer)
        c = length(X) ÷ n
        return [X[1+c*k:(k == n-1 ? end : c*k+c)] for k = 0:n-1]
    end

    mean(x) = sum(x)/length(x)

    getFunctions(id::Symbol) = activations[id]

    getFunctions(f::Tuple{Function, Function}) = f

    function applyLayer!(layer::Layer, x::AbstractArray)
        layer.z = layer.W*x + layer.b
        layer.a = layer.afun(layer.z)

        return layer.a
    end

    function forward!(net::Net, x::AbstractArray)
        input = x
        map(layer -> input = applyLayer!(layer, input), net.layers)

        return input
    end

    function backward!(net::Net, x::AbstractArray, t::AbstractArray)
       lastLayer = net.layers[end]

       lastLayer.dCda =  lastLayer.dafun(lastLayer.z) * net.dC(lastLayer.a, t)
       lastLayer.dCdW += lastLayer.dCda * transpose(net.layers[end - 1].a)
       lastLayer.dCdb += lastLayer.dCda

       for i in (length(net.layers) - 1):-1:1
            layer = net.layers[i]
            next = net.layers[i + 1]
            prevout = i == 1 ? x : net.layers[i - 1].a

            layer.dCda = layer.dafun(layer.a) * transpose(next.W) * next.dCda
            layer.dCdW += layer.dCda * transpose(prevout)
            layer.dCdb += layer.dCda
       end
    end

    function updateLayer!(layer::Layer, α::Float64)
        layer.W -= α*layer.dCdW
        layer.b -= α*layer.dCdb

        layer.dCda = zeros(size(layer.dCda))
        layer.dCdb = zeros(size(layer.dCdb))
        layer.dCdW = zeros(size(layer.dCdW))
    end

    function identify(net::Net, x::AbstractArray)
        vec = forward!(net, x)
        id = argmax(vec)

        return id, vec
    end

    function accuracy(net::Net, x::AbstractArray, t::AbstractArray)
        identities = map(i -> identify(net, x[:, i])[1], 1:size(x, 2))
        cmp = [Int(identities[i] == argmax(t[:, i])) for i in 1:size(t, 2)]

        return sum(cmp)/size(t, 2)
    end

    function train!(net::Net, x::AbstractArray, t::AbstractArray, batchSize::Int64, epochs::Int64, α::Float64, αDecay::Float64 = 1.0)
    plotly()

    meanCosts = Vector{Float64}()
    accs = Vector{Float64}()

    testIndices = shuffle(1:size(x, 2))[1:2*batchSize]
    trainIndices = filter(i -> !(i in testIndices), 1:size(x, 2))

    for i in 1:epochs
        costs = Vector{Float64}()
        acc = 0
        indices = shuffle(trainIndices) # one column represents one data point

        for i in indices[1:batchSize]
            forward!(net, x[:, i])
            backward!(net, x[:, i], t[:, i])
            updateLayer!.(net.layers, α)

            output = forward!(net, x[:, i])
            push!(costs, net.C(output, t[:, i]))
        end
        acc = accuracy(net, x[:, testIndices], t[:, testIndices])
        meanCost = mean(costs)
        α /= αDecay

        push!(meanCosts, meanCost)
        push!(accs, acc);
        println("Epoch $i/$epochs:")
        println("\tMean cost: $meanCost")
        println("\tAccuracy: $(acc *100)%")
        println("\tLearning rate: $α")
    end

    plt = plot(1:epochs, meanCosts, xlabel = "Epoch", ylabel = "Mean cost", legend = false, line = [:scatter, :path], dpi = 600, size = (1440, 810), grid = false)
    plot!(plt, 1:epochs, accs, line = [:scatter, :path])
    display(plt)
    #savefig(plt, "plt.png")
end

end

max_stars_repo_name: achjaj/shape-recognition

max_issues_repo_name: achjaj/shape-recognition

max_forks_repo_name: achjaj/shape-recognition


text:
struct IPythonDisplay <: AbstractDisplay end

Base.display(d::IPythonDisplay, m::MIME, @nospecialize(x)) =
    try
        buf = IOBuffer()
        show(buf, m, x)
        data = take!(buf)
        dict = pydict()
        dict[string(m)] = istextmime(m) ? pystr(data) : pybytes(data)
        @py `sys.modules["IPython"].display.display($dict, raw=True)`
    catch
        throw(MethodError(display, (d, m, x)))
    end

Base.display(d::IPythonDisplay, @nospecialize(x)) = begin
    if ispyref(x)
        @py `sys.modules["IPython"].display.display($x)`
        return
    end
    buf = IOBuffer()
    dict = pydict()
    for (m, _) in [_py_mimes; (MIME"text/plain", "")]
        try
            show(buf, m(), x)
        catch
            continue
        end
        data = take!(buf)
        dict[string(m())] = istextmime(m()) ? pystr(data) : pybytes(data)
    end
    length(dict) == 0 && throw(MethodError(display, (d, x)))
    try
        @py `sys.modules["IPython"].display.display($dict, raw=True)`
    catch
        throw(MethodError(display, (d, x)))
    end
end


text:
using Test

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


text:
############################################################################################
# Constants
"RNG for sampling based solutions"
const _RNG = Random.MersenneTwister(1)   # shorthand
Random.seed!(_RNG, 1)

"Tolerance for stochastic solutions"
const _TOL = 1.0e-6

"Number of samples"
N = 10^3

"Initial number of data points for DataTune"
N_initial = Int64(N / 4)

############################################################################################
# Assign data configuration in various dimensions
data_uv = zeros(N)
data_mv = zeros(Int64(N / 2), 2)
data_mv2 = zeros(2, Int64(N / 2))


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule ParseGen_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("ParseGen")
JLLWrappers.@generate_main_file("ParseGen", UUID("3685ca4f-ed3b-50e9-b1b5-004114d6e21a"))
end  # module ParseGen_jll


text:
"""
    Num(val)

Wrap anything in a type that is a subtype of Real
"""
struct Num <: Real
    val
end

const show_numwrap = Ref(false)

Num(x::Num) = x # ideally this should never be called
(n::Num)(args...) = Num(value(n)(map(value,args)...))
value(x) = x
value(x::Num) = x.val

SciMLBase.issymbollike(::Num) = true
SciMLBase.issymbollike(::SymbolicUtils.Symbolic) = true

SymbolicUtils.@number_methods(
                              Num,
                              Num(f(value(a))),
                              Num(f(value(a), value(b))),
                              [conj, real, transpose]
                             )
Base.conj(x::Num) = x
Base.transpose(x::Num) = x

Base.eps(::Type{Num}) = Num(0)
Base.typemin(::Type{Num}) = Num(-Inf)
Base.typemax(::Type{Num}) = Num(Inf)
Base.float(x::Num) = x

Base.promote_rule(::Type{Bool}, ::Type{<:Num}) = Num
for C in [Complex, Complex{Bool}]
    @eval begin
        Base.:*(x::Num, z::$C) = Complex(x * real(z), x * imag(z))
        Base.:*(z::$C, x::Num) = Complex(real(z) * x, imag(z) * x)
        Base.:/(x::Num, z::$C) = let (a, b) = reim(z), den = a^2 + b^2
            Complex(x * a / den, x * b / den)
        end
        Base.:/(z::$C, x::Num) = Complex(real(z) / x, imag(z) / x)
        Base.:+(x::Num, z::$C) = Complex(x + real(z), imag(z))
        Base.:+(z::$C, x::Num) = Complex(real(z) + x, imag(z))
        Base.:-(x::Num, z::$C) = Complex(x - real(z), -imag(z))
        Base.:-(z::$C, x::Num) = Complex(real(z) - x, imag(z))
    end
end

function Base.inv(z::Complex{Num})
    a, b = reim(z)
    den = a^2 + b^2
    Complex(a/den, -b/den)
end
function Base.:/(x::Complex{Num}, y::Complex{Num})
    a, b = reim(x)
    c, d = reim(y)
    den = c^2 + d^2
    Complex((a*c + b*d)/den, (b*c - a*d)/den)
end
Base.:^(z::Complex{Num}, n::Integer) = Base.power_by_squaring(z, n)

function Base.show(io::IO, z::Complex{<:Num})
    r, i = reim(z)
    compact = get(io, :compact, false)
    show(io, r)
    print(io, (compact ? "+" : " + ") * "(")
    show(io, i)
    print(io, ")*im")
end

SymbolicUtils.simplify(n::Num; kw...) = Num(SymbolicUtils.simplify(value(n); kw...))
"""
    substitute(expr, s::Dict)

Performs the substitution on `expr` according to rule(s) `s`.
# Examples
```julia
julia> @parameters t
(t,)
julia> @variables x y z(t)
(x, y, z(t))
julia> ex = x + y + sin(z)
(x + y) + sin(z(t))
julia> substitute(ex, Dict([x => z, sin(z) => z^2]))
(z(t) + y) + (z(t) ^ 2)
```
"""
substitute(expr::Num, s::Pair; kw...) = Num(substituter(s)(value(expr); kw...)) # backward compat
substitute(expr::Num, s::Vector; kw...) = Num(substituter(s)(value(expr); kw...))
substitute(expr::Num, s::Dict; kw...) = Num(substituter(s)(value(expr); kw...))
# TODO: move this to SymbolicUtils
substitute(expr, s::Pair; kw...) = substituter([s[1] => s[2]])(expr; kw...)
substitute(expr, s::Vector; kw...) = substituter(s)(expr; kw...)

substituter(pair::Pair) = substituter((pair,))
function substituter(pairs)
    dict = Dict(value(k) => value(v)  for (k, v) in pairs)
    (expr; kw...) -> SymbolicUtils.substitute(expr, dict; kw...)
end

SymbolicUtils.symtype(n::Num) = symtype(n.val)

function Base.iszero(x::Num)
    x = value(x)
    x isa Number && iszero(x) && return true
    _x = SymbolicUtils.to_mpoly(x)[1]
    return (_x isa Number || _x isa SymbolicUtils.MPoly) && iszero(_x)
end

import SymbolicUtils: <ₑ, Symbolic, Term, operation, arguments

Base.show(io::IO, n::Num) = show_numwrap[] ? print(io, :(Num($(value(n))))) : Base.show(io, value(n))

Base.promote_rule(::Type{<:Number}, ::Type{<:Num}) = Num
Base.promote_rule(::Type{<:Symbolic{<:Number}}, ::Type{<:Num}) = Num
function Base.getproperty(t::Union{Add, Mul, Pow, Term}, f::Symbol)
    if f === :op
        Base.depwarn("`x.op` is deprecated, use `operation(x)` instead", :getproperty, force=true)
        operation(t)
    elseif f === :args
        Base.depwarn("`x.args` is deprecated, use `arguments(x)` instead", :getproperty, force=true)
        arguments(t)
    else
        getfield(t, f)
    end
end
<ₑ(s::Num, x) = value(s) <ₑ value(x)
<ₑ(s, x::Num) = value(s) <ₑ value(x)
<ₑ(s::Num, x::Num) = value(s) <ₑ value(x)

for T in (Integer, Rational)
    @eval Base.:(^)(n::Num, i::$T) = Num(value(n)^i)
end

macro num_method(f, expr, Ts=nothing)
    if Ts === nothing
        Ts = [Any]
    else
        @assert Ts.head == :tuple
        # e.g. a tuple or vector
        Ts = Ts.args
    end

    ms = [quote
              $f(a::$T, b::$Num) = $expr
              $f(a::$Num, b::$T) = $expr
          end for T in Ts]
    quote
        $f(a::$Num, b::$Num) = $expr
        $(ms...)
    end |> esc
end

"""
    tosymbolic(a::Union{Sym,Num}) -> Sym{Real}
    tosymbolic(a::T) -> T
"""
tosymbolic(a::Num) = tosymbolic(value(a))
tosymbolic(a::Sym) = Sym{symtype(a)}(nameof(a)) # unwrap stuff like Parameter{<:Number}
tosymbolic(a) = a

@num_method Base.isless  (val = isless(tosymbolic(a), tosymbolic(b)); val isa Bool ? val : Num(val)) (Real,)
@num_method Base.:(<)    (val = tosymbolic(a) < tosymbolic(b)       ; val isa Bool ? val : Num(val)) (Real,)
@num_method Base.:(<=)   (val = tosymbolic(a) <= tosymbolic(b)      ; val isa Bool ? val : Num(val)) (Real,)
@num_method Base.:(>)    (val = tosymbolic(a) > tosymbolic(b)       ; val isa Bool ? val : Num(val)) (Real,)
@num_method Base.:(>=)   (val = tosymbolic(a) >= tosymbolic(b)      ; val isa Bool ? val : Num(val)) (Real,)
@num_method Base.:(==)   (val = tosymbolic(a) == tosymbolic(b)      ; val isa Bool ? val : Num(val)) (AbstractFloat,Number)
@num_method Base.isequal isequal(tosymbolic(a), tosymbolic(b)) (AbstractFloat, Number, Symbolic)

Base.hash(x::Num, h::UInt) = hash(value(x), h)

Base.convert(::Type{Num}, x::Symbolic{<:Number}) = Num(x)
Base.convert(::Type{Num}, x::Number) = Num(x)
Base.convert(::Type{Num}, x::Num) = x

Base.convert(::Type{<:Array{Num}}, x::AbstractArray) = map(Num, x)
Base.convert(::Type{<:Array{Num}}, x::AbstractArray{Num}) = x
Base.convert(::Type{Sym}, x::Num) = value(x) isa Sym ? value(x) : error("cannot convert $x to Sym")

LinearAlgebra.lu(x::Union{Adjoint{<:Num},Transpose{<:Num},Array{<:Num}}; check=true, kw...) = sym_lu(x; check=check)

_iszero(x::Number) = iszero(x)
_isone(x::Number) = isone(x)
_iszero(::Symbolic) = false
_isone(::Symbolic) = false
_iszero(x::Num) = _iszero(value(x))
_isone(x::Num) = _isone(value(x))

SymbolicUtils.Code.toexpr(x::Num) = SymbolicUtils.Code.toexpr(value(x))

SymbolicUtils.setmetadata(x::Num, t, v) = Num(SymbolicUtils.setmetadata(value(x), t, v))
SymbolicUtils.getmetadata(x::Num, t) = SymbolicUtils.getmetadata(value(x), t)
SymbolicUtils.hasmetadata(x::Num, t) = SymbolicUtils.hasmetadata(value(x), t)


text:
function _naive_lag(block::Block, lag::Int64)
    return Block(block.times[(1 + lag):end], block.values[1:(end - lag)])
end

function _naive_diff(block::Block, lag::Int64)
    lagged_block = _naive_lag(block, lag)
    return Block(lagged_block.times, block.values[(1 + lag):end] - lagged_block.values)
end

@testset "lag" begin
    @testset "negative" begin
        @test_throws ArgumentError lag(n1, -1)
    end

    @testset "zero" begin
        # Lagging by zero knots should return identically the same node.
        @test lag(n1, 0) === n1
        @test lag(n2, 0) === n2
    end

    @testset "lag with one input knot" begin
        for n_lag in 1:3
            # n3 corresponds to a block with exactly one knot. So any amount of lagging
            # should then lead to a node which, when evaluated, gives a block with no knots.
            n = lag(n3, n_lag)

            @test value_type(n) == value_type(n3)
            @test _eval(n) == Block{value_type(n3)}()
        end
    end

    @testset "general" begin
        for n_lag in 0:10
            n = lag(n4, n_lag)
            @test value_type(n) == value_type(n4)
            @test _eval(n) == _naive_lag(b4, n_lag)
        end
    end
end

@testset "diff" begin
    @testset "non-positive" begin
        @test_throws ArgumentError diff(n1, -1)
        @test_throws ArgumentError diff(n1, 0)
    end

    @testset "general" begin
        @test diff(n4, 1) === diff(n4)
        for n_lag in 1:10
            n = diff(n4, n_lag)
            @test value_type(n) == value_type(n4)
            @test _eval(n) == _naive_diff(b4, n_lag)
        end
    end
end


text:
# DOESN'T ALWAYS WORK
## function redundant_constraint_check{T<:Real}(mat::ChernMat{T}, k::Int, verbosity::Int = 0)
##     zeros = find(x->x==0, mat.B[:, k+mat.n])
##     red_rows = IntSet()
##     for i in 1:k-1
##         zs = find(x->x==0, mat.B[:, i+mat.n])
##         if issubset(zs, zeros) && length(setdiff(zeros, zs)) > 0
##             push!(red_rows, i)
##         elseif issubset(zeros, zs) && length(setdiff(zs, zeros)) > 0
##             push!(red_rows, k)
##             break
##         end
##     end
##     return red_rows
## end

"""
# Description
Calculates the finite generators of the following cone:

   {x: Ax >= 0}

This is solved by the generalised Chernikova algorithm:
"A note on Chernikova's Algorithm" by Le Verge (1994)

# Arguments
* `A::Matrix{Integer}`: Matrix of cone constraints (each column defines a constraint)
* `verbosity`: level of information printed to standard output

# Returns
* `birays::Matrix{Integer}`: a matrix whose columns are the bidirectional cone generators
* `unirays::Matrix{Integer}`: a matrix whose columns are the unidirectional cone generators
* `redundant_cons::IntSet`: indices of constraints (rows) in input matrix which are redundant
"""
function chernikova_general(A::Matrix{T}, verbosity::Int = 0) where T<:Integer
    # Initialisation
    m, n = size(A)
    bidray = ChernMat(A)
    uniray = ChernMat(Array{T}(undef, 0, m+n), m, n, 0)

    #redundant_cons=IntSet()

    for k in 1:m
        if verbosity > 0
            println("Iteration ", k)
            println("---------------")
            println("Bidirectional rays")
            pprint(bidray)
            println("Unidirectional rays")
            pprint(uniray)
        end
        # Find if it exists, bidirectional ray which does not saturate k-th constraint
        index_non_zero = -1
        for i in 1:bidray.rows
            if bidray.B[i,k+n] != 0
                index_non_zero = i
                break
            end
        end

        if index_non_zero != -1
            if verbosity > 0
                println("Bidirectional ray $(index_non_zero) is unsaturated by constraint $(k)")
            end
            new_uni_ray = sign(bidray.B[index_non_zero, k+n]) * bidray.B[index_non_zero, :]
            new_uni_ray = reshape(new_uni_ray, 1, length(new_uni_ray))

            # Update bidirectional rays
            new_bidray_mat = remove_row(bidray.B, index_non_zero)
            for i in 1:bidray.rows-1
                if new_bidray_mat[i,n+k] != 0
                    new_bidray_mat[i, :] = combine(k+n, vec(new_uni_ray), vec(new_bidray_mat[i,:]))
                end
            end
            bidray.B = new_bidray_mat
            bidray.rows -= 1

            # Update unidirectional rays
            new_uniray_mat = add_row(uniray.B, new_uni_ray)
            for i in 1:uniray.rows
                if uniray.B[i, n+k] != 0
                    new_uniray_mat[i,:] = combine(new_uniray_mat, k+n, uniray.rows+1, i)
                end
            end
            uniray.B = new_uniray_mat
            uniray.rows += 1
        else
            if verbosity > 0
                println("All bidirectional rays are saturated by constraint $(k)")
            end

            pos, nil, neg = get_pos_neg_indices(uniray, k+n)
            if verbosity > 1
                println("pos, nil, neg: $(pos), $(nil), $(neg)")
            end

            if length(neg) == 0
                if verbosity > 0
                    println("Constraint $k is violated by no bidirectional or unidirectional rays so is redundant")
                end
                #push!(redundant_cons, k)
                continue
            end

            ## if length(pos) + length(nil) == 0
            ##     if verbosity > 0
            ##         println("Constraint $k violates all bidirectional and unidirectional rays so Cone is zero set")
            ##     end
            ##     return Array{T}(undef, n, 0)
            ## end

            if verbosity > 0
                println("Adding constraint $(k) which is currently violated by $(length(neg)) of $(uniray.rows) extremal rays")
                println("New unidirectional basis will consist of a maximum of $(uniray.rows) - $(length(neg)) + $(length(pos)) * $(length(neg)) = $(uniray.rows - length(neg) + length(pos)*length(neg)) extremal rays")
            end;

            max_rows = length(pos) + length(nil) + length(pos) * length(neg)
            new_B = Array{T}(undef, max_rows, uniray.m + uniray.n)

            # Handle case of two rows separately
            if uniray.rows == 2
                if verbosity > 0; println("Handling two row case..."); end;
                new_B[1,:] = uniray.B[pos[1],:]
                new_row = combine(uniray.B, k+n, pos[1], neg[1])
                if verbosity > 1; println("Candidate row: ", new_row); end;
                if !collinear(vec(uniray.B[pos[1],:]), vec(new_row))
                    new_B[2,:] = new_row
                    uniray.rows = 2
                    uniray.B = new_B
                else
                    uniray.rows = 1
                    uniray.B = new_B[1,:]
                end
                continue
            end

            # Add rows with non-negative intersections
            # with leading column to next matrix
            for (l,i) in enumerate([pos;nil]); new_B[l,:] = uniray.B[i,:]; end;
            new_rows = length(pos) + length(nil)

            # Go through pairs of row with positive and negative
            # coefficients in leading column and combine if necessary
            for i1 in pos, i2 in neg
                if combinable(uniray, i1, i2, verbosity - 1)
                    new_rows += 1
                    new_B[new_rows, :] = combine(uniray.B, k+n, i1, i2)
                end
            end
            uniray.B = new_B[1:new_rows,:]
            uniray.rows = new_rows

            if verbosity > 0
                @printf("Added %d / %d positive combinations of extremal rays\n",
                        new_rows - length(pos) - length(nil), length(pos) * length(neg))
                println("------------------------------------------------")
            end
        end
        #union!(redundant_cons, redundant_constraint_check(uniray,k, verbosity))
    end
    if verbosity > 0
        println("Result")
        println("---------------")
        println("Bidirectional rays")
        pprint(bidray)
        println("Unidirectional rays")
        pprint(uniray)
    end
    return norm_cols(LHS(bidray)'), norm_cols(LHS(uniray)')#, redundant_cons
end

function chernikova_general(A::Matrix{T}, verbosity::Int = 0) where T<:Rational
    Aint = intmat(A)
    chernikova_general(Aint, verbosity)
end

function remove_redundant_constraints(A::Matrix{T}, verbosity::Int = 0) where T<:Integer
    m,n = size(A)
    uni, bid, red_cons = chernikova_general(A)
    indices = setdiff(1:m, red_cons)
    return A[indices,:]
end


text:
function H5LSRTM()

end


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

using Documenter
using Stonks

DocMeta.setdocmeta!(Stonks, :DocTestSetup, :(using Stonks); recursive=true)

makedocs(
    sitename = "Stonks.jl",
    format = Documenter.HTML(
      prettyurls = false,
    ),
    modules = [Stonks],
    pages = [
      "Home" => "index.md",
      "User guide" => [
        "basic_usage.md"
        "advanced_usage.md"
      ],
      "API" => [
        "Types" => "api_types.md"
        "Functions" => "api_functions.md"
      ],
      "Contributing" => "contributing.md",
    ],
)

deploydocs(
    repo = "github.com/alinski29/Stonks.jl.git",
    target = "build",
    deps = nothing,
    make = nothing,
    devbranch = "main"
)


text:
@defstruct PoolingLayer Layer (
  name :: AbstractString = "pooling",
  (bottoms :: Vector{Symbol} = Symbol[], length(bottoms) > 0),
  (tops :: Vector{Symbol} = Symbol[], length(tops) == length(bottoms)),
  (kernel :: NTuple{2, Int} = (1,1), all(broadcast(>, [kernel...], 0))),
  (stride :: NTuple{2, Int} = (1,1), all(broadcast(>, [stride...], 0))),
  (pad :: NTuple{2, Int} = (0,0), all(broadcast(>=, [pad...], 0))),
  pooling :: PoolingFunction = Pooling.Max(),
  neuron :: ActivationFunction = Neurons.Identity(),
)
@characterize_layer(PoolingLayer,
  can_do_bp  => true,
  has_neuron => true
)

type PoolingLayerState <: LayerState
  layer      :: PoolingLayer
  blobs      :: Vector{Blob}
  blobs_diff :: Vector{Blob}

  etc        :: Any
end

function setup_etc(backend::CPUBackend, layer::PoolingLayer, inputs,
    pooled_width, pooled_height)

  if isa(layer.pooling, Pooling.Max)
    masks = Array{Array}(length(inputs))
    for i = 1:length(inputs)
      width,height,channels,num = size(inputs[i])
      masks[i] = Array{Csize_t}(pooled_width[i], pooled_height[i], channels, num)
    end
    etc = masks
  else
    etc = nothing
  end
  return etc
end

function setup(backend::Backend, layer::PoolingLayer, inputs::Vector{Blob}, diffs::Vector{Blob})
  blobs = Array{Blob}(length(inputs))
  blobs_diff = Array{Blob}(length(inputs))
  pw_all = Array{Int}(length(inputs))
  ph_all = Array{Int}(length(inputs))
  for i = 1:length(inputs)
    width,height,channels,num = size(inputs[i])

    pooled_width  = round(Int, ceil(float(width +2*layer.pad[1]-layer.kernel[1]) / layer.stride[1]))+1
    pooled_height = round(Int, ceil(float(height+2*layer.pad[2]-layer.kernel[2]) / layer.stride[2]))+1

    # make sure the last pooling is not purely pooling padded area
    if layer.pad[1] > 0 || layer.pad[2] > 0
      if ((pooled_height-1) * layer.stride[2] >= height + layer.pad[2])
        pooled_height -= 1
      end
      if ((pooled_width-1) * layer.stride[1] >= width + layer.pad[1])
        pooled_width -= 1
      end
    end

    dtype = eltype(inputs[i])

    blobs[i] = make_blob(backend,dtype, (pooled_width,pooled_height,channels,num))
    if isa(diffs[i], NullBlob)
      blobs_diff[i] = NullBlob() # don't need back propagation unless bottom layer want
    else
      blobs_diff[i] = make_blob(backend,dtype, (pooled_width,pooled_height,channels,num))
    end

    pw_all[i] = pooled_width
    ph_all[i] = pooled_height
  end

  etc = setup_etc(backend, layer, inputs, pw_all, ph_all)
  state = PoolingLayerState(layer, blobs, blobs_diff, etc)
end
function shutdown(backend::CPUBackend, state::PoolingLayerState)
  map(destroy, state.blobs)
  map(destroy, state.blobs_diff)
end

function forward(backend::CPUBackend, state::PoolingLayerState, inputs::Vector{Blob})
  forward(backend, state.layer.pooling, state, inputs)
end

function forward(backend::CPUBackend, pool::StdPoolingFunction, state::PoolingLayerState, inputs::Vector{Blob})
  for i = 1:length(inputs)
    input = inputs[i].data
    output = state.blobs[i].data

    if isa(pool, Pooling.Max)
      max_pooling_forward(input, output, state.etc[i], state.layer)
    elseif isa(pool, Pooling.Mean)
      mean_pooling_forward(input, output, state.layer)
    end
  end
end

function backward(backend::CPUBackend, state::PoolingLayerState, inputs::Vector{Blob}, diffs::Vector{Blob})
  backward(backend, state.layer.pooling, state, inputs, diffs)
end

function backward(backend::CPUBackend, pool::StdPoolingFunction, state::PoolingLayerState,
    inputs::Vector{Blob}, diffs::Vector{Blob})

  for i = 1:length(inputs)
    diff = diffs[i]
    if !isa(diff, NullBlob)
      if isa(pool, Pooling.Max)
        max_pooling_backward(diff.data, state.blobs_diff[i].data, state.etc[i], state.layer)
      elseif isa(pool, Pooling.Mean)
        mean_pooling_backward(diff.data, state.blobs_diff[i].data, state.layer)
      end
    end
  end
end


text:
import TimeZones: TimeZone, localzone
import Mocking: @patch, apply
import Base: AbstractCmd
import Compat: is_apple, is_windows, is_linux, readstring

# For mocking make sure we are actually changing the time zone
name = string(localzone()) == "Europe/Warsaw" ? "Pacific/Apia" : "Europe/Warsaw"

tzfile_path = joinpath(TZFILE_DIR, split(name, '/')...)
@assert isfile(tzfile_path) "Tests require a local tzfile present"
win_name = name == "Europe/Warsaw" ? "Central European Standard Time" : "Samoa Standard Time"
timezone = TimeZone(name)

if is_apple()
    # Determine time zone via systemsetup.
    patch = @patch readstring(cmd::AbstractCmd) = "Time Zone:  " * name * "\n"
    apply(patch) do
        @test localzone() == timezone
    end

    # Determine time zone from /etc/localtime.
    patches = [
        @patch readstring(cmd::AbstractCmd) = ""
        @patch readlink(filename::AbstractString) = "/usr/share/zoneinfo/$name"
    ]
    apply(patches) do
        @test localzone() == timezone
    end

elseif is_windows()
    patch = @patch readstring(cmd::AbstractCmd) = "$win_name\r\n"
    apply(patch) do
        @test localzone() == timezone
    end

    # Dateline Standard Time -> Etc/GMT+12 -> UTC-12:00

elseif is_linux()
    # Test TZ environmental variable
    withenv("TZ" => ":$name") do
        @test localzone() == timezone
    end

    withenv("TZ" => nothing) do
        # Determine time zone from /etc/timezone
        patches = [
            @patch isfile(f::AbstractString) = f == "/etc/timezone"
            @patch open(fn::Function, f::AbstractString) = fn(IOBuffer("$name #Works with comments\n"))
        ]
        apply(patches) do
            @test localzone() == timezone
        end

        # Determine time zone from /etc/conf.d/clock
        patches = [
            @patch isfile(f::AbstractString) = f == "/etc/conf.d/clock"
            @patch open(fn::Function, f::AbstractString) = fn(IOBuffer("\n\nTIMEZONE=\"$name\""))
        ]
        apply(patches) do
            @test localzone() == timezone
        end

        # Determine time zone from symlink /etc/localtime
        patches = [
            @patch isfile(f::AbstractString) = false
            @patch islink(f::AbstractString) = f == "/etc/localtime"
            @patch readlink(f::AbstractString) = "/usr/share/zoneinfo/$name"
        ]
        apply(patches) do
            @test localzone() == timezone
        end

        # Determine time zone from contents of /etc/localtime
        tz_from_file = open(tzfile_path) do f
            TimeZones.read_tzfile(f, "local")
        end

        patches = [
            @patch isfile(f::AbstractString) = f == "/etc/localtime"
            @patch islink(f::AbstractString) = false
            @patch open(fn::Function, f::AbstractString) = fn(open(tzfile_path))
        ]
        apply(patches) do
            @test localzone() == tz_from_file
        end

        # Unable to determine time zone
        patches = [
            @patch isfile(f::AbstractString) = false
            @patch islink(f::AbstractString) = false
        ]
        apply(patches) do
            @test_throws ErrorException localzone()
        end
    end
end


text:
function production(r::Recipe, nfacs)
	if nfacs == 0 return end
	@printf "%s: %d\n" r.name nfacs
	@printf "\tProduces\n"
	for (k,v) in r.outs
		@printf "\t\t%0.2f \"%s\" per min - %0.2f per second\n" 60v * nfacs k v * nfacs
	end
	@printf "\tConsumes\n"
	for (k,v) in r.ins
		@printf "\t\t%0.2f \"%s\" per min - %0.2f per second\n" 60v * nfacs k v * nfacs
	end
end

macro RIN(iname, iqty)
	return quote
		recipe.ins[$iname] = $iqty / recipe.time
	end
end

macro ROUT(iname, iqty)
	return quote
		recipe.outs[$iname] = $iqty / recipe.time
	end
end

max_stars_repo_name: lawless-m/factorio-utils

max_issues_repo_name: lawless-m/factorio-utils

max_forks_repo_name: lawless-m/factorio-utils


text:
# --- PRIVATE METHODS ---------------------------------------------------------------------------------------- #
function parse_gene_seq(gene_seq::String)

    # We will return a dictionary w/nucleotide keys and the number of nucleotides as values -
    nucleotide_dictionary = Dict();
    nucleotide_dictionary["a"] = 0;
    nucleotide_dictionary["t"] = 0;
    nucleotide_dictionary["g"] = 0;
    nucleotide_dictionary["c"] = 0;

    # What is the length of the gene sequence -
    number_of_nucleotides = length(gene_seq);

    for nucleotide_index = collect(1:number_of_nucleotides)

      # get the test nucleotide -
      test_nucleotide = gene_seq[nucleotide_index];
      if (test_nucleotide == 'a')
        value = nucleotide_dictionary["a"];
        nucleotide_dictionary["a"] = value + 1;
      end

      if (test_nucleotide == 't')
        value = nucleotide_dictionary["t"];
        nucleotide_dictionary["t"] = value + 1;
      end

      if (test_nucleotide == 'g')
        value = nucleotide_dictionary["g"];
        nucleotide_dictionary["g"] = value + 1;
      end

      if (test_nucleotide == 'c')
        value = nucleotide_dictionary["c"];
        nucleotide_dictionary["c"] = value + 1;
      end
    end

    # return -
    return nucleotide_dictionary;
end

function parse_protein_seq(protein_seq::String)
end

function compute_sequence_length(local_sequence)

  # initialize -
  sequence_count = 0

  # iterate through the array, don't count \n
  for nucleotide in local_sequence
    if (nucleotide != '\n')
      sequence_count = sequence_count + 1
    end
  end

  # return -
  return sequence_count
end

function build_translation_reaction_buffer_for_protein_sequence(protein_name::String, enzymeSymbol::String, protein_seq::String, configuration_dictionary::Dict{String,Any})

    # get default values for biological types -
    MRNA_type = configuration_dictionary["mRNA_type_prefix"]
    TRNA_type = configuration_dictionary["tRNA_type_prefix"]
    GENE_type = configuration_dictionary["gene_type_prefix"]
    PROTEIN_type = configuration_dictionary["protein_type_prefix"]

    # Load the AA symbol map -
    path_to_mapping_file = joinpath(path_to_package,"configuration/aa_map.csv")
    map_array = readdlm(path_to_mapping_file,','); #metabolite 1, one letter 2
    protein_aa_dictionary = Dict();

    # Create a mapping dictionary -
    symbol_metabolite_map = Dict();
    for map_index in collect(1:20)

      one_letter_aa_symbol = map_array[map_index,2];
      metabolite_symbol = map_array[map_index,1];
      symbol_metabolite_map[one_letter_aa_symbol] = metabolite_symbol;
      protein_aa_dictionary[metabolite_symbol] = 0.0;
    end

    # Parse the protein seq -
    number_aa_residues = length(protein_seq);
    local_counter = 0;
    for aa_index in collect(1:number_aa_residues)

      # What AA do we have?
      aa_value = string(protein_seq[aa_index]);
      if (aa_value != "\n" && aa_value != " ")

        key = symbol_metabolite_map[aa_value];

        # Update the dictionary -
        quantity_aa = protein_aa_dictionary[key];
        protein_aa_dictionary[key] = quantity_aa + 1;
        local_counter+=1;
      end
    end

    # Ok, we have the protein sequence , build the reaction string buffer -
    buffer="";
    buffer*="translation_initiation_$(protein_name),[],$(MRNA_type)_$(protein_name)+$(enzymeSymbol),$(enzymeSymbol)_START_$(protein_name),false\n"
    buffer*="translation_$(protein_name),[],$(enzymeSymbol)_START_$(protein_name)+$(2*local_counter)*M_gtp_c+$(2*local_counter)*M_h2o_c";
    for aa_index in collect(1:20)

      # Get charged tRNA -
      metabolite_symbol = map_array[aa_index,1];

      # number of this AA -
      value = protein_aa_dictionary[metabolite_symbol];

      # Add charged tRNA species to buffer -
      buffer*="+$(value)*$(metabolite_symbol)_$(TRNA_type)";
    end

    # products -
    buffer*=",$(enzymeSymbol)+$(MRNA_type)_$(protein_name)+$(PROTEIN_type)_$(protein_name)+$(2*local_counter)*M_gdp_c+$(2*local_counter)*M_pi_c+$(local_counter)*$(TRNA_type),false\n"

    # Write the reactions for charing the tRNA -
    for aa_index in collect(1:20)

      # Get charged tRNA -
      metabolite_symbol = map_array[aa_index,1];

      # number of this AA -
      value = protein_aa_dictionary[metabolite_symbol];

      # Add charged tRNA species to buffer -
      buffer*="$(TRNA_type)_charging_$(metabolite_symbol)_$(protein_name),[],$(value)*$(metabolite_symbol)+$(value)*M_atp_c+$(value)*$(TRNA_type)+$(value)*M_h2o_c,";
      buffer*="$(value)*$(metabolite_symbol)_$(TRNA_type)+$(value)*M_amp_c+$(value)*M_ppi_c,false\n";
    end

    return buffer;
end

function build_transcription_reaction_buffer_for_gene_sequence(gene_name::String, enzymeSymbol::String, gene_seq::String, configuration_dictionary::Dict{String,Any})

    # get default values for biological types -
    MRNA_type = configuration_dictionary["mRNA_type_prefix"]
    TRNA_type = configuration_dictionary["tRNA_type_prefix"]
    GENE_type = configuration_dictionary["gene_type_prefix"]
    PROTEIN_type = configuration_dictionary["protein_type_prefix"]

    # function variables -
    buffer= "";
    total_ntp = 0;

    # generate the sequence dictionary -
    nucleotide_dictionary = parse_gene_seq(gene_seq);

    # write the RNAP binding step -
    buffer*="transcriptional_initiation_$(gene_name),[],$(GENE_type)_$(gene_name)+$(enzymeSymbol),$(enzymeSymbol)_OPEN_$(GENE_type)_$(gene_name),false\n";
    buffer*="transcription_$(gene_name),[],$(enzymeSymbol)_OPEN_$(GENE_type)_$(gene_name)";

    # go through by dictionary, and get the base count -
    for (key,value) in nucleotide_dictionary

      if (key == "a")

        # write the M_atp_c line -
        buffer*="+$(value)*M_atp_c"

        # How many a's do we have?
        total_ntp += value;

      elseif (key == "t")

        # write the M_utp_c line -
        buffer*="+$(value)*M_utp_c"

        # How many u's do we have?
        total_ntp += value;

      elseif (key == "g")

        # write the M_gtp_c line -
        buffer*="+$(value)*M_gtp_c"

        # How many g's do we have?
        total_ntp += value;

      else

        # write the M_gtp_c line -
        buffer*="+$(value)*M_ctp_c"

        # How many c's do we have?
        total_ntp += value;
      end
    end

    # mRNA+GENE+RNAP+1320*M_pi_c,0,inf;
    buffer*="+$(total_ntp)*M_h2o_c,$(MRNA_type)_$(gene_name)+$(GENE_type)_$(gene_name)+$(enzymeSymbol)+$(total_ntp)*M_ppi_c,false\n"

    # mRNA_decay degradation reaction -
    # mRNA_decay,[],mRNA,144*M_cmp_c+151*M_gmp_c+189*M_ump_c+176*M_amp_c,0,inf;
    buffer*="$(MRNA_type)_degradation_$(gene_name),[],$(MRNA_type)_$(gene_name),"
    local_buffer = "";
    for (key,value) in nucleotide_dictionary

      if (key == "a")

        # write the M_atp_c line -
        local_buffer*="+$(value)*M_amp_c"

      elseif (key == "t")

        # write the M_utp_c line -
        local_buffer*="+$(value)*M_ump_c"

      elseif (key == "g")

        # write the M_gtp_c line -
        local_buffer*="+$(value)*M_gmp_c"

      else

        # write the M_gtp_c line -
        local_buffer*="+$(value)*M_cmp_c"

      end
    end

    buffer*="$(local_buffer[2:end]),false\n"

    # dump -
    # outfile = open("./transcription_$(gene_name).txt", "w")
    # write(outfile,buffer);
    # close(outfile);

    # return the buffer -
    return buffer;
end
# ----------------------------------------------------------------------------------------------------------- #

max_stars_repo_name: varnerlab/CFMG

max_issues_repo_name: varnerlab/CFMG

max_forks_repo_name: varnerlab/CFMG


text:
using SVG
using Test

function wtest()
    z = IOBuffer()
    write(z, Svg([Circle(0,1,1), Line(0,1,1,2), Polyline([0,1,2], [3,4,5])]), 10, 10)
    seek(z, 0)
    read(z, String) == "<svg width=\"10\" height=\"10\">\n<circle cx=\"0\" cy=\"1\" r=\"1\" style=\"fill:none;stroke:black;stroke-width:1.0\" />\n<line x1=\"0\" y1=\"1\" x2=\"1\" y2=\"2\" style=\"fill:none;stroke:black;stroke-width:1.0\" />\n<polyline points=\"0,3 1,4 2,5 \" style=\"fill:none;stroke:black;stroke-width:1.0\" />\n</svg>\n"
end

@testset "SVG.jl" begin
#==
   @test bounds(Circle(0,1,1)) == (xmin=-1, xmax=1, ymin=0, ymax=2)
   @test bounds(Line(0,1,1,2)) == (xmin=0, xmax=1, ymin=1, ymax=2)
   @test bounds(Polyline([0,1,2], [3,4,5])) == (xmin=0, xmax=2, ymin=3, ymax=5)
   @test bounds(Polyline([(0,3), (1,4), (2,5)]) == (xmin=0, xmax=2, ymin=3, ymax=5)
   @test bounds(Svg([Circle(0,1,1), Line(0,1,1,2), Polyline([0,1,2], [3,4,5])])) == (xmin=-1, xmax=2, ymin=0, ymax=5)
==#
   @test Polyline([0,1,2], [3,4,5]) == Polyline([(0,3), (1,4), (2,5)])
   @test wtest()

end

max_stars_repo_name: lawless-m/jsvg

max_issues_repo_name: lawless-m/jsvg

max_forks_repo_name: lawless-m/jsvg