text:
module evaluations
using LinearAlgebra
using ..matrices,..layers,..ft2d,..grid
export prepare_source,a2p,absorption,field_expansion,stackamp

#just slices a vector e in half
function slicehalf(e)
    mylength=convert(Int64,length(e)/2)
    return e[1:mylength],e[mylength+1:end]
end

#create normalized source vector depending on propagation modes and grid size
function prepare_source(kinc,Wref,Nx,Ny)
    #the total number of scattering states
    width=(Nx*2+1)*(Ny*2+1)
    #vertical
    normal=[0,0,1]
    #te polarization E-field is perpendicular with z-axis and propagation direction (so, parallel with surface)
    kte=cross(normal,kinc)/norm(cross(normal,kinc))
    #tm polarization E-field is perpendicular with te and propagation direction (so, not necessarily parallel with surface)
    ktm=cross(kinc,kte)/norm(cross(kinc,kte))

    esource=zeros(width*2)*1im
    esource[convert(Int64,(width+1)/2)]=kte[1]
    esource[convert(Int64,(width+1)/2)+width]=kte[2]
    a0te=Wref\esource

    esource=zeros(width*2)*1im
    esource[convert(Int64,(width+1)/2)]=ktm[1]
    esource[convert(Int64,(width+1)/2)+width]=ktm[2]
    a0tm=Wref\esource#/sqrt(epsref)
    return a0te,a0tm
end

#convert amplitude vector to electric field
function a2e2(a,W)
    e=W*a
    ex,ey=slicehalf(e)
    return ex,ey
end

#convert amplitude vector to electric field
function a2e(a,W,Kx,Ky,Kz)
    e=W*a
    ex,ey=slicehalf(e)
    ez=-Kz\(Kx*ex+Ky*ey)
    return ex,ey,ez
end

#convert electric field to total power
function e2p(ex,ey,ez,Kz,kz0)
    P=abs.(ex).^2+abs.(ey).^2+abs.(ez).^2
    P=sum(real.(Kz)*P/real(kz0))
    return P
end

#convert amplitude vector to total power
function a2p(a,W,Kx,Ky,Kz,kz0)
    ex,ey,ez=a2e(a,W,Kx,Ky,Kz)
    return e2p(ex,ey,ez,Kz,kz0)
end

#convert amplitude vector to total power
function a2p(a,h::Halfspace,Kx,Ky,kz0)
    return a2p(a,h.W,Kx,Ky,h.Kz,kz0)
end

#compute the amplitudes before and after a layer in the stack
function stackamp(Sup,S,Slo,a0)
    Sbefore=Sup
    Safter=concatenate(S,Slo)
    ain=(I-Sbefore.S22*Safter.S11)\(Sbefore.S21*a0)
    bout=(I-Safter.S11*Sbefore.S22)\(Safter.S11*Sbefore.S21*a0)

    Sbefore=concatenate(Sup,S)
    Safter=Slo
    aout=(I-Sbefore.S22*Safter.S11)\(Sbefore.S21*a0)
    bin=(I-Safter.S11*Sbefore.S22)\(Safter.S11*Sbefore.S21*a0)
    return ain,aout,bin,bout
end

#compute the absorption in one layer within the stack
#not working properly, better use the alternative method
function absorption(Sabove,Sint,Sbelow,a0,W0,Kx,Ky,Kz0,kz0)
    #compute amplitudes before and after layer
    ain,aout,bin,bout=stackamp(Sabove,Sint,Sbelow,a0)
    #Power entering the layer
    pin=a2p(ain,W0,Kx,Ky,Kz0,kz0)+a2p(bin,W0,Kx,Ky,Kz0,kz0)
    #power leaving the layer
    pout=a2p(aout,W0,Kx,Ky,Kz0,kz0)+a2p(bout,W0,Kx,Ky,Kz0,kz0)
    return pin-pout
end

#compute the field expansion in a layer using fourier transform
function field_expansion(ain,aout,bin,bout,layer,V0,zpoints,Kx,Ky,Kz,k0,nx,ny,realgrid)
    W0*I+0*V0
    #create empty vector for result
    efield=zeros(size(realgrid.x,1),size(realgrid.y,2),zpoints,3)*1im
    hfield=zeros(size(realgrid.x,1),size(realgrid.y,2),zpoints,3)*1im
    #compute the waves transmitted into the layer
    outside=Matrix([W0 W0;V0 -V0])
    inside=Matrix([layer.W+0*layer.V layer.W+0*layer.V;layer.V -layer.V])
    ain,bout=slicehalf(inside\outside*[ain;bout])
    aout,bin=slicehalf(inside\outside*[aout;bin])

    for zind=1:zpoints
        #propagation of the waves
        a=exp(Matrix(layer.q)*k0*layer.thi/zpoints*(zind-.5))*ain
        #b=exp(-Matrix(q)*k0*(zind-1))*bout
        b=exp(Matrix(layer.q)*k0*layer.thi/zpoints*(zpoints+.5-zind))*bin
        #convert amplitude vectors to electric fields
        ex,ey,ez=a2e(a+b,layer.W,Kx,Ky,Kz)
        hx,hy,hz=a2e(-a+b,layer.V,Kx,Ky,Kz)
        #convert from reciprocal lattice vectors to real space distribution
        efield[:,:,zind,1]=recipvec2real(nx,ny,ex,realgrid.x,realgrid.y)
        efield[:,:,zind,2]=recipvec2real(nx,ny,ey,realgrid.x,realgrid.y)
        efield[:,:,zind,3]=recipvec2real(nx,ny,ez,realgrid.x,realgrid.y)

        hfield[:,:,zind,1]=recipvec2real(nx,ny,hx,realgrid.x,realgrid.y)
        hfield[:,:,zind,2]=recipvec2real(nx,ny,hy,realgrid.x,realgrid.y)
        hfield[:,:,zind,3]=recipvec2real(nx,ny,hz,realgrid.x,realgrid.y)
end
    return efield,hfield
end

#experimental_unverified: Kz for structured layers
function Kzpatt(Kx,Ky,epsilon)
    Kz=sqrt.(Complex.(conj.(epsilon)-Kx*Kx-Ky*Ky))'
    return Kz
end

function kzpatt2(Kx,Ky,epsilon)
    eta=I/epsilon
    P=[Kx*eta*Ky I-Kx*eta*Kx;Ky*eta*Ky-I -Ky*eta*Kx]
    Q=[Kx*Ky epsilon-Kx*Kx;Ky*Ky-epsilon -Ky*Kx]
    ev=eigen(Matrix(P*Q))
    q=Diagonal(sqrt.(Complex.(ev.values)))

    return q[1:size(epsilon,1),1:size(epsilon,2)]/1im
end

#compute the absorption in one layer within the stack
#this is with transformation to real space and subsequent integration, unnecessary overhead, legacy
function absorption(Sabove,Sint,Sbelow,V0,nx,ny,a0,Nreal)

    #compute amplitudes before and after layer
    ain,aout,bin,bout=stackamp(Sabove,Sint,Sbelow,a0)
    #We need a real space meshgrid for the spatial Fourier transform
    realgrid=grid_xy_square(Nreal)
    W0=0*V0+I
    #poynting vector z component before layer
    ex,ey=a2e2(ain+bout,W0)
    hx,hy=a2e2(-ain+bout,V0)

    ex=recipvec2real(nx,ny,ex,realgrid.x,realgrid.y)
    ey=recipvec2real(nx,ny,ey,realgrid.x,realgrid.y)
    hx=recipvec2real(nx,ny,hx,realgrid.x,realgrid.y)
    hy=recipvec2real(nx,ny,hy,realgrid.x,realgrid.y)

    poynting=ex.*conj.(hy)-ey.*conj.(hx)
    #and after layer
    ex,ey=a2e2(aout+bin,W0)
    hx,hy=a2e2(-aout+bin,V0)

    ex=recipvec2real(nx,ny,ex,realgrid.x,realgrid.y)
    ey=recipvec2real(nx,ny,ey,realgrid.x,realgrid.y)
    hx=recipvec2real(nx,ny,hx,realgrid.x,realgrid.y)
    hy=recipvec2real(nx,ny,hy,realgrid.x,realgrid.y)

    poynting2=ex.*conj.(hy)-ey.*conj.(hx)
    #integrate, take imaginary part of difference
    return imag.(sum(poynting-poynting2)/Nreal/Nreal)
end

function absorption(Sabove,Sint,Sbelow,V0,a0,kz0)
    #compute amplitudes before and after layer
    ain,aout,bin,bout=stackamp(Sabove,Sint,Sbelow,a0)
    #W is just the identity matrix for unpatterned space
    W0=0*V0+I

    #in-plane fields "above" the layer
    ex,ey=a2e2(ain+bout,W0)
    hx,hy=a2e2(-ain+bout,V0)
    #imaginary part of the z-component of the poynting vector integrated over reciprocal space
    p1=imag(sum(ex.*conj.(hy)-ey.*conj.(hx)))/kz0

    #and "below" layer
    ex,ey=a2e2(aout+bin,W0)
    hx,hy=a2e2(-aout+bin,V0)
    p2=imag(sum(ex.*conj.(hy)-ey.*conj.(hx)))/kz0

    return p1-p2
end

end


text:
using FileIO

"""
    load(filename::File{format"MIDI"})
Read a file into a `MIDIFile` data type.

!!! note
    This function must not be called explicitly. [`FileIO.load`](https://juliaio.github.io/FileIO.jl/stable/) must be called instead.
"""
function load(f::File{format"MIDI"})
    open(f) do s
        skipmagic(s)
        midifile = load(s)
    end
end

function load(s::Stream{format"MIDI"})
    midifile = MIDIFile()

    # Skip the next four bytes - this is the header size, and it's always equal to 6.
    skip(s, 4)

    # Read the format code. 0 = single track, 1 = multiple tracks, 2 = multiple songs
    # Remember - MIDI files store data in big-endian format, which is why ntoh is used
    midifile.format = ntoh(read(s, UInt16))

    # Get the number of tracks and time division
    numberoftracks = ntoh(read(s, UInt16))
    midifile.tpq = ntoh(read(s, Int16))
    midifile.tracks = [readtrack(s.io) for x in 1:numberoftracks]

    midifile
end

"""
    save(filename::File{format"MIDI"}, data::MIDIFile)
Write a `MIDIFile` as a ".mid" file to the given filename.

    save(filename::File{format"MIDI"}, notes::Notes)
Create a `MIDIFile` directly from `notes`, using format 1.

!!! note
    This function must not be called explicitly. [`FileIO.save`](https://juliaio.github.io/FileIO.jl/stable/) must be called instead.
"""
function save(f::File{format"MIDI"}, data::MIDIFile)
    open(f, "w") do s
        save(s, data)
    end
end

function save(s::Stream{format"MIDI"}, data::MIDIFile)
    write(s, magic(format"MIDI"))

    write(s, hton(convert(UInt32, 6))) # Header length
    write(s, hton(data.format))
    write(s, hton(convert(UInt16, length(data.tracks))))
    write(s, hton(data.tpq))

    map(track->writetrack(s.io, track), data.tracks)
    return data
end

function save(s::Union{File{format"MIDI"}, Stream{format"MIDI"}}, notes::Notes)
    track = MIDITrack()
    addnotes!(track, notes)
    midi = MIDIFile(1, notes.tpq, [track])
    save(s, midi)
    return midi
end

ext: jl


text:
using SEP
using Base.Test
using FITSIO

# use test image in deps directory
datadir = joinpath(dirname(@__FILE__), "..", "deps", "src", "sep-1.0.0",
                   "data")

data = read(FITS(joinpath(datadir, "image.fits"))[1])
back_sextractor = read(FITS(joinpath(datadir, "back.fits"))[1])
rms_sextractor = read(FITS(joinpath(datadir, "rms.fits"))[1])

# test background
bkg = background(data)
println(bkg)

back = collect(bkg)
println(back ≈ back_sextractor)

for T in (Float32, Float64)
    A = zeros(T, size(data))
    back = collect(T, bkg)
    println(back ≈ back_sextractor)
end

A = zeros(Float32, size(data))
A .-= bkg

B = zeros(Float32, size(data))
B -= bkg
@test A ≈ B


text:
@defcomp TotalCosts begin

    # Per capita costs to aggregate
    abatement_costs_percap_peryear          = Parameter(index=[time, region], unit="\$/person") # Total abatement costs per capita per year
    adaptation_costs_percap_peryear         = Parameter(index=[time, region], unit="\$/person") # Total adaptation costs per capita per year
    slr_damages_percap_peryear              = Parameter(index=[time, region], unit="\$/person") # SLR damages per capita per year
    market_damages_percap_peryear           = Parameter(index=[time, region], unit="\$/person") # Market damages per capita per year
    non_market_damages_percap_peryear       = Parameter(index=[time, region], unit="\$/person") # Non market damages per capita per year
    discontinuity_damages_percap_peryear    = Parameter(index=[time, region], unit="\$/person") # Discontinuity damages per capita per year

    # other parameters
    population = Parameter(index=[time, region], unit="million person")
    period_length = Parameter(index=[time], unit="year")

    # Undiscounted costs to calculate

    total_damages_percap_peryear    = Variable(index=[time, region], unit="\$/person")  # Undiscounted total damages per capita per year
    total_damages_peryear           = Variable(index=[time, region], unit="\$million")  # Undiscounted total damages per year
    total_damages_aggregated        = Variable(index=[time, region], unit="\$million")  # Undiscounted total damages per period

    total_abatement_percap_peryear  = Variable(index=[time, region], unit="\$/person")  # Undiscounted total abatement per capita per year
    total_abatement_peryear         = Variable(index=[time, region], unit="\$million")  # Undiscounted total abatement per year
    total_abatement_aggregated      = Variable(index=[time, region], unit="\$million")  # Undiscounted total abatement per period

    total_costs_percap_peryear      = Variable(index=[time, region], unit="\$/person")  # Undiscounted total costs per capita per year (damages + abatement)
    total_costs_peryear             = Variable(index=[time, region], unit="\$million")  # Undiscounted total costs per year
    total_costs_aggregated          = Variable(index=[time, region], unit="\$million")  # Undiscounted total costs per period

    function run_timestep(p, v, d, t)

        # Damages
        v.total_damages_percap_peryear[t, :] =
            p.adaptation_costs_percap_peryear[t, :] +
            p.slr_damages_percap_peryear[t, :] +
            p.market_damages_percap_peryear[t, :] +
            p.non_market_damages_percap_peryear[t, :] +
            p.discontinuity_damages_percap_peryear[t, :]
        v.total_damages_peryear[t, :] = v.total_damages_percap_peryear[t, :] .* p.population[t, :]
        v.total_damages_aggregated[t, :] = v.total_damages_peryear[t, :] .* p.period_length[t]

        # Abatement
        v.total_abatement_percap_peryear[t, :] = p.abatement_costs_percap_peryear[t, :]
        v.total_abatement_peryear[t, :] = v.total_abatement_percap_peryear[t, :] .* p.population[t, :]
        v.total_abatement_aggregated[t, :] = v.total_abatement_peryear[t, :] .* p.period_length[t]

        # Total costs (damages + abatement)
        v.total_costs_percap_peryear[t, :] = v.total_damages_percap_peryear[t, :] + p.abatement_costs_percap_peryear[t, :]
        v.total_costs_peryear[t, :] = v.total_costs_percap_peryear[t, :] .* p.population[t, :]
        v.total_costs_aggregated[t, :] = v.total_costs_peryear[t, :] .* p.period_length[t]
    end
end


text:
export sdc

function sdc(p::NFFTPlan{D,0,T}; iters=20) where {D,T}
    # Weights for sample density compensation.
    # Uses method of Pipe & Menon, 1999. Mag Reson Med, 186, 179.
    weights = ones(Complex{T}, p.M)
    weights_tmp = similar(weights)
    # Pre-weighting to correct non-uniform sample density
    for i in 1:iters
        p.tmpVec[:] .= 0.0
        convolve_adjoint!(p, weights, p.tmpVec)
        weights_tmp[:] .= 0.0
        convolve!(p, p.tmpVec, weights_tmp)
        for j in 1:length(weights)
            weights[j] = weights[j] / (abs(weights_tmp[j]) + eps(T))
        end
    end
    # Post weights to correct image scaling
    # This finds c, where ||u - c*v||_2^2 = 0 and then uses
    # c to scale all weights by a scalar factor.
    u = ones(Complex{T}, p.N)
    f = nfft(p, u)
    f = f .* weights # apply weights from above
    v = nfft_adjoint(p, f)
    c = v[:] \ u[:]  # least squares diff
    abs.(weights * c[1]) # [1] needed b/c 'c' is a 1x1 Array
end


text:
# This code is part of QuantumCircuits.
#
# (C) Copyright Rafał Pracht 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

module OtherGates

using QuantumCircuits.QCircuits.QBase
using QuantumCircuits.QCircuits.Math
using QuantumCircuits.QCircuits.Gates
using QuantumCircuits.QCircuits.Gates: Parameter, Xmatrix, Zmatrix
using QuantumCircuits.QCircuits.Registers

import Base: show, length, inv
import QuantumCircuits.QCircuits.QBase: tomatrix, setparameters!, simplify,
       standardGateError, decompose

import QuantumCircuits.QCircuits.Gates: getqubits, getqubitsids, appendparams!,
       appendRandParams!, setparameters!, getArgs, decompose

export Rzx

"Rotation gates"
abstract type TwoQubitsRotationGate <: QuantumGate end

"Rotation macro"
macro twoQubitsRotationGate(name)
    eval(quote
        mutable struct $name <: TwoQubitsRotationGate
            qubit1::Qubit
            qubit2::Qubit
            θ::Parameter
        end
        $name(qubit1::Qubit, qubit2::Qubit) = $name(qubit1, qubit2, nothing)

        Base.:(==)(g1::$name, g2::$name) = g1.qubit1 == g2.qubit1 && g1.qubit2 == g2.qubit2 && g1.θ == g2.θ
        Base.hash(g::$name, h::UInt) = hash((g.qubit1, g.qubit2, g.θ), h)

        #$name(qubis::Vector{<:Integer}, θ::ParamT) = [$name(q, θ) for q in qubis]
        getArgs(g::$name) = (getid(g.qubit1), getid(g.qubit2), g.θ)

        inv(g::$name) = $name(g.qubit1, g.qubit2, -g.θ)
    end)
end

@twoQubitsRotationGate(Rzx)

"Return the qubits on which operate the gate"
getqubits(gate::TwoQubitsRotationGate) = (gate.qubit1, gate.qubit2)

"Return the qubits ids on which operate the gate"
getqubitsids(gate::TwoQubitsRotationGate) = (getid(gate.qubit1), getid(gate.qubit2))

Base.show(io::IO, gate::TwoQubitsRotationGate) = print(io, "$(typeof(gate))($(gate.qubit1), $(gate.qubit2), $(gate.θ))")

function appendparams!(param, gate::TwoQubitsRotationGate)
    @assert !isnothing(gate.θ) "Unable to append param without set it first."
    push!(param, gate.θ)
end

appendRandParams!(param, ::TwoQubitsRotationGate) = append!(param, rand(1) * 2π)

Base.length(gate::TwoQubitsRotationGate) = 1

function setparameters!(gate::TwoQubitsRotationGate, params)
    @assert length(params) == 1 "Rzx has 1 parameters but $(length(param)) was provided."
    @assert !isnothing(params[1]) "Unable to set nothing as parameters"
    gate.θ = params[1]
end

function tomatrix(g::Rzx, param=nothing)
    if isnothing(param)
        θ = g.θ
    else
        @assert length(param) == 1 "Rzx has 1 parameters but $(length(param)) was provided."
        θ = param[1]
    end

    q1 = getid(g.qubit1)
    q2 = getid(g.qubit2)
    Δ = abs(q1 - q2)

    if q1 < q2
        mat = kron(Xmatrix, eye(2^(Δ-1)), Zmatrix)
    else
        mat = kron(Zmatrix, eye(2^(Δ-1)), Xmatrix)
    end

    return exp(-im * (θ/2) * mat)
end

# function decompose(gate::U4)
#     return [
#         U3(gate.qubit1, gate.params[1], gate.params[2], gate.params[3]),
#         U3(gate.qubit2, gate.params[4], gate.params[5], gate.params[6]),
#         CX(gate.qubit2, gate.qubit1),
#         Rz(gate.qubit1, gate.params[7]),
#         Ry(gate.qubit2, gate.params[8]),
#         CX(gate.qubit1, gate.qubit2),
#         Ry(gate.qubit2, gate.params[9]),
#         CX(gate.qubit2, gate.qubit1),
#         U3(gate.qubit1, gate.params[10], gate.params[11], gate.params[12]),
#         U3(gate.qubit2, gate.params[13], gate.params[14], gate.params[15])
#     ]
# end

end  # module OtherGates


text:
using Plots

points = Tuple{Float64, Float64}[]

open(ARGS[1], "r") do file
  for line in readlines(file)
    text_values = split(line)
    values = map(x -> parse(Float64, x), text_values)
    push!(points, Tuple(values))
  end
end

gr()
scatter(points, label=["Frontier"], markersize=1)
savefig(ARGS[2])

max_stars_repo_name: Markhyz/Portfolio-Optimization

max_issues_repo_name: Markhyz/Portfolio-Optimization

max_forks_repo_name: Markhyz/Portfolio-Optimization


text:
_is_unregistered(dat::Dict) = haskey(dat, "repo-rev") || haskey(dat, "repo-url") || haskey(dat, "path")

function _find_unregistered_pkgs(pkgdir)
    manffile = filter(readdir(pkgdir; join = true)) do file
        basename(file) in Base.manifest_names
    end
    isempty(manffile) && return String[]
    manffile = first(manffile)
    devs = String[]
    manfdeps = TOML.parsefile(manffile)
    for (pkg, dat) in manfdeps
        dat = Dict(dat...)
        _is_unregistered(dat) && push!(devs, pkg)
    end
    return devs
end


text:
using ApproxInferenceBase
using Test
using Distributions
using Random

@testset "Factored" begin
    d=Factored(Uniform(0,1),Uniform(100,101))
    @test all((0,100) .<= rand(d) .<= (1,101))
    @test pdf(d,(0.0,0.0)) == 0.0
    @test pdf(d,(0.5,100.5)) == 1.0
    @test logpdf(d,(0.5,100.5)) == 0.0
    @test logpdf(d,(0.0,0.0)) == -Inf
    @test length(d) == 2
    m=Factored(Uniform(0.00,1.0),DiscreteUniform(1,2))
    sample=rand(m)
    @test 0<sample[1]<1
    @test sample[2] == 1 || sample[2] == 2
    @test pdf(m,sample) == 0.5
    @test logpdf(m,sample) ≈ log(0.5)
end


text:
import LinearAlgebra.tr

function tr(e::AbstractExpr)
    return sum(diag(e))
end


text:
# Julia wrapper for header: /Users/jgoldfar/Documents/misc/julia/Hypre/deps/usr/include/HYPRE_parcsr_ls.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function HYPRE_CSRMatrixCreate(num_rows::HYPRE_Int,num_cols::HYPRE_Int,row_sizes)
    ccall((:HYPRE_CSRMatrixCreate,libHypre),HYPRE_CSRMatrix,(HYPRE_Int,HYPRE_Int,Ptr{HYPRE_Int}),num_rows,num_cols,row_sizes)
end

function HYPRE_CSRMatrixDestroy(matrix::HYPRE_CSRMatrix)
    ccall((:HYPRE_CSRMatrixDestroy,libHypre),HYPRE_Int,(HYPRE_CSRMatrix,),matrix)
end

function HYPRE_CSRMatrixInitialize(matrix::HYPRE_CSRMatrix)
    ccall((:HYPRE_CSRMatrixInitialize,libHypre),HYPRE_Int,(HYPRE_CSRMatrix,),matrix)
end

function HYPRE_CSRMatrixRead(file_name)
    ccall((:HYPRE_CSRMatrixRead,libHypre),HYPRE_CSRMatrix,(Cstring,),file_name)
end

function HYPRE_CSRMatrixPrint(matrix::HYPRE_CSRMatrix,file_name)
    ccall((:HYPRE_CSRMatrixPrint,libHypre),Void,(HYPRE_CSRMatrix,Cstring),matrix,file_name)
end

function HYPRE_CSRMatrixGetNumRows(matrix::HYPRE_CSRMatrix,num_rows)
    ccall((:HYPRE_CSRMatrixGetNumRows,libHypre),HYPRE_Int,(HYPRE_CSRMatrix,Ptr{HYPRE_Int}),matrix,num_rows)
end

function HYPRE_ParCSRMatrixCreate(comm::MPI.Comm,global_num_rows::HYPRE_Int,global_num_cols::HYPRE_Int,row_starts,col_starts,num_cols_offd::HYPRE_Int,num_nonzeros_diag::HYPRE_Int,num_nonzeros_offd::HYPRE_Int,matrix)
    ccall((:HYPRE_ParCSRMatrixCreate,libHypre),HYPRE_Int,(MPI.Comm,HYPRE_Int,HYPRE_Int,Ptr{HYPRE_Int},Ptr{HYPRE_Int},HYPRE_Int,HYPRE_Int,HYPRE_Int,Ptr{HYPRE_ParCSRMatrix}),comm,global_num_rows,global_num_cols,row_starts,col_starts,num_cols_offd,num_nonzeros_diag,num_nonzeros_offd,matrix)
end

function HYPRE_ParCSRMatrixDestroy(matrix::HYPRE_ParCSRMatrix)
    ccall((:HYPRE_ParCSRMatrixDestroy,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,),matrix)
end

function HYPRE_ParCSRMatrixInitialize(matrix::HYPRE_ParCSRMatrix)
    ccall((:HYPRE_ParCSRMatrixInitialize,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,),matrix)
end

function HYPRE_ParCSRMatrixRead(comm::MPI.Comm,file_name,matrix)
    ccall((:HYPRE_ParCSRMatrixRead,libHypre),HYPRE_Int,(MPI.Comm,Cstring,Ptr{HYPRE_ParCSRMatrix}),comm,file_name,matrix)
end

function HYPRE_ParCSRMatrixPrint(matrix::HYPRE_ParCSRMatrix,file_name)
    ccall((:HYPRE_ParCSRMatrixPrint,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,Cstring),matrix,file_name)
end

function HYPRE_ParCSRMatrixGetComm(matrix::HYPRE_ParCSRMatrix,comm)
    ccall((:HYPRE_ParCSRMatrixGetComm,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,Ptr{MPI.Comm}),matrix,comm)
end

function HYPRE_ParCSRMatrixGetDims(matrix::HYPRE_ParCSRMatrix,M,N)
    ccall((:HYPRE_ParCSRMatrixGetDims,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,Ptr{HYPRE_Int},Ptr{HYPRE_Int}),matrix,M,N)
end

function HYPRE_ParCSRMatrixGetRowPartitioning(matrix::HYPRE_ParCSRMatrix,row_partitioning_ptr)
    ccall((:HYPRE_ParCSRMatrixGetRowPartitioning,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,Ptr{Ptr{HYPRE_Int}}),matrix,row_partitioning_ptr)
end

function HYPRE_ParCSRMatrixGetColPartitioning(matrix::HYPRE_ParCSRMatrix,col_partitioning_ptr)
    ccall((:HYPRE_ParCSRMatrixGetColPartitioning,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,Ptr{Ptr{HYPRE_Int}}),matrix,col_partitioning_ptr)
end

function HYPRE_ParCSRMatrixGetLocalRange(matrix::HYPRE_ParCSRMatrix,row_start,row_end,col_start,col_end)
    ccall((:HYPRE_ParCSRMatrixGetLocalRange,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,Ptr{HYPRE_Int},Ptr{HYPRE_Int},Ptr{HYPRE_Int},Ptr{HYPRE_Int}),matrix,row_start,row_end,col_start,col_end)
end

function HYPRE_ParCSRMatrixGetRow(matrix::HYPRE_ParCSRMatrix,row::HYPRE_Int,size,col_ind,values)
    ccall((:HYPRE_ParCSRMatrixGetRow,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,HYPRE_Int,Ptr{HYPRE_Int},Ptr{Ptr{HYPRE_Int}},Ptr{Ptr{HYPRE_Complex}}),matrix,row,size,col_ind,values)
end

function HYPRE_ParCSRMatrixRestoreRow(matrix::HYPRE_ParCSRMatrix,row::HYPRE_Int,size,col_ind,values)
    ccall((:HYPRE_ParCSRMatrixRestoreRow,libHypre),HYPRE_Int,(HYPRE_ParCSRMatrix,HYPRE_Int,Ptr{HYPRE_Int},Ptr{Ptr{HYPRE_Int}},Ptr{Ptr{HYPRE_Complex}}),matrix,row,size,col_ind,values)
end

function HYPRE_CSRMatrixToParCSRMatrix(comm::MPI.Comm,A_CSR::HYPRE_CSRMatrix,row_partitioning,col_partitioning,matrix)
    ccall((:HYPRE_CSRMatrixToParCSRMatrix,libHypre),HYPRE_Int,(MPI.Comm,HYPRE_CSRMatrix,Ptr{HYPRE_Int},Ptr{HYPRE_Int},Ptr{HYPRE_ParCSRMatrix}),comm,A_CSR,row_partitioning,col_partitioning,matrix)
end

function HYPRE_ParCSRMatrixMatvec(alpha::HYPRE_Complex,A::HYPRE_ParCSRMatrix,x::HYPRE_ParVector,beta::HYPRE_Complex,y::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRMatrixMatvec,libHypre),HYPRE_Int,(HYPRE_Complex,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_Complex,HYPRE_ParVector),alpha,A,x,beta,y)
end

function HYPRE_ParCSRMatrixMatvecT(alpha::HYPRE_Complex,A::HYPRE_ParCSRMatrix,x::HYPRE_ParVector,beta::HYPRE_Complex,y::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRMatrixMatvecT,libHypre),HYPRE_Int,(HYPRE_Complex,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_Complex,HYPRE_ParVector),alpha,A,x,beta,y)
end

function HYPRE_ParCSRParaSailsCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRParaSailsCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRParaSailsDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRParaSailsDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRParaSailsSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRParaSailsSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRParaSailsSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRParaSailsSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRParaSailsSetParams(solver::HYPRE_Solver,thresh::HYPRE_Real,nlevels::HYPRE_Int)
    ccall((:HYPRE_ParCSRParaSailsSetParams,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real,HYPRE_Int),solver,thresh,nlevels)
end

function HYPRE_ParCSRParaSailsSetFilter(solver::HYPRE_Solver,filter::HYPRE_Real)
    ccall((:HYPRE_ParCSRParaSailsSetFilter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,filter)
end

function HYPRE_ParCSRParaSailsSetSym(solver::HYPRE_Solver,sym::HYPRE_Int)
    ccall((:HYPRE_ParCSRParaSailsSetSym,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,sym)
end

function HYPRE_ParCSRParaSailsSetLoadbal(solver::HYPRE_Solver,loadbal::HYPRE_Real)
    ccall((:HYPRE_ParCSRParaSailsSetLoadbal,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,loadbal)
end

function HYPRE_ParCSRParaSailsSetReuse(solver::HYPRE_Solver,reuse::HYPRE_Int)
    ccall((:HYPRE_ParCSRParaSailsSetReuse,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,reuse)
end

function HYPRE_ParCSRParaSailsSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRParaSailsSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRPilutCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRPilutCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRPilutDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRPilutDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRPilutSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRPilutSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRPilutSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRPilutSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRPilutSetMaxIter(solver::HYPRE_Solver,max_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRPilutSetMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_iter)
end

function HYPRE_ParCSRPilutSetDropTolerance(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRPilutSetDropTolerance,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRPilutSetFactorRowSize(solver::HYPRE_Solver,size::HYPRE_Int)
    ccall((:HYPRE_ParCSRPilutSetFactorRowSize,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,size)
end

function HYPRE_ParCSRPCGCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRPCGCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRPCGDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRPCGDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRPCGSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRPCGSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRPCGSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRPCGSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRPCGSetTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRPCGSetTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRPCGSetAbsoluteTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRPCGSetAbsoluteTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRPCGSetMaxIter(solver::HYPRE_Solver,max_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRPCGSetMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_iter)
end

function HYPRE_ParCSRPCGSetStopCrit(solver::HYPRE_Solver,stop_crit::HYPRE_Int)
    ccall((:HYPRE_ParCSRPCGSetStopCrit,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,stop_crit)
end

function HYPRE_ParCSRPCGSetTwoNorm(solver::HYPRE_Solver,two_norm::HYPRE_Int)
    ccall((:HYPRE_ParCSRPCGSetTwoNorm,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,two_norm)
end

function HYPRE_ParCSRPCGSetRelChange(solver::HYPRE_Solver,rel_change::HYPRE_Int)
    ccall((:HYPRE_ParCSRPCGSetRelChange,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,rel_change)
end

function HYPRE_ParCSRPCGSetPrecond(solver::HYPRE_Solver,precond::HYPRE_PtrToParSolverFcn,precond_setup::HYPRE_PtrToParSolverFcn,precond_solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRPCGSetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver),solver,precond,precond_setup,precond_solver)
end

function HYPRE_ParCSRPCGGetPrecond(solver::HYPRE_Solver,precond_data)
    ccall((:HYPRE_ParCSRPCGGetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Solver}),solver,precond_data)
end

function HYPRE_ParCSRPCGSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRPCGSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRPCGSetPrintLevel(solver::HYPRE_Solver,print_level::HYPRE_Int)
    ccall((:HYPRE_ParCSRPCGSetPrintLevel,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,print_level)
end

function HYPRE_ParCSRPCGGetNumIterations(solver::HYPRE_Solver,num_iterations)
    ccall((:HYPRE_ParCSRPCGGetNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_iterations)
end

function HYPRE_ParCSRPCGGetFinalRelativeResidualNorm(solver::HYPRE_Solver,norm)
    ccall((:HYPRE_ParCSRPCGGetFinalRelativeResidualNorm,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,norm)
end

function HYPRE_ParCSRDiagScaleSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,y::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRDiagScaleSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,y,x)
end

function HYPRE_ParCSRDiagScale(solver::HYPRE_Solver,HA::HYPRE_ParCSRMatrix,Hy::HYPRE_ParVector,Hx::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRDiagScale,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,HA,Hy,Hx)
end

function HYPRE_ParCSRGMRESCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRGMRESCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRGMRESDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRGMRESDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRGMRESSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRGMRESSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRGMRESSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRGMRESSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRGMRESSetKDim(solver::HYPRE_Solver,k_dim::HYPRE_Int)
    ccall((:HYPRE_ParCSRGMRESSetKDim,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,k_dim)
end

function HYPRE_ParCSRGMRESSetTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRGMRESSetTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRGMRESSetAbsoluteTol(solver::HYPRE_Solver,a_tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRGMRESSetAbsoluteTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,a_tol)
end

function HYPRE_ParCSRGMRESSetMinIter(solver::HYPRE_Solver,min_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRGMRESSetMinIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,min_iter)
end

function HYPRE_ParCSRGMRESSetMaxIter(solver::HYPRE_Solver,max_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRGMRESSetMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_iter)
end

function HYPRE_ParCSRGMRESSetStopCrit(solver::HYPRE_Solver,stop_crit::HYPRE_Int)
    ccall((:HYPRE_ParCSRGMRESSetStopCrit,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,stop_crit)
end

function HYPRE_ParCSRGMRESSetPrecond(solver::HYPRE_Solver,precond::HYPRE_PtrToParSolverFcn,precond_setup::HYPRE_PtrToParSolverFcn,precond_solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRGMRESSetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver),solver,precond,precond_setup,precond_solver)
end

function HYPRE_ParCSRGMRESGetPrecond(solver::HYPRE_Solver,precond_data)
    ccall((:HYPRE_ParCSRGMRESGetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Solver}),solver,precond_data)
end

function HYPRE_ParCSRGMRESSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRGMRESSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRGMRESSetPrintLevel(solver::HYPRE_Solver,print_level::HYPRE_Int)
    ccall((:HYPRE_ParCSRGMRESSetPrintLevel,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,print_level)
end

function HYPRE_ParCSRGMRESGetNumIterations(solver::HYPRE_Solver,num_iterations)
    ccall((:HYPRE_ParCSRGMRESGetNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_iterations)
end

function HYPRE_ParCSRGMRESGetFinalRelativeResidualNorm(solver::HYPRE_Solver,norm)
    ccall((:HYPRE_ParCSRGMRESGetFinalRelativeResidualNorm,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,norm)
end

function HYPRE_ParCSRFlexGMRESCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRFlexGMRESCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRFlexGMRESDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRFlexGMRESDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRFlexGMRESSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRFlexGMRESSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRFlexGMRESSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRFlexGMRESSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRFlexGMRESSetKDim(solver::HYPRE_Solver,k_dim::HYPRE_Int)
    ccall((:HYPRE_ParCSRFlexGMRESSetKDim,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,k_dim)
end

function HYPRE_ParCSRFlexGMRESSetTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRFlexGMRESSetTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRFlexGMRESSetAbsoluteTol(solver::HYPRE_Solver,a_tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRFlexGMRESSetAbsoluteTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,a_tol)
end

function HYPRE_ParCSRFlexGMRESSetMinIter(solver::HYPRE_Solver,min_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRFlexGMRESSetMinIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,min_iter)
end

function HYPRE_ParCSRFlexGMRESSetMaxIter(solver::HYPRE_Solver,max_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRFlexGMRESSetMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_iter)
end

function HYPRE_ParCSRFlexGMRESSetPrecond(solver::HYPRE_Solver,precond::HYPRE_PtrToParSolverFcn,precond_setup::HYPRE_PtrToParSolverFcn,precond_solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRFlexGMRESSetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver),solver,precond,precond_setup,precond_solver)
end

function HYPRE_ParCSRFlexGMRESGetPrecond(solver::HYPRE_Solver,precond_data)
    ccall((:HYPRE_ParCSRFlexGMRESGetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Solver}),solver,precond_data)
end

function HYPRE_ParCSRFlexGMRESSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRFlexGMRESSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRFlexGMRESSetPrintLevel(solver::HYPRE_Solver,print_level::HYPRE_Int)
    ccall((:HYPRE_ParCSRFlexGMRESSetPrintLevel,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,print_level)
end

function HYPRE_ParCSRFlexGMRESGetNumIterations(solver::HYPRE_Solver,num_iterations)
    ccall((:HYPRE_ParCSRFlexGMRESGetNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_iterations)
end

function HYPRE_ParCSRFlexGMRESGetFinalRelativeResidualNorm(solver::HYPRE_Solver,norm)
    ccall((:HYPRE_ParCSRFlexGMRESGetFinalRelativeResidualNorm,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,norm)
end

function HYPRE_ParCSRFlexGMRESSetModifyPC(solver::HYPRE_Solver,modify_pc::HYPRE_PtrToModifyPCFcn)
    ccall((:HYPRE_ParCSRFlexGMRESSetModifyPC,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToModifyPCFcn),solver,modify_pc)
end

function HYPRE_ParCSRLGMRESCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRLGMRESCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRLGMRESDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRLGMRESDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRLGMRESSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRLGMRESSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRLGMRESSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRLGMRESSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRLGMRESSetKDim(solver::HYPRE_Solver,k_dim::HYPRE_Int)
    ccall((:HYPRE_ParCSRLGMRESSetKDim,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,k_dim)
end

function HYPRE_ParCSRLGMRESSetAugDim(solver::HYPRE_Solver,aug_dim::HYPRE_Int)
    ccall((:HYPRE_ParCSRLGMRESSetAugDim,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,aug_dim)
end

function HYPRE_ParCSRLGMRESSetTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRLGMRESSetTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRLGMRESSetAbsoluteTol(solver::HYPRE_Solver,a_tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRLGMRESSetAbsoluteTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,a_tol)
end

function HYPRE_ParCSRLGMRESSetMinIter(solver::HYPRE_Solver,min_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRLGMRESSetMinIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,min_iter)
end

function HYPRE_ParCSRLGMRESSetMaxIter(solver::HYPRE_Solver,max_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRLGMRESSetMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_iter)
end

function HYPRE_ParCSRLGMRESSetPrecond(solver::HYPRE_Solver,precond::HYPRE_PtrToParSolverFcn,precond_setup::HYPRE_PtrToParSolverFcn,precond_solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRLGMRESSetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver),solver,precond,precond_setup,precond_solver)
end

function HYPRE_ParCSRLGMRESGetPrecond(solver::HYPRE_Solver,precond_data)
    ccall((:HYPRE_ParCSRLGMRESGetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Solver}),solver,precond_data)
end

function HYPRE_ParCSRLGMRESSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRLGMRESSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRLGMRESSetPrintLevel(solver::HYPRE_Solver,print_level::HYPRE_Int)
    ccall((:HYPRE_ParCSRLGMRESSetPrintLevel,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,print_level)
end

function HYPRE_ParCSRLGMRESGetNumIterations(solver::HYPRE_Solver,num_iterations)
    ccall((:HYPRE_ParCSRLGMRESGetNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_iterations)
end

function HYPRE_ParCSRLGMRESGetFinalRelativeResidualNorm(solver::HYPRE_Solver,norm)
    ccall((:HYPRE_ParCSRLGMRESGetFinalRelativeResidualNorm,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,norm)
end

function HYPRE_ParCSRBiCGSTABCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRBiCGSTABCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRBiCGSTABDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRBiCGSTABDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRBiCGSTABSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRBiCGSTABSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRBiCGSTABSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRBiCGSTABSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRBiCGSTABSetTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRBiCGSTABSetTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRBiCGSTABSetAbsoluteTol(solver::HYPRE_Solver,a_tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRBiCGSTABSetAbsoluteTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,a_tol)
end

function HYPRE_ParCSRBiCGSTABSetMinIter(solver::HYPRE_Solver,min_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRBiCGSTABSetMinIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,min_iter)
end

function HYPRE_ParCSRBiCGSTABSetMaxIter(solver::HYPRE_Solver,max_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRBiCGSTABSetMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_iter)
end

function HYPRE_ParCSRBiCGSTABSetStopCrit(solver::HYPRE_Solver,stop_crit::HYPRE_Int)
    ccall((:HYPRE_ParCSRBiCGSTABSetStopCrit,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,stop_crit)
end

function HYPRE_ParCSRBiCGSTABSetPrecond(solver::HYPRE_Solver,precond::HYPRE_PtrToParSolverFcn,precond_setup::HYPRE_PtrToParSolverFcn,precond_solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRBiCGSTABSetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver),solver,precond,precond_setup,precond_solver)
end

function HYPRE_ParCSRBiCGSTABGetPrecond(solver::HYPRE_Solver,precond_data)
    ccall((:HYPRE_ParCSRBiCGSTABGetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Solver}),solver,precond_data)
end

function HYPRE_ParCSRBiCGSTABSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRBiCGSTABSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRBiCGSTABSetPrintLevel(solver::HYPRE_Solver,print_level::HYPRE_Int)
    ccall((:HYPRE_ParCSRBiCGSTABSetPrintLevel,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,print_level)
end

function HYPRE_ParCSRBiCGSTABGetNumIterations(solver::HYPRE_Solver,num_iterations)
    ccall((:HYPRE_ParCSRBiCGSTABGetNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_iterations)
end

function HYPRE_ParCSRBiCGSTABGetFinalRelativeResidualNorm(solver::HYPRE_Solver,norm)
    ccall((:HYPRE_ParCSRBiCGSTABGetFinalRelativeResidualNorm,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,norm)
end

function HYPRE_ParCSRHybridCreate(solver)
    ccall((:HYPRE_ParCSRHybridCreate,libHypre),HYPRE_Int,(Ptr{HYPRE_Solver},),solver)
end

function HYPRE_ParCSRHybridDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRHybridDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRHybridSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRHybridSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRHybridSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRHybridSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRHybridSetTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRHybridSetAbsoluteTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetAbsoluteTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRHybridSetConvergenceTol(solver::HYPRE_Solver,cf_tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetConvergenceTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,cf_tol)
end

function HYPRE_ParCSRHybridSetDSCGMaxIter(solver::HYPRE_Solver,dscg_max_its::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetDSCGMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,dscg_max_its)
end

function HYPRE_ParCSRHybridSetPCGMaxIter(solver::HYPRE_Solver,pcg_max_its::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetPCGMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,pcg_max_its)
end

function HYPRE_ParCSRHybridSetSetupType(solver::HYPRE_Solver,setup_type::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetSetupType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,setup_type)
end

function HYPRE_ParCSRHybridSetSolverType(solver::HYPRE_Solver,solver_type::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetSolverType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,solver_type)
end

function HYPRE_ParCSRHybridSetKDim(solver::HYPRE_Solver,k_dim::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetKDim,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,k_dim)
end

function HYPRE_ParCSRHybridSetTwoNorm(solver::HYPRE_Solver,two_norm::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetTwoNorm,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,two_norm)
end

function HYPRE_ParCSRHybridSetStopCrit(solver::HYPRE_Solver,stop_crit::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetStopCrit,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,stop_crit)
end

function HYPRE_ParCSRHybridSetRelChange(solver::HYPRE_Solver,rel_change::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetRelChange,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,rel_change)
end

function HYPRE_ParCSRHybridSetPrecond(solver::HYPRE_Solver,precond::HYPRE_PtrToParSolverFcn,precond_setup::HYPRE_PtrToParSolverFcn,precond_solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRHybridSetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver),solver,precond,precond_setup,precond_solver)
end

function HYPRE_ParCSRHybridSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRHybridSetPrintLevel(solver::HYPRE_Solver,print_level::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetPrintLevel,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,print_level)
end

function HYPRE_ParCSRHybridSetStrongThreshold(solver::HYPRE_Solver,strong_threshold::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetStrongThreshold,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,strong_threshold)
end

function HYPRE_ParCSRHybridSetMaxRowSum(solver::HYPRE_Solver,max_row_sum::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetMaxRowSum,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,max_row_sum)
end

function HYPRE_ParCSRHybridSetTruncFactor(solver::HYPRE_Solver,trunc_factor::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetTruncFactor,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,trunc_factor)
end

function HYPRE_ParCSRHybridSetPMaxElmts(solver::HYPRE_Solver,P_max_elmts::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetPMaxElmts,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,P_max_elmts)
end

function HYPRE_ParCSRHybridSetMaxLevels(solver::HYPRE_Solver,max_levels::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetMaxLevels,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_levels)
end

function HYPRE_ParCSRHybridSetMeasureType(solver::HYPRE_Solver,measure_type::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetMeasureType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,measure_type)
end

function HYPRE_ParCSRHybridSetCoarsenType(solver::HYPRE_Solver,coarsen_type::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetCoarsenType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,coarsen_type)
end

function HYPRE_ParCSRHybridSetInterpType(solver::HYPRE_Solver,interp_type::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetInterpType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,interp_type)
end

function HYPRE_ParCSRHybridSetCycleType(solver::HYPRE_Solver,cycle_type::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetCycleType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,cycle_type)
end

function HYPRE_ParCSRHybridSetGridRelaxType(solver::HYPRE_Solver,grid_relax_type)
    ccall((:HYPRE_ParCSRHybridSetGridRelaxType,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,grid_relax_type)
end

function HYPRE_ParCSRHybridSetGridRelaxPoints(solver::HYPRE_Solver,grid_relax_points)
    ccall((:HYPRE_ParCSRHybridSetGridRelaxPoints,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{Ptr{HYPRE_Int}}),solver,grid_relax_points)
end

function HYPRE_ParCSRHybridSetNumSweeps(solver::HYPRE_Solver,num_sweeps::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetNumSweeps,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,num_sweeps)
end

function HYPRE_ParCSRHybridSetCycleNumSweeps(solver::HYPRE_Solver,num_sweeps::HYPRE_Int,k::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetCycleNumSweeps,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int,HYPRE_Int),solver,num_sweeps,k)
end

function HYPRE_ParCSRHybridSetRelaxType(solver::HYPRE_Solver,relax_type::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetRelaxType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,relax_type)
end

function HYPRE_ParCSRHybridSetCycleRelaxType(solver::HYPRE_Solver,relax_type::HYPRE_Int,k::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetCycleRelaxType,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int,HYPRE_Int),solver,relax_type,k)
end

function HYPRE_ParCSRHybridSetRelaxOrder(solver::HYPRE_Solver,relax_order::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetRelaxOrder,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,relax_order)
end

function HYPRE_ParCSRHybridSetRelaxWt(solver::HYPRE_Solver,relax_wt::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetRelaxWt,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,relax_wt)
end

function HYPRE_ParCSRHybridSetLevelRelaxWt(solver::HYPRE_Solver,relax_wt::HYPRE_Real,level::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetLevelRelaxWt,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real,HYPRE_Int),solver,relax_wt,level)
end

function HYPRE_ParCSRHybridSetOuterWt(solver::HYPRE_Solver,outer_wt::HYPRE_Real)
    ccall((:HYPRE_ParCSRHybridSetOuterWt,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,outer_wt)
end

function HYPRE_ParCSRHybridSetLevelOuterWt(solver::HYPRE_Solver,outer_wt::HYPRE_Real,level::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetLevelOuterWt,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real,HYPRE_Int),solver,outer_wt,level)
end

function HYPRE_ParCSRHybridSetMaxCoarseSize(solver::HYPRE_Solver,max_coarse_size::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetMaxCoarseSize,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_coarse_size)
end

function HYPRE_ParCSRHybridSetMinCoarseSize(solver::HYPRE_Solver,min_coarse_size::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetMinCoarseSize,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,min_coarse_size)
end

function HYPRE_ParCSRHybridSetSeqThreshold(solver::HYPRE_Solver,seq_threshold::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetSeqThreshold,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,seq_threshold)
end

function HYPRE_ParCSRHybridSetRelaxWeight(solver::HYPRE_Solver,relax_weight)
    ccall((:HYPRE_ParCSRHybridSetRelaxWeight,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,relax_weight)
end

function HYPRE_ParCSRHybridSetOmega(solver::HYPRE_Solver,omega)
    ccall((:HYPRE_ParCSRHybridSetOmega,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,omega)
end

function HYPRE_ParCSRHybridSetAggNumLevels(solver::HYPRE_Solver,agg_num_levels::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetAggNumLevels,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,agg_num_levels)
end

function HYPRE_ParCSRHybridSetNumPaths(solver::HYPRE_Solver,num_paths::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetNumPaths,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,num_paths)
end

function HYPRE_ParCSRHybridSetNumFunctions(solver::HYPRE_Solver,num_functions::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetNumFunctions,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,num_functions)
end

function HYPRE_ParCSRHybridSetDofFunc(solver::HYPRE_Solver,dof_func)
    ccall((:HYPRE_ParCSRHybridSetDofFunc,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,dof_func)
end

function HYPRE_ParCSRHybridSetNodal(solver::HYPRE_Solver,nodal::HYPRE_Int)
    ccall((:HYPRE_ParCSRHybridSetNodal,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,nodal)
end

function HYPRE_ParCSRHybridGetNumIterations(solver::HYPRE_Solver,num_its)
    ccall((:HYPRE_ParCSRHybridGetNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_its)
end

function HYPRE_ParCSRHybridGetDSCGNumIterations(solver::HYPRE_Solver,dscg_num_its)
    ccall((:HYPRE_ParCSRHybridGetDSCGNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,dscg_num_its)
end

function HYPRE_ParCSRHybridGetPCGNumIterations(solver::HYPRE_Solver,pcg_num_its)
    ccall((:HYPRE_ParCSRHybridGetPCGNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,pcg_num_its)
end

function HYPRE_ParCSRHybridGetFinalRelativeResidualNorm(solver::HYPRE_Solver,norm)
    ccall((:HYPRE_ParCSRHybridGetFinalRelativeResidualNorm,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,norm)
end

function HYPRE_ParCSRHybridSetNumGridSweeps(solver::HYPRE_Solver,num_grid_sweeps)
    ccall((:HYPRE_ParCSRHybridSetNumGridSweeps,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_grid_sweeps)
end

function HYPRE_ParCSRCGNRCreate(comm::MPI.Comm,solver)
    ccall((:HYPRE_ParCSRCGNRCreate,libHypre),HYPRE_Int,(MPI.Comm,Ptr{HYPRE_Solver}),comm,solver)
end

function HYPRE_ParCSRCGNRDestroy(solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRCGNRDestroy,libHypre),HYPRE_Int,(HYPRE_Solver,),solver)
end

function HYPRE_ParCSRCGNRSetup(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRCGNRSetup,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRCGNRSolve(solver::HYPRE_Solver,A::HYPRE_ParCSRMatrix,b::HYPRE_ParVector,x::HYPRE_ParVector)
    ccall((:HYPRE_ParCSRCGNRSolve,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector),solver,A,b,x)
end

function HYPRE_ParCSRCGNRSetTol(solver::HYPRE_Solver,tol::HYPRE_Real)
    ccall((:HYPRE_ParCSRCGNRSetTol,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Real),solver,tol)
end

function HYPRE_ParCSRCGNRSetMinIter(solver::HYPRE_Solver,min_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRCGNRSetMinIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,min_iter)
end

function HYPRE_ParCSRCGNRSetMaxIter(solver::HYPRE_Solver,max_iter::HYPRE_Int)
    ccall((:HYPRE_ParCSRCGNRSetMaxIter,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,max_iter)
end

function HYPRE_ParCSRCGNRSetStopCrit(solver::HYPRE_Solver,stop_crit::HYPRE_Int)
    ccall((:HYPRE_ParCSRCGNRSetStopCrit,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,stop_crit)
end

function HYPRE_ParCSRCGNRSetPrecond(solver::HYPRE_Solver,precond::HYPRE_PtrToParSolverFcn,precondT::HYPRE_PtrToParSolverFcn,precond_setup::HYPRE_PtrToParSolverFcn,precond_solver::HYPRE_Solver)
    ccall((:HYPRE_ParCSRCGNRSetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver),solver,precond,precondT,precond_setup,precond_solver)
end

function HYPRE_ParCSRCGNRGetPrecond(solver::HYPRE_Solver,precond_data)
    ccall((:HYPRE_ParCSRCGNRGetPrecond,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Solver}),solver,precond_data)
end

function HYPRE_ParCSRCGNRSetLogging(solver::HYPRE_Solver,logging::HYPRE_Int)
    ccall((:HYPRE_ParCSRCGNRSetLogging,libHypre),HYPRE_Int,(HYPRE_Solver,HYPRE_Int),solver,logging)
end

function HYPRE_ParCSRCGNRGetNumIterations(solver::HYPRE_Solver,num_iterations)
    ccall((:HYPRE_ParCSRCGNRGetNumIterations,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Int}),solver,num_iterations)
end

function HYPRE_ParCSRCGNRGetFinalRelativeResidualNorm(solver::HYPRE_Solver,norm)
    ccall((:HYPRE_ParCSRCGNRGetFinalRelativeResidualNorm,libHypre),HYPRE_Int,(HYPRE_Solver,Ptr{HYPRE_Real}),solver,norm)
end


text:
using Documenter
using SatelliteDynamics
using SatelliteDynamics.EarthEnvironment
using SatelliteDynamics.Simulation

include("src/makeplots.jl")

# Generate documents
makedocs(
    modules   = [SatelliteDynamics, SatelliteDynamics.EarthEnvironment, SatelliteDynamics.Simulation],
    doctest   = false,
    clean     = true,
    linkcheck = true,
    format    = Documenter.HTML(),
    sitename  = "SatelliteDynamics.jl",
    authors   = "Duncan Eddy",
    pages     = Any[
        "Home" => "index.md",
        "Modules" => Any[
            "modules/constants.md",
            "modules/universe.md",
            "modules/time.md",
            "Reference Systems" => "modules/reference_systems.md",
            "modules/attitude.md",
            "modules/coordinates.md",
            "modules/astrodynamics.md",
            "Orbit Dynamics" => "modules/orbit_dynamics.md",
            "Earth Environment" => Any[
                "Space Weather" => "modules/earth_environment/space_weather.md",
                "NRLMSISE00" => "modules/earth_environment/nrlmsise00.md"
            ],
            "Simulation" => Any[
                "modules/simulation/integrators.md",
                "modules/simulation/propagators.md"
            ]
        ],
        "Tutorials" => Any[
            "tutorials/orbit_propagation_example.md",
        ],
        "Function Index" => "modules/function_index.md",
    ]
)

# Generate plots
# makeplots()

deploydocs(
    repo = "github.com/sisl/SatelliteDynamics.jl",
    devbranch = "master",
    devurl = "latest",
)


text:
module MXMLSynth

using LibSndFile
using PortAudio
using SampledSignals
using MusicXML
using DataStructures

no_smoother(L,t) = 1
quadratic_smoother(L,t) = t^2 / (L/10000 + t^2)
cubic_smoother(L,t) = t^3 / (L/100000 + t^3)

function createSmoother(asymm_smoother, L)
  return t -> asymm_smoother(L,t) * asymm_smoother(L,L-t)
end

exp_fader(L,t) = exp(-t/L)

function createFader(unscaled_fader, L)
  return t -> unscaled_fader(L, t)
end

function calcFrequency(pitch::MusicXML.Pitch)
  # calculate the number of half-steps from A440 = A4
  id = pitch.octave * 12 + Int(pitch.step) + pitch.alter
  nhalfsteps = id - 58
  return 440 * 2 ^ (nhalfsteps/12) + 10*(rand()-0.5)
end

function saveBuffer(fpath::String, sb::SampledSignals.SampleBuf)
  LibSndFile.save(fpath, sb)
end

function playBuffer(sb::SampledSignals.SampleBuf,
                    stream::PortAudio.PortAudioStream = PortAudioStream("default"))
  write(stream, SampledSignals.SampleBufSource(sb))
end

function mergeBuffers(buffers::Array{SampleBuf,1})
  if length(buffers) == 1
    return buffers[1]
  end
  # assume all buffers have same sample_rate
  sample_rate = buffers[1].samplerate
  len = max(collect(length(b) for b in buffers)...)
  accum = SampleBuf(zeros(len), sample_rate)
  for (i,b) in enumerate(buffers)
    println(length(b))
    # buffers are not always the same length (# of samples)
    # is this a bug?  workaround is to zero-pad the end of the short buffers
    temp = vcat(b, SampleBuf(zeros(len - length(b)), sample_rate))
    accum += temp
  end
  return accum
end

function synthesizeMXML(tree::MusicXML.MXMLTree,
                        sample_rate = 4.41e4,
                        bpm = 120*40,
                        smoothing_function = quadratic_smoother
                        )
  buffers = SampleBuf[]
  for part in tree.parts
    buffer = synthesizePart(part, sample_rate, bpm, smoothing_function)
    push!(buffers, buffer)
  end
  return mergeBuffers(buffers)
end

# Returns a SampledSignals.SampleBuf
function synthesizePart(part::MusicXML.Part,
                         sample_rate = 4.41e4,
                         bpm = 120*20,
                         smoothing_function = quadratic_smoother
                         )
  buffer = Float64[]
  smoother = createSmoother(smoothing_function, 10/sample_rate)
  fader = createFader(exp_fader, 1)
  component(k,f,t) = sin(k*pi/8) * sin.(2*pi*k*f*t) / k^2
  samples_per_beat = round(sample_rate * 60 / bpm)
  for measure in part.measures
    for note in measure.notes
      num_samples = round(Int, samples_per_beat * note.duration / 4);
      if note.isrest
        append!(buffer, zeros(Float64, num_samples))
      else
        note_length = num_samples / sample_rate
        t = linspace(0, note_length, num_samples)
        freq = calcFrequency(note.pitch)
        y = zeros(Float64, length(t))
        for k in 1:15
          y += component(k, freq, t)
        end
        y = y .* smoother.(t) .* fader(t)
        append!(buffer, y)
      end
    end
  end
  return SampleBuf(buffer, sample_rate)
end

end


text:
using Semaphores
using Test

function test_named_semaphore()
    @info("testing posix named semaphores")
    sem = NamedSemaphore("/testsem")
    close(sem)
    delete!(sem)
    sem = NamedSemaphore("/testsem", true, true)

    Sys.isapple() || (@test count(sem) == 1)

    lock(sem)
    Sys.isapple() || (@test count(sem) == 0)
    @test !trylock(sem)
    unlock(sem)
    Sys.isapple() || (@test count(sem) == 1)
    @test trylock(sem)
    Sys.isapple() || (@test count(sem) == 0)

    N = 10
    for idx in 1:N
        unlock(sem)
    end
    Sys.isapple() || (@test count(sem) == N)
    for idx in 1:N
        lock(sem)
    end
    Sys.isapple() || (@test count(sem) == 0)

    close(sem)
    delete!(sem)
end

function test_sysv_semaphore()
    @info("testing system v semaphores")
    tok = Semaphores.ftok(pwd(), 0)
    sem = Semaphores.semcreate(tok, 2)
    @test sem >= 0
    try
        @test 0 == Semaphores.semget(sem)

        a = Cushort[0,0]
        Semaphores.semset(sem, a)
        Semaphores.semget(sem, a)
        @test sum(a) == 0

        Semaphores.semset(sem, Cint(10))
        Semaphores.semset(sem, Cint(5), 1)
        Semaphores.semget(sem, a)
        @test a[1] == 10
        @test a[2] == 5

        a = Cushort[5,10]
        Semaphores.semset(sem, a)
        a = Cushort[0,0]
        Semaphores.semget(sem, a)
        @test a == Cushort[5,10]

        o = [Semaphores.SemBuf(0,1),Semaphores.SemBuf(1,1)]
        Semaphores.semop(sem, o)
        a = Cushort[0,0]
        Semaphores.semget(sem, a)
        @test a == Cushort[6,11]

        o = [Semaphores.SemBuf(0,-1),Semaphores.SemBuf(1,1)]
        Semaphores.semop(sem, o)
        a = Cushort[0,0]
        Semaphores.semget(sem, a)
        @test a == Cushort[5,12]
    finally
        Semaphores.semrm(sem)
    end
end

function test_resource_counter()
    @info("testing single resource counter")
    rescounter = ResourceCounter(pwd())
    try
        reset(rescounter, 1)
        @test count(rescounter,0) == 1
        reset(rescounter, [2])
        @test count(rescounter) == [2]
        change(rescounter, -1)
        @test count(rescounter,0) == 1
        change(rescounter, 2)
        @test count(rescounter) == [3]
        close(rescounter)
    finally
        delete!(rescounter)
    end

    @info("testing multiple resource counter")
    rescounter = ResourceCounter((pwd(),2), 2)
    try
        reset(rescounter, [1,2])
        @test count(rescounter,0) == 1
        @test count(rescounter,1) == 2
        reset(rescounter, [2,3])
        @test count(rescounter) == [2,3]
        change(rescounter, -1, 0)
        @test count(rescounter,0) == 1
        @test count(rescounter,1) == 3
        change(rescounter, 2, 1)
        @test count(rescounter) == [1,5]
        change(rescounter, [SemBuf(0,1),SemBuf(1,-3)])
        @test count(rescounter) == [2,2]
        close(rescounter)
    finally
        delete!(rescounter)
    end
end

test_named_semaphore()
test_sysv_semaphore()
test_resource_counter()


text:
# Import the compressed log file of a simulation (.csv.xz) and convert it to an arrow file that can be re-played
# by the KiteViewer.
#
# Available fields in the input (some of them contain arrays):
# time,azimuth,course,depower,elevation,force,heading,height,kite_distance,l_tether,position,prediction,set_force,steering,
#      sync_speed,system_state,time,time_rel,turn_rate,v_app,v_app_norm,v_reelout,vel_kite,yaw_angle

module Importer

using CodecXz, CSV, DataFrames, StaticArrays, StructArrays, Rotations, LinearAlgebra
include("./Utils.jl")
using .Utils

# Constants
const CSV_FILE = se().log_file * ".csv"

# Functions
function decompress(in, out)
    stream = open(in)
    output = open(out,"w")
    for line in eachline(XzDecompressorStream(stream))
        println(output, line)
    end
    close(stream)
    close(output)
end

function parse_array(pos)
    res = replace(pos, ['\n', ']', '['] => "")
    arr = parse.(MyFloat, split(res))
    arr = reshape(arr, (3, length(arr) ÷ 3))
end

function parse_vector(pos)
    res = replace(pos, [')', '('] => "")
    res = replace(res, ',' => " ")
    arr = parse.(MyFloat, split(res))
end

function getX(pos); return parse_array(pos)[1,:]; end
function getY(pos); return parse_array(pos)[2,:]; end
function getZ(pos); return parse_array(pos)[3,:]; end

# calculate the rotation matrix of the kite based on the position of the
# last two tether particles and the apparent wind speed vector
function rot(pos_kite, pos_before, v_app)
    delta = pos_kite - pos_before
    c = -delta
    z = normalize(c)
    y = normalize(cross(-v_app, c))
    x = normalize(cross(y, c))
    rot = rot3d([0,-1.0,0], [1.0,0,0], [0,0,-1.0], z, y, x)
end

function df2syslog(df)
    orient = MVector(1.0f0, 0, 0, 0)
    steps = size(df)[1]
    orient_vec = Vector{MVector{4, Float32}}(undef, steps)
    V_app = df.v_app
    for i in range(1, length=steps)
        pos_kite = [df.X[i][end], df.Y[i][end], df.Z[i][end]]
        pos_before = [df.X[i][end-1], df.Y[i][end-1], df.Z[i][end-1]]
        v_app = V_app[i]
        rotation = rot(pos_kite, pos_before, v_app)
        q = UnitQuaternion(rotation)
        orient_vec[i] = MVector{4, Float32}(q.w, q.x, q.y, q.z)
    end
    return StructArray{SysState}((df.time_rel, orient_vec, df.elevation, df.azimuth, df.l_tether, df.v_reelout, df.force, df.depower,
                                  df.v_app_norm, df.X*se().zoom, df.Y*se().zoom, df.Z*se().zoom))
end

function import_log()
    input_file = se().log_file * ".csv.xz"
    println("Importing file \"$input_file\" ...")
    decompress(input_file, CSV_FILE)

    # convert to DataFrame, cleanup, transform
    data = DataFrame(CSV.File(CSV_FILE, types=Dict(2=>Float32, 4=>Float32, 5=>Float32, 6=>Float32, 10=>Float32, 21=>Float32, 22=>Float32)))
    df = select(data, :time_rel, :position, :v_app => :v_app_str, :azimuth, :elevation, :force, :v_reelout, :depower, :v_app_norm, :l_tether)
    df[!, :X] = getX.(df.position)
    df[!, :Y] = getY.(df.position)
    df[!, :Z] = getZ.(df.position)
    df[!, :v_app] = parse_vector.(df.v_app_str)
    select!(df, Not(:position))
    select!(df, Not(:v_app_str))

    # convert to arrow format and save
    syslog = df2syslog(df)
    name = basename(CSV_FILE)[1:end-4]
    save_log(SysLog(name, syslog, syslog2extlog(syslog)))
    println("Saved file:    \"data/$name.arrow\" .")
    return data
end

# main program
import_log()

end
nothing


text:
# Maybe a fancy trick shot isn't the best idea; after all, you only have one
# probe, so you had better not miss.
#
# To get the best idea of what your options are for launching the probe, you
# need to find every initial velocity that causes the probe to eventually be
# within the target area after any step.
#
# In the above example, there are 112 different initial velocity values that
# meet these criteria:
#
# 23,-10  25,-9   27,-5   29,-6   22,-6   21,-7   9,0     27,-7   24,-5
# 25,-7   26,-6   25,-5   6,8     11,-2   20,-5   29,-10  6,3     28,-7
# 8,0     30,-6   29,-8   20,-10  6,7     6,4     6,1     14,-4   21,-6
# 26,-10  7,-1    7,7     8,-1    21,-9   6,2     20,-7   30,-10  14,-3
# 20,-8   13,-2   7,3     28,-8   29,-9   15,-3   22,-5   26,-8   25,-8
# 25,-6   15,-4   9,-2    15,-2   12,-2   28,-9   12,-3   24,-6   23,-7
# 25,-10  7,8     11,-3   26,-7   7,1     23,-9   6,0     22,-10  27,-6
# 8,1     22,-8   13,-4   7,6     28,-6   11,-4   12,-4   26,-9   7,4
# 24,-10  23,-8   30,-8   7,0     9,-1    10,-1   26,-5   22,-9   6,5
# 7,5     23,-6   28,-10  10,-2   11,-1   20,-9   14,-2   29,-7   13,-3
# 23,-5   24,-8   27,-9   30,-7   28,-5   21,-10  7,9     6,6     21,-5
# 27,-10  7,2     30,-9   21,-8   22,-7   24,-9   20,-6   6,9     29,-5
# 8,-2    27,-8   30,-5   24,-7
#
# How many distinct initial velocity values cause the probe to be within the
# target area after any step?

# read input
(targetx1, targetx2, targety1, targety2) = parse.(
  Int,
  match(
    r"x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)",
    readline("input.txt")
  )
)

# The sum of consecutive integers from 0 to n is n(n+1)/2. Using this, we can
# find the minimum possible starting x velocity by solving n(n+1)/2=targetx1-1.
# Anything equal to or less than that result will fall to a velocity of zero
# before reaching the target zone.
# n(n+1)/2=targetx1-1
# n^2 + n - 2*(targetx1-1) = 0
# n = (-b +- sqrt(b^2 - 4ac)) / 2a
minimum_xvel = floor(Int, sqrt(1 + 8 * (targetx1-1)) / 2)

# Our minimum starting y velocity is equal to the minimum target y because
# anything less than that will overshoot our target y on the very first step.
# See part 1 for an explanation of how to find the maximum starting y velocity.
#
# From a giving y velocity, we can determine how many steps it'll take to reach
# the target y. From that, we can find what x velocities will get us in the
# target x range. Then we increment our starting y velocity and do it again.
cnt = 0
for yvel in targety1:(abs(targety1)-1)
  inityvel = yvel

  # I feel like there's some mathematical way to calculate how many steps it'll
  # take to reach the target y zone with an initial y velocity, but I can't
  # brain it at the moment, so...
  steps = 0
  if yvel > 0
    # I did brain this little optimization: when our initial y velocity is
    # positive, it'll take 2*yvel+1 steps to get to a y position of 0, at which
    # point our velocity will be -yvel-1
    steps = 2 * yvel + 1
    yvel = -yvel - 1
  end

  # find the minimum number of steps required to reach the target y range
  # yvel is guaranteed non-positive at this point
  ypos = 0
  while ypos > targety2
    ypos += yvel
    yvel -= 1
    steps += 1
  end

  # a given initial y velocity may hit the target y range more than once - we
  # need to keep track of the x velocities we've already matched so we don't
  # count them again
  matched_x = Int[]
  while ypos >= targety1
    # Maximum x velocity is the point where steps(max+(max-steps+1))/2=targetx2
    # steps*max + steps*max - steps^2 + steps = 2*targetx2
    # 2*steps*max = 2*targetx2 + steps^2 - steps
    # max = targetx2/steps + steps/2 - 1/2
    # This isn't quite right, but my brain is done.
    for xvel in minimum_xvel:floor(Int, targetx2 / steps + steps / 2 - 0.5)
      initxvel = xvel
      xpos = 0
      for _ in 1:steps
        xpos += xvel
        xvel -= 1
        xvel == 0 && break
      end
      if targetx1 <= xpos <= targetx2 && !in(initxvel, matched_x)
        global cnt += 1
        println(initxvel, ",", inityvel, ": ", steps, " - ", xpos, ",", ypos)
        push!(matched_x, initxvel)
      end
    end

    ypos += yvel
    yvel -= 1
    steps += 1
  end
end

println("Result: ", cnt)


text:
import Pkg; Pkg.add("Plots"); Pkg.add("Polynomials")
using Plots
using Polynomials
include( "bug_1.jl")
include( "bug_2.jl")

W_O = Dict("w1" => [
                        [(x = 1, y = 1), (x = 2, y = 1), (x = 2, y = 5),(x = 1, y = 5)],
                        [(x = 3, y = 4), (x = 4, y = 4), (x = 4, y = 12),(x = 3, y = 12)],
                        [(x = 3, y = 12), (x = 12, y = 12), (x = 12, y = 13),(x = 3, y = 13)],
                        [(x = 12, y = 5), (x = 13, y = 5), (x = 13, y = 13),(x = 12, y = 13)],
                        [(x = 6, y = 5), (x = 12, y = 5), (x = 12, y = 6),(x = 6, y = 6)]
                    ],
            "w2" => [
                        [(x = -6, y = -6), (x = 25, y = -6), (x = 25, y = -5),(x = -6, y = -5)],
                        [(x = -6, y = 5), (x = 30, y = 5), (x = 30, y = 6),(x = -6, y = 6)],
                        [(x = -6, y = -5), (x = -5, y = -5), (x = -5, y = 5),(x = -6, y = 5)],
                        [(x = 4, y = -5), (x = 5, y = -5), (x = 5, y = 1),(x = 4, y = 1)],
                        [(x = 9, y = 0), (x = 10, y = 0), (x = 10, y = 5),(x = 9, y = 5)],
                        [(x = 14, y = -5), (x = 15, y = -5), (x = 15, y = 1),(x = 14, y = 1)],
                        [(x = 19, y = 0), (x = 20, y = 0), (x = 20, y = 5),(x = 19, y = 5)],
                        [(x = 24, y = -5), (x = 25, y = -5), (x = 25, y = 1),(x = 24, y = 1)],
                        [(x = 29, y = 0), (x = 30, y = 0), (x = 30, y = 5),(x = 29, y = 5)],
                    ]
    );
# display(plot([1,2],[10,3]))
w1 = get(W_O, "w1", 0);

w2 = get(W_O, "w2", 0);

function main(args)

    if isempty(args)
        println("\n --*--*--*--*")
        println("No argument provided. type: julia hw_1.jl help")
        return
    end
    if args[1] == "help"
        println("Usgae : \n
    bug1 -w1: bug 1, workspace 1\n
    bug1 -w2: bug 1, workspace 2\n
    bug2 -w1: bug 2, workspace 1\n
    bug2 -w2: bug 2, workspace 2")
    end
    if (args[1] == "bug1")

        if args[2] == "-w1"
            start = (x = 0, y = 0)
            goal = (x = 10, y = 10)
            x_start = [0];
            y_start = [0];
            x_goal = [10];
            y_goal = [10];
            xx = [];yy = [];
            points = []
            plt1 = plot(x_start, y_start, legend=false, marker=([:dot :d]))
            for arr in w1
                points = make_array(arr)
                plot!(plt1, points, legend=false)
            end
            plot!(plt1, x_goal, y_goal, marker=([:dot :d]))
            bug1_w1(w1, plt1)
            png("bug1_w1")
        elseif args[2] == "-w2"
            x_start = [0];
            y_start = [0];
            x_goal = [35];
            y_goal = [0];
            points = []
            goal = (x = 35, y = 0);
            start = (x = 0, y = 0)
            plt2 = plot(x_start, y_start, legend=false, marker=([:hex :d]))
            for arr in w2
                points = make_array(arr)
                plot!(plt2, points, legend=false)
            end
            plot!(plt2, x_goal, y_goal, marker=([:hex :d]))
            bug1_w2(w2)
            png("bug1_w2")
        end

        return

    end
    if (args[1 ] == "bug2")
        if args[2] == "-w1"
            start = (x = 0, y = 0)
            goal = (x = 10, y = 10)
            x_start = [0];
            y_start = [0];
            x_goal = [10];
            y_goal = [10];
            xx = [];yy = [];
            points = []
            plt1 = plot(x_start, y_start, legend=false, marker=([:dot :d]))
            for arr in w1
                points = make_array(arr)
                plot!(plt1, points, legend=false)
            end
            plot!(plt1, x_goal, y_goal, marker=([:dot :d]))
            bug2_w1()
            png("bug2_w1")
        elseif args[2] == "-w2"
            x_start = [0];
            y_start = [0];
            x_goal = [35];
            y_goal = [0];
            points = []
            goal = (x = 35, y = 0);
            start = (x = 0, y = 0)
            plt2 = plot(x_start, y_start, legend=false, marker=([:hex :d]))
            for arr in w2
                points = make_array(arr)
                plot!(plt2, points, legend=false)
            end
            plot!(plt2, x_goal, y_goal, marker=([:hex :d]))
            bug2_w2(w2)
            png("bug2_w2")
        end

        return
    end

end

main(ARGS)


text:
function plot_hufftree(T)
    """
        plot_hufftree - plot a huffman tree

        plot_hufftree(T);

        Copyright (c) 2008 Gabriel Peyre
    """
    figure(figsize=(10,10))
    plot_tree(T,[0,0],1)
    xlim(-1,1)
    axis("off")
end

function plot_tree(T,x,j)
    tw = 15;
    lw = 1.5;
    ms = 10;

    if typeof(T)==String
        de = [-.02 -.2]
        # display a string
        u = text(x[1]+de[1],x[2]+de[2],T);
        #set(u,"FontSize",tw);
    else
        # display a split
        h0 = 1/2^j;
        h = 1 * h0;
        plot( [x[1]; x[1]-h], [x[2]; x[2]-1], ".-" ,ms=ms,lw=lw,c="b")
        #set(u,"MarkerSize",ms);
        #set(u,"LineWidth",lw);
        plot( [x[1]; x[1]+h], [x[2]; x[2]-1], ".-",ms=ms,lw=lw,c="b")
        #set(u,"MarkerSize",ms);
        #set(u,"LineWidth",lw);
        #xlim(-1,1)
        plot_tree(T[1],[x[1]-h x[2]-1],j+1)
        plot_tree(T[2],[x[1]+h x[2]-1],j+1)
    end
end


text:
# This file was generated, do not modify it. # hide
BayesianQDA = @load BayesianQDA pkg=ScikitLearn

max_issues_repo_name: alan-turing-institute/MLJTutorials

max_forks_repo_name: alan-turing-institute/MLJTutorials


text:
# 3. Districtwise timeseries of Confirmed, Recovered and Deceased numbers.

# function get_district_timeseries(state::String)
#     df = read_CSV_url(districts_csv_url)
#     return df[df[!,:State].==state,:]
# end

function get_district_timeseries(district::String)
    df = read_CSV_url(districts_csv_url)
    return df[df[!,:District].==district,:]
end

# 6. Districtwise Cumulative numbers till date.
function get_state_districts_cumulative(state::String, brief::Bool=true)
    df = read_CSV_url(district_wise_csv_url)
    dfstate = df[df[!,:State].==state,:]

    if brief == true
        colindices = []
        rmcols = ["SlNo", "State_Code", "District_Key", "Migrated_Other", "District_Notes"]
        for col in rmcols
            colindex = columnindex(df,col)
            append!(colindices,colindex)
        end
        select!(dfstate,Not(colindices))
    end

    return dfstate
end


text:
"""
    step_size(::ForwardMode, x::AbstractFloat)

# Description

Determine the step-size to use for forward-mode finite differences.

# Arguments

* `::ForwardMode`: An instance of the `ForwardMode` type.
* `x::AbstractFloat`: A point at which the derivative of a function will be
    approximated. Its type must implement `eps`.

# Returns

* `ϵ::Real`: The step-size to use for finite differences at `x`.

# References

See Section 5.7 of Numerical Recipes in C for the mathematical justification
for working with `sqrt(eps(typeof(x)))`.

# Examples

```julia
import FiniteDiff: step_size, ForwardMode
ϵ = step_size(ForwardMode(), 0.0)
```
"""
@inline function step_size(::ForwardMode, x::AbstractFloat)::Real
    return sqrt(eps(typeof(x))) * max(one(typeof(x)), abs(x))
end

"""
    step_size(::BackwardMode, x::AbstractFloat)

# Description

Determine the step-size to use for backward-mode finite differences.

# Arguments

* `::BackwardMode`: An instance of the `BackwardMode` type.
* `x::AbstractFloat`: A point at which the derivative of a function will be
    approximated. Its type must implement `eps`.

# Returns

* `ϵ::Real`: The step-size to use for finite differences at `x`.

# References

See Section 5.7 of Numerical Recipes in C for the mathematical justification
for working with `sqrt(eps(typeof(x)))`.

# Examples

```julia
import FiniteDiff: step_size, BackwardMode
ϵ = step_size(BackwardMode(), 0.0)
```
"""
@inline function step_size(::BackwardMode, x::AbstractFloat)::Real
    return sqrt(eps(typeof(x))) * max(one(typeof(x)), abs(x))
end

"""
    step_size(::CentralMode, x::AbstractFloat)

# Description

Determine the step-size to use for central-mode finite differences.

# Arguments

* `::CentralMode`: An instance of the `CentralMode` type.
* `x::AbstractFloat`: A point at which the derivative of a function will be
    approximated. Its type must implement `eps`.

# Returns

* `ϵ::Real`: The step-size to use for finite differences at `x`.

# References

See Section 5.7 of Numerical Recipes in C for the mathematical justification
for working with `cbrt(eps(typeof(x)))`.

# Examples

```julia
import FiniteDiff: step_size, CentralMode
ϵ = step_size(CentralMode(), 0.0)
```
"""
@inline function step_size(::CentralMode, x::AbstractFloat)::Real
    return cbrt(eps(typeof(x))) * max(one(typeof(x)), abs(x))
end

"""
    step_size(::ComplexMode, x::AbstractFloat)

# Description

Determine the step-size to use for complex-mode finite differences.

# Arguments

* `::ComplexMode`: An instance of the `ComplexMode` type.
* `x::AbstractFloat`: A point at which the derivative of a function will be
    approximated. Its type must implement `eps`.

# Returns

* `ϵ::Real`: The step-size to use for finite differences at `x`.

# References

See "The Complex-Step Derivative Approximation" by Martins, Sturdza and Alonso
(2003) for the mathematical justification for working with `eps(x)`.

# Examples

```julia
import FiniteDiff: step_size, ComplexMode
ϵ = step_size(ComplexMode(), 0.0)
```
"""
@inline function step_size(::ComplexMode, x::AbstractFloat)::Real
    return eps(typeof(x))
end

"""
    step_size(::HessianMode, x::AbstractFloat)

# Description

Determine the step-size to use for finite differences of hessians.

# Arguments

* `::HessianMode`: An instance of the `HessianMode` type.
* `x::AbstractFloat`: A point at which the derivative of a function will be
    approximated. Its type must implement `eps`.

# Returns

* `ϵ::Real`: The step-size to use for finite differences at `x`.

# References

See Section 5.7 of Numerical Recipes in C for the mathematical justification
for working with `eps(x)^(1 // 4)`.

# Examples

```julia
import FiniteDiff: step_size, HessianMode
ϵ = step_size(HessianMode(), 0.0)
```
"""
@inline function step_size(::HessianMode, x::AbstractFloat)::Real
    return eps(typeof(x))^(1 // 4) * max(one(typeof(x)), abs(x))
end


text:
#!/usr/bin/env julia --project
using ArgParse

using ClimateMachine
using ClimateMachine.Atmos
using ClimateMachine.Orientations
using ClimateMachine.ConfigTypes
using ClimateMachine.Diagnostics
using ClimateMachine.GenericCallbacks
using ClimateMachine.ODESolvers
using Thermodynamics.TemperatureProfiles
using Thermodynamics
using ClimateMachine.TurbulenceClosures
using ClimateMachine.VariableTemplates
using StaticArrays
using Test
using CLIMAParameters
using CLIMAParameters.Atmos.SubgridScale: C_smag
using CLIMAParameters.Planet: R_d, cp_d, cv_d, MSLP, grav
struct EarthParameterSet <: AbstractEarthParameterSet end
const param_set = EarthParameterSet();

function init_risingbubble!(problem, bl, state, aux, localgeo, t)
    ## Problem float-type
    FT = eltype(state)

    (x, y, z) = localgeo.coord
    param_set = parameter_set(bl)

    ## Unpack constant parameters
    R_gas::FT = R_d(param_set)
    c_p::FT = cp_d(param_set)
    c_v::FT = cv_d(param_set)
    p0::FT = MSLP(param_set)
    _grav::FT = grav(param_set)
    γ::FT = c_p / c_v

    ## Define bubble center and background potential temperature
    xc::FT = 5000
    yc::FT = 1000
    zc::FT = 2000
    r = sqrt((x - xc)^2 + (z - zc)^2)
    rc::FT = 2000
    θamplitude::FT = 2
    q_tot_amplitude::FT = 1e-3

    ## TODO: clean this up, or add convenience function:
    ## This is configured in the reference hydrostatic state
    ref_state = reference_state(bl)
    θ_ref::FT = ref_state.virtual_temperature_profile.T_surface

    ## Add the thermal perturbation:
    Δθ::FT = 0
    Δq_tot::FT = 0
    if r <= rc
        Δθ = θamplitude * (1.0 - r / rc)
        Δq_tot = q_tot_amplitude * (1.0 - r / rc)
    end

    ## Compute perturbed thermodynamic state:
    θ = θ_ref + Δθ                                      # potential temperature
    q_pt = PhasePartition(Δq_tot)
    R_m = gas_constant_air(param_set, q_pt)
    _cp_m = cp_m(param_set, q_pt)
    _cv_m = cv_m(param_set, q_pt)
    π_exner = FT(1) - _grav / (_cp_m * θ) * z           # exner pressure
    ρ = p0 / (R_gas * θ) * (π_exner)^(_cv_m / R_m)      # density
    T = θ * π_exner

    if moisture_model(bl) isa EquilMoist
        e_int = internal_energy(param_set, T, q_pt)
        ts = PhaseEquil(param_set, e_int, ρ, Δq_tot)
    else
        e_int = internal_energy(param_set, T)
        ts = PhaseDry(param_set, e_int, ρ)
    end
    ρu = SVector(FT(0), FT(0), FT(0))                   # momentum
    ## State (prognostic) variable assignment
    e_kin = FT(0)                                       # kinetic energy
    e_pot = gravitational_potential(bl, aux)            # potential energy
    ρe_tot = ρ * total_energy(e_kin, e_pot, ts)         # total energy
    ρq_tot = ρ * Δq_tot                                 # total water specific humidity

    ## Assign State Variables
    state.ρ = ρ
    state.ρu = ρu
    state.energy.ρe = ρe_tot
    if !(moisture_model(bl) isa DryModel)
        state.moisture.ρq_tot = ρq_tot
    end
end

function config_risingbubble(FT, N, resolution, xmax, ymax, zmax, with_moisture)

    T_surface = FT(300)
    T_min_ref = FT(0)
    T_profile = DryAdiabaticProfile{FT}(param_set, T_surface, T_min_ref)
    ref_state = HydrostaticState(T_profile)

    _C_smag = FT(C_smag(param_set))

    if with_moisture
        moisture = EquilMoist()
    else
        moisture = DryModel()
    end
    physics = AtmosPhysics{FT}(
        param_set;
        ref_state = ref_state,
        turbulence = SmagorinskyLilly(_C_smag),
        moisture = moisture,
        tracers = NoTracers(),
    )
    model = AtmosModel{FT}(
        AtmosLESConfigType,
        physics;
        init_state_prognostic = init_risingbubble!,
        source = (Gravity(),),
    )

    config = ClimateMachine.AtmosLESConfiguration(
        "RisingBubble",
        N,
        resolution,
        xmax,
        ymax,
        zmax,
        param_set,
        init_risingbubble!,
        model = model,
    )
    return config
end

function config_diagnostics(driver_config)
    FT = Float64
    interval = "50ssecs"
    boundaries = [
        FT(0.0) FT(0.0) FT(0.0)
        FT(10000) FT(500) FT(10000)
    ]
    resolution = (FT(100), FT(100), FT(100))
    interpol = ClimateMachine.InterpolationConfiguration(
        driver_config,
        boundaries,
        resolution,
    )
    dgngrp = setup_atmos_default_diagnostics(
        AtmosLESConfigType(),
        interval,
        driver_config.name,
    )
    state_dgngrp = setup_dump_state_diagnostics(
        AtmosLESConfigType(),
        interval,
        driver_config.name,
        interpol = interpol,
    )
    aux_dgngrp = setup_dump_aux_diagnostics(
        AtmosLESConfigType(),
        interval,
        driver_config.name,
        interpol = interpol,
    )
    return ClimateMachine.DiagnosticsConfiguration([
        dgngrp,
        state_dgngrp,
        aux_dgngrp,
    ])
end

function main()
    # add a command line argument to specify whether to use a moist setup
    rb_args = ArgParseSettings(autofix_names = true)
    add_arg_group!(rb_args, "RisingBubble")
    @add_arg_table! rb_args begin
        "--with-moisture"
        help = "use a moist setup"
        action = :store_const
        constant = true
        default = false
    end
    cl_args = ClimateMachine.init(parse_clargs = true, custom_clargs = rb_args)
    with_moisture = cl_args["with_moisture"]

    FT = Float64
    N = 4
    Δh = FT(125)
    Δv = FT(125)
    resolution = (Δh, Δh, Δv)
    xmax = FT(10000)
    ymax = FT(500)
    zmax = FT(10000)
    t0 = FT(0)
    timeend = FT(1000)

    CFL = FT(1.7)

    driver_config =
        config_risingbubble(FT, N, resolution, xmax, ymax, zmax, with_moisture)

    ode_solver_type = ClimateMachine.ExplicitSolverType(
        solver_method = LSRK144NiegemannDiehlBusch,
    )

    solver_config = ClimateMachine.SolverConfiguration(
        t0,
        timeend,
        driver_config,
        ode_solver_type = ode_solver_type,
        init_on_cpu = true,
        Courant_number = CFL,
    )
    dgn_config = config_diagnostics(driver_config)

    result = ClimateMachine.invoke!(
        solver_config;
        diagnostics_config = dgn_config,
        user_callbacks = (),
        check_euclidean_distance = true,
    )

    @test isapprox(result, FT(1); atol = 1.5e-3)
end

main()


text:
level_iter(S, n::Int) = n == 1 ? S.nodes : chain((level_iter(node, n-1) for node in S.nodes)...)

struct LevelIterIdx{T}
    iter::T
end
LevelIterIdx(S::AbstractMultiScaleArray, n::Int) = LevelIterIdx(level_iter(S, n))

function Base.iterate(l::LevelIterIdx)
    x = iterate(l.iter)
    x == nothing && return nothing
    val, new_state = x
    end_idx = 1 + length(val) - 1
    ((val, 1, end_idx), (new_state, end_idx + 1))
end

function Base.iterate(l::LevelIterIdx,state)
    x = iterate(l.iter,state[1])
    x == nothing && return nothing
    val, new_state = x
    end_idx = state[2] + length(val) - 1
    ((val, state[2], end_idx), (new_state, end_idx + 1))
end

LevelIter(n::Int,S::AbstractMultiScaleArray...) = zip((level_iter(s, n) for s in S)...)


text:
# harris corner feature example from webcam or movie

using Images, ImageView, ImageDraw, ImageFeatures, Gtk.ShortNames, VideoIO

@show projdir = joinpath(dirname(@__FILE__), "..")
srcdir = joinpath(projdir,"src")
include(joinpath(srcdir, "SensorFeatureTracking.jl"))
include(joinpath(srcdir, "Common.jl"))

function fromvideohandle(fhl ;iters=50, param1=0.15, param2=0.35)
    grid, frames, canvases = canvasgrid((1,2))  # 1 row, 2 columns

    img = read(fhl)

    imshow(canvases[1,1], img)
    imshow(canvases[1,2], img)

    win = Window(grid)
    showall(win)

    for i in 1:iters
        read!(fhl, img)

        # imshow(canvases[1,1], img)
        imgg = Gray.(img)
        # corners = fastcorners(imgg, param1, param2)
        # fts1 = Features(corners)
        ## corners = getharriscorners(imgg)
        fts1 = getapproxbestharris(imgg, 200)

        # draw the results
        for ft in fts1
            drawfeaturecircle2d!(imgg, ft, radius=5)
        end
        imshow(canvases[1,2], imgg)
        sleep(0.001)
    end

    nothing
end

# f = VideoIO.testvideo("annie_oakley") # this doesn't directly work for reading images in current version

f = VideoIO.opencamera() #webcam
fromvideohandle(f)
close(f)

#

max_stars_repo_name: dehann/SensorFeatureTracking

max_issues_repo_name: dehann/SensorFeatureTracking

max_forks_repo_name: dehann/SensorFeatureTracking


text:
using MPI
MPI.Init()

comm = MPI.COMM_WORLD
println("Hello world, I am $(MPI.Comm_rank(comm)) of $(MPI.Comm_size(comm))")
MPI.Barrier(comm)


text:
@defcomp radiativeforcing begin
	FORCOTH	  = Variable(index=[time])	 #Exogenous forcing for other greenhouse gases
    FORC      = Variable(index=[time])   #Increase in radiative forcing (watts per m2 from 1900)

    MAT       = Parameter(index=[time])  #Carbon concentration increase in atmosphere (GtC from 1750)
    eqmat     = Parameter()              #Equilibrium concentration of CO2 in atmosphere (GTC)
    fco22x    = Parameter()              #Forcings of equilibrium CO2 doubling (Wm-2)
	fex0	  = Parameter()				 #2015 forcings of non-CO2 GHG (Wm-2)
	fex1	  = Parameter()				 #2100 forcings of non-CO2 GHG (Wm-2)

    function run_timestep(p, v, d, t)
		#Define function for FORCOTH
		for tm = 1:100
			if tm < 19
				v.FORCOTH[tm] = p.fex0 + (1/17) * (p.fex1 - p.fex0) * (tm - 1)
			else
				v.FORCOTH[tm] = p.fex0 + (p.fex1 - p.fex0)
			end
		end

        #Define function for FORC
        v.FORC[t] = p.fco22x * (log((p.MAT[t] / p.eqmat)) / log(2)) + v.FORCOTH[t]
    end
end


text:
using Codex.GitLab
using Dates
using Test

GitLab = Codex.GitLab

@testset "GitLab" begin
    # Allow tests to pass locally without GITLAB_TOKEN.
    if "CI" in keys(ENV) || "GITLAB_TOKEN" in keys(ENV)
        config = GitLab.Config(ENV["GITLAB_TOKEN"], "https://gitlab.com")
        project_id = 22670750
        project = GitLab.Project(config, project_id)

        # Ensure that `enforce_schedule` also deletes.
        @test GitLab.create_schedule(project,
            (description = "Test", ref = "master", cron = "0 1 * * *")
        ).description == "Test"

        params = [
            (description = string(Dates.now(), "-1"), ref = "master",
            cron = "0 1 * * *", active = false),
            (description = string(Dates.now(), "-2"), ref = "master",
            cron = "0 2 * * *", active = false)
        ]

        # Smoke test for `variables = []`.
        GitLab.enforce_schedules(project, [params[1]])

        variables = [
            [(key = "key1", value = "value1")],
            [(key = "key2", value = "value2")]
        ]
        schedules = GitLab.enforce_schedules(project, params; variables)
        @test GitLab.n_schedules(project) == 2
        @test schedules[1].active == false

        # Create project variable.
        @test GitLab.create_variable(project,
            (key = "key3", value = "value3")
        ).key == "key3"

        variables = [
            (key = "key4", value = string(Dates.now(), "-4"), protected = true),
            (key = "key5", value = string(Dates.now(), "-5"))
        ]
        enforce_variables(project, variables)
        @test length(GitLab.list_variables(project)) == 2
    else
        @warn "Skipping the GitLab tests"
    end
end


text:
module CondaPkg

if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@compiler_options"))
    # Without this, resolve() takes a couple of seconds, with, it takes 0.1 seconds.
    # Maybe with better structured code or precompilation it's not necessary.
    # Note: compile=min makes --code-coverage not work
    @eval Base.Experimental.@compiler_options optimize=0 infer=false #compile=min
end

import Base: @kwdef
import MicroMamba
import JSON3
import Pkg
import TOML

let toml = TOML.parsefile(joinpath(@__DIR__, "..", "Project.toml"))
    @eval const UUID = Base.UUID($(toml["uuid"]))
    @eval const PKGID = Base.PkgId(UUID, "CondaPkg")
    @eval const VERSION = Base.VersionNumber($(toml["version"]))
end

@kwdef mutable struct State
    # backend
    backend::Symbol = :NotSet
    condaexe::String = ""
    # resolve
    resolved::Bool = false
    load_path::Vector{String} = String[]
    meta_dir::String = ""
    frozen::Bool = false
end

const STATE = State()

include("backend.jl")
include("spec.jl")
include("meta.jl")
include("resolve.jl")
include("env.jl")
include("deps.jl")

include("PkgREPL.jl")

end # module