text:
#=
 █████╗  ██████╗██████╗ ██╗
██╔══██╗██╔════╝██╔══██╗██║
███████║██║     ██████╔╝██║
██╔══██║██║     ██╔══██╗██║
██║  ██║╚██████╗██║  ██║███████╗
╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝
File:       rendezvous_review.jl
Author:     Gabriel Barsi Haberfeld, 2020. gbh2@illinois.edu
Function:   This program simulates all results in the paper "Geometry-Informed
            Minimum Risk Rendezvous Algorithm for Heterogeneous Agents in Urban
            Environments"
Instructions:   Run this file in juno with Julia 1.2.0 or later.
Requirements:   JuMP, Ipopt, Plots, LinearAlgebra, BenchmarkTools.
=#

function RendezvousPlanner(
    UASPos,
    LPos,
    OptTimeSample,
    Er,
    ts,
    PrevPNR = [0, 0],
    PNRStat = false,
    p = 2,
    gp = nothing,
    DriverPos = 0.0,
)
    RDVPos = path(DriverPosition(ts, OptTimeSample[p], gp) + DriverPos, p)
    #@show OptTimeSample, RDVPos
    MPC = Model(
        optimizer_with_attributes(
            Ipopt.Optimizer,
            "print_level" => 0,
            "max_iter" => convert(Int64, 500),
        ),
    )
    @variable(MPC, PNR[i = 1:2])
    @variable(MPC, -vmax <= v[i = 1:2, j = 1:4] <= vmax)
    @variable(MPC, t[j = 1:4] >= 0.1)
    @constraint(MPC, PNR .== v[:, 1] .* t[1] .+ UASPos)
    @constraint(MPC, RDVPos .== v[:, 2] .* t[2] .+ PNR)
    @constraint(MPC, LPos .== v[:, 3] .* t[3] .+ RDVPos)
    @constraint(MPC, LPos .== v[:, 4] .* t[4] .+ PNR)

    @NLconstraint(
        MPC,
        m[1] * v[1, 1]^2 * t[1] +
        m[1] * v[1, 2]^2 * t[2] +
        m[2] * v[1, 3]^2 * t[3] +
        m[1] * v[2, 1]^2 * t[1] +
        m[1] * v[2, 2]^2 * t[2] +
        m[2] * v[2, 3]^2 * t[3] +
        m[1] * alpha * t[1] +
        m[1] * alpha * t[2] +
        m[2] * alpha * t[3] <= Er
    )
    @NLconstraint(
        MPC,
        m[1] * v[1, 1]^2 * t[1] +
        m[1] * v[1, 4]^2 * t[4] +
        m[1] * v[2, 1]^2 * t[1] +
        m[1] * v[2, 4]^2 * t[4] +
        m[1] * alpha * t[1] +
        m[1] * alpha * t[4] <= Er
    )
    ta = OptTimeSample[p] - ts #available time is time to RDV minus current time
    @constraint(MPC, t[1] + t[2] <= ta)
    if PrevPNR[1] != 0 || PrevPNR[2] != 0
        PNRDist = @expression(MPC, PrevPNR - PNR)
        #@constraint(MPC, PNRDist' * PNRDist <= 1000.0)
    end
    @objective(MPC, Min, sum(t[i] for i = 2:4) - 1 * t[1])
    #@show m
    JuMP.optimize!(MPC)
    v = value.(v)
    t = value.(t)
    return v, t
end

function RendezvousMinTime(
    UASPos,
    LPos,
    OptTimeSample,
    Er,
    ts,
    PrevPNR = [0, 0],
    PNRStat = false,
    p = 2,
    gp = nothing,
    DriverPos = 0.0,
)
    RDVPos = path(DriverPosition(ts, OptTimeSample[p], gp) + DriverPos, p)
    #@show OptTimeSample, RDVPos
    MPC = Model(
        optimizer_with_attributes(
            Ipopt.Optimizer,
            "print_level" => 0,
            "max_iter" => convert(Int64, 500),
        ),
    )
    @variable(MPC, PNR[i = 1:2])
    @variable(MPC, -vmax <= v[i = 1:2, j = 1:4] <= vmax)
    @variable(MPC, t[j = 1:4] >= 0.1)
    @constraint(MPC, PNR .== v[:, 1] .* t[1] .+ UASPos)
    @constraint(MPC, RDVPos .== v[:, 2] .* t[2] .+ PNR)
    @constraint(MPC, LPos .== v[:, 3] .* t[3] .+ RDVPos)
    @constraint(MPC, LPos .== v[:, 4] .* t[4] .+ PNR)

    @NLconstraint(
        MPC,
        m[1] * v[1, 1]^2 * t[1] +
        m[1] * v[1, 2]^2 * t[2] +
        m[2] * v[1, 3]^2 * t[3] +
        m[1] * v[2, 1]^2 * t[1] +
        m[1] * v[2, 2]^2 * t[2] +
        m[2] * v[2, 3]^2 * t[3] +
        m[1] * alpha * t[1] +
        m[1] * alpha * t[2] +
        m[2] * alpha * t[3] <= Er
    )
    @NLconstraint(
        MPC,
        m[1] * v[1, 1]^2 * t[1] +
        m[1] * v[1, 4]^2 * t[4] +
        m[1] * v[2, 1]^2 * t[1] +
        m[1] * v[2, 4]^2 * t[4] +
        m[1] * alpha * t[1] +
        m[1] * alpha * t[4] <= Er
    )
    ta = OptTimeSample[p] - ts #available time is time to RDV minus current time
    @constraint(MPC, t[1] + t[2] <= ta)
    if PrevPNR[1] != 0 || PrevPNR[2] != 0
        PNRDist = @expression(MPC, PrevPNR - PNR)
        #@constraint(MPC, PNRDist' * PNRDist <= 1000.0)
    end
    @objective(MPC, Min, sum(t[i] for i = 1:4))

    JuMP.optimize!(MPC)
    v = value.(v)
    t = value.(t)
    return v, t
end

function maxRange(Er, mass = [2, 1], tmax = 1000)
    m = mass
    OCP = Model(
        optimizer_with_attributes(
            Ipopt.Optimizer,
            "print_level" => 0,
            "max_iter" => convert(Int64, 50000),
        ),
    )
    @variable(OCP, r >= 0)
    @variable(OCP, v[i = 1:2, j = 1:2] >= 0)
    @variable(OCP, t[i = 1:2] >= 0)
    @NLobjective(OCP, Max, sqrt((v[1, 1] * t[1])^2 + (v[2, 1] * t[1])^2))
    @NLconstraint(
        OCP,
        sqrt((v[1, 1] * t[1])^2 + (v[2, 1] * t[1])^2) ==
        sqrt((v[1, 2] * t[2])^2 + (v[2, 2] * t[2])^2)
    ) # one-way ranges are the same
    @NLconstraint(
        OCP,
        m[1] * v[1, 1]^2 * t[1] + #vx^2 going
        m[2] * v[1, 2]^2 * t[2] +
        m[1] * v[2, 1]^2 * t[1] + #vx^2 back
        m[2] * v[2, 2]^2 * t[2] +
        m[1] * alpha * t[1] + #hovering going
        m[2] * alpha * t[2] <= Er #hovering back
    )
    #@constraint(OCP, sum(t[i] for i = 1:2) <= tmax)
    @constraint(OCP, t[1] <= tmax)
    JuMP.optimize!(OCP)
    v = value.(v)
    t = value.(t)
    r = sqrt((v[1, 1] * t[1])^2 + (v[2, 1] * t[1])^2)
    #@show r, v, t
    return r
end

function minTime(Er, mass = [2, 1], xmax = 500, ymax = 500)
    m = mass
    OCP = Model(
        optimizer_with_attributes(
            Ipopt.Optimizer,
            "print_level" => 0,
            "max_iter" => convert(Int64, 500),
        ),
    )

    @variable(OCP, r >= 0)
    @variable(OCP, v[i = 1:2, j = 1:2] >= 0)
    @variable(OCP, t[i = 1:2] >= 0)
    @NLobjective(OCP, Min, sum(t[i] for i = 1:2))
    rmax = sqrt(xmax^2 + ymax^2)
    @NLconstraint(
        OCP,
        sqrt((v[1, 1] * t[1])^2 + (v[2, 1] * t[1])^2) ==
        sqrt((v[1, 2] * t[2])^2 + (v[2, 2] * t[2])^2)
    ) # one-way ranges are the same
    @NLconstraint(OCP, sqrt((v[1, 1] * t[1])^2 + (v[2, 1] * t[1])^2) == rmax)
    @NLconstraint(
        OCP,
        m[1] * v[1, 1]^2 * t[1] + #vx^2 going
        m[2] * v[1, 2]^2 * t[2] +
        m[1] * v[2, 1]^2 * t[1] + #vx^2 back
        m[2] * v[2, 2]^2 * t[2] +
        m[1] * alpha * t[1] + #hovering going
        m[2] * alpha * t[2] <= Er #hovering back
    )
    JuMP.optimize!(OCP)
    v = value.(v)
    t = value.(t)
    r = sqrt((v[1, 1] * t[1])^2 + (v[2, 1] * t[1])^2)
    @show r, v, t
    tmax = sum(t)
    return tmax
end

function minReturnEnergy(p1, p2)
    lm = mass[2]
    OCP = Model(
        optimizer_with_attributes(
            Ipopt.Optimizer,
            "print_level" => 0,
            "max_iter" => convert(Int64, 500),
        ),
    )
    @variable(OCP, vmax >= v[i = 1:2] >= -vmax)
    @variable(OCP, t >= 0)
    @NLobjective(OCP, Min, v[1]^2 * t + v[2]^2 * t + alpha * t)
    @constraint(OCP, p1[1] + v[1] * t == p2[1])
    @constraint(OCP, p1[2] + v[2] * t == p2[2])
    JuMP.optimize!(OCP)
    v = value.(v)
    t = value.(t)
    E = lm / 2 * t * (v[1]^2  + v[2]^2) + lm * alpha * t
    return E, t, v
end

max_stars_repo_name: gbarsih/Multi-Path-Safe-Rendezvous

max_issues_repo_name: gbarsih/Multi-Path-Safe-Rendezvous

max_forks_repo_name: gbarsih/Multi-Path-Safe-Rendezvous


text:
#=
 █████╗  ██████╗██████╗ ██╗
██╔══██╗██╔════╝██╔══██╗██║
███████║██║     ██████╔╝██║
██╔══██║██║     ██╔══██╗██║
██║  ██║╚██████╗██║  ██║███████╗
╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝
File:       rendezvous_review.jl
Author:     Gabriel Barsi Haberfeld, 2020. gbh2@illinois.edu
Function:   This program simulates all results in the paper "Geometry-Informed
            Minimum Risk Rendezvous Algorithm for Heterogeneous Agents in Urban
            Environments"
Instructions:   Run this file in juno with Julia 1.2.0 or later.
Requirements:   JuMP, Ipopt, Plots, LinearAlgebra, BenchmarkTools.
=#

default(size = 0.6 .* [800, 600])
default(palette = :tol_bright)
default(dpi = 300)
default(lw = 2)
default(margin = 1mm)
FontSize = 12
default(xtickfontsize = FontSize)
default(ytickfontsize = FontSize)
default(xguidefontsize = FontSize)
default(yguidefontsize = FontSize)
default(legendfontsize = FontSize)
default(titlefontsize = FontSize)
rng = MersenneTwister(1234)

function plotPlan(UASPos, LPos, RDVPos, v, t)
    plotpath(1)
    plotpath!(2)
    PNR = UASPos + v[:, 1] * t[1]
    RDV = PNR + v[:, 2] * t[2]
    L = RDV + v[:, 3] * t[3]
    LA = PNR + v[:, 4] * t[4]
    scatter!([UASPos[1]], [UASPos[2]])
    scatter!([LPos[1]], [LPos[2]])
    scatter!([PNR[1]], [PNR[2]])
    scatter!([RDV[1]], [RDV[2]])
    scatter!([L[1]], [L[2]])
    scatter!([LA[1]], [LA[2]])
    DPlan = [UASPos PNR RDV L]
    #DPlan = [UASPos RDV L]
    p = plot!(DPlan[1, :], DPlan[2, :])
end

function plotPlan!(UASPos, LPos, RDVPos, v, t)
    plotpath!(1)
    plotpath!(2)
    PNR = UASPos + v[:, 1] * t[1]
    RDV = PNR + v[:, 2] * t[2]
    L = RDV + v[:, 3] * t[3]
    LA = PNR + v[:, 4] * t[4]
    scatter!([UASPos[1]], [UASPos[2]])
    scatter!([LPos[1]], [LPos[2]])
    scatter!([PNR[1]], [PNR[2]])
    scatter!([RDV[1]], [RDV[2]])
    scatter!([L[1]], [L[2]])
    scatter!([LA[1]], [LA[2]])
    DPlan = [UASPos PNR RDV L]
    #DPlan = [UASPos RDV L]
    p = plot!(DPlan[1, :], DPlan[2, :])
end

function plotPlan!(
    UASPos,
    LPos,
    v,
    t,
    TimeSamples,
    np,
    ts,
    DriverPos,
    gp = nothing,
)
    np = size(TimeSamples, 2)
    for i = 1:np
        plotpath!(i)
        #plotTimeSamples!(TimeSamples, np, ts, DriverPos, gp)
    end
    PNR = UASPos + v[:, 1] * t[1]
    RDV = PNR + v[:, 2] * t[2]
    L = RDV + v[:, 3] * t[3]
    LA = PNR + v[:, 4] * t[4]
    scatter!([UASPos[1]], [UASPos[2]], markersize = 5.0)
    DPlan = [UASPos PNR RDV L]
    APlan = [UASPos PNR L]
    annotate!(PNR[1] + ho, PNR[2], text("PNR", 12, :center))
    annotate!(UASPos[1], UASPos[2] - vo, text("UAS", 12, :center))
    annotate!(L[1], L[2] - vo, text("Depot", 12, :center))
    annotate!(RDV[1], RDV[2] + vo, text("RDV", 12, :right))
    p1 = pv1[3, :]
    p2 = pv2[3, :]
    annotate!(p1[1] - ho, p1[2] + vo, text("Path 1", 12, :right))
    annotate!(p2[1] - ho, p2[2] - vo, text("Path 2", 12, :right))
    pp = scatter!(DPlan[1, :], DPlan[2, :])
    pp = plot!(DPlan[1, :], DPlan[2, :], lw = 2)
    pp = plot!(APlan[1, :], APlan[2, :], linestyle = :dash)
end

function plotMap(UASPos, LPos)
    plot(formatter = :latex)
    plotpath!(1)
    plotpath!(2)
    L = LPos
    scatter!([UASPos[1]], [UASPos[2]])
    scatter!([LPos[1]], [LPos[2]])
    scatter!([L[1]], [L[2]])
    annotate!(UASPos[1], UASPos[2] + vo, text(L"\textrm{UAS}", 12, :center))
    annotate!(L[1], L[2] - vo, text(L"\textrm{Depot}", 12, :center))
    p1 = pv1[3, :]
    p2 = pv2[3, :]
    annotate!(p1[1] - ho, p1[2] + vo, text(L"\textrm{Path 1}", 12, :right))
    annotate!(p2[1] - ho, p2[2] - vo, text(L"\textrm{Path 2}", 12, :right))
    xlabel!(L"x\;[m]")
    ylabel!(L"y\;[m]")
    savefig("map.pdf")
end

function drawConvexHull(TimeSamples, p = [1, 2], ucol = :blue)
    lt = length(TimeSamples)
    lp = length(p)
    θ = DriverPosFunction(TimeSamples)
    v = zeros(lt * lp)
    v = [zeros(2) for i = 1:lt*lp]
    for j = 1:lp
        idx1 = 1 + (j - 1) * lt
        idx2 = j * lt
        v[idx1:idx2] = [path(i, j, true) for i in θ]
    end
    hull = convex_hull(v)
    plot!(VPolygon(hull), alpha = 0.2, color = ucol)
end

function drawMultiConvexHull(PosSamples, p = [1, 2], ucol = :blue)
    ls, lp = size(PosSamples)
    if lp != length(p)
        error("Incorrect input dimensions")
    end
    v = [zeros(2) for i = 1:ls*lp]
    for j = 1:lp
        θ = PosSamples[:, j]
        idx1 = 1 + (j - 1) * ls
        idx2 = j * ls
        v[idx1:idx2] = [path(i, j, true) for i in θ]
    end
    hull = convex_hull(v)
    plot!(VPolytope(hull), alpha = 0.2, color = ucol)
end

function CircleShape(h, k, r)
    θ = range(0, 2 * π, length = 500)
    h .+ r * sin.(θ), k .+ r * cos.(θ)
end

function PlotRangeContours(
    Er = 50000,
    DepotCoord = [0.0, 0.0],
    t0 = 30,
    tint = 30,
    n = 20,
    mass = [2, 1],
    keep = false,
)
    t = range(t0, step = tint, length = n)
    r = zeros(n)
    if !keep
        p = plot()
    end
    p = plot!()
    for i = 1:n
        r[i] = maxRange(Er, mass, t[i])
        p = plot!(
            CircleShape(DepotCoord[1], DepotCoord[2], r[i]),
            seriestype = [:shape],
            c = :green,
            linecolor = :black,
            linealpha = 0.05,
            #linewidth = 0.0,
            legend = :false,
            fillalpha = min(1 / n, 0.1),
            aspecratio = 1,
            size = (1200, 1200),
        )
        s1 = @sprintf("\$T_{\\operator{max}}=%0.1fs\$", t[i])
        s1 = @sprintf("%ds", t[i])
        θ = -(i^(1.3) / (5 * n) * 2 * π + π)
        annotate!(
            DepotCoord[1] + r[i] * cos(θ),
            DepotCoord[2] + r[i] * sin(θ),
            Plots.text(s1, FontSize, rotation = rad2deg(θ - π / 2)),
        )
        xlabel!(L"x")
        ylabel!(L"y")
    end
    p = title!("Range for DIfferent Target Times")
    display(p)
    savefig("range_contours.png")
    return p
end

function PlotRangeTiers!(
    Er = 10000,
    UASPos = [0.0, 0.0],
    tmax = 100,
    mass = [2, 1],
)
    p = plot!(
        CircleShape(
            UASPos[1],
            UASPos[2],
            maxRange(Er, [mass[2], mass[2]], tmax),
        ),
        seriestype = [:shape],
        c = :green,
        linecolor = :black,
        linealpha = 0.1,
        #linewidth = 0.0,
        legend = :false,
        fillalpha = 0.3,
        aspecratio = 1,
    )
    p = plot!(
        CircleShape(
            UASPos[1],
            UASPos[2],
            maxRange(Er, [mass[1], mass[1]], tmax),
        ),
        seriestype = [:shape],
        c = :blue,
        linecolor = :black,
        linealpha = 0.1,
        #linewidth = 0.0,
        legend = :false,
        fillalpha = 0.3,
        aspecratio = 1,
    )
    p = plot!(
        CircleShape(UASPos[1], UASPos[2], maxRange(Er, mass, tmax)),
        seriestype = [:shape],
        c = :red,
        linecolor = :black,
        linealpha = 0.1,
        #linewidth = 0.0,
        legend = :false,
        fillalpha = 0.3,
        aspecratio = 1,
    )
end

function plotpath!(ns = ones(1))
    x = zeros(2, 1001)
    p = plot!(legend = :false)
    for i in ns
        j = 1
        for θ in range(0, size(x, 2) - 1, step = 1)
            x[:, j] .= path(θ, i)
            j = j + 1
        end
        p = plot!(x[1, :], x[2, :], xlims = (0, 1300), ylims = (400, 1300))
    end
    return p
end

function plotPosSamples!(PosSamples, np = ones(1))
    pp = plot!()
    for p in np
        c = path.(PosSamples[:, p], p)
        pp = scatter!(c, markersize = 3.0)
    end
    return pp
end

function plotTimeSamples!(
    TimeSamples,
    np,
    ti = 0.0,
    DriverPos = 0.0,
    gp = nothing,
)
    PosSamples = DriverPosition(ti, TimeSamples, gp) .+ DriverPos
    PosSamples[PosSamples.>=Mp] .= Mp
    plotPosSamples!(PosSamples, np)
end

ext: jl


text:
function initRxUHD(pointerUSRP)
	# ----------------------------------------------------
	# --- Rx Streamer
	# ----------------------------------------------------
	# --- Create a pointer related to the Rx streamer
	addressStream = Ref{Ptr{uhd_rx_streamer}}();
	# --- Cal the init
	@assert_uhd ccall((:uhd_rx_streamer_make, libUHD), uhd_error, (Ptr{Ptr{uhd_rx_streamer}},),addressStream);
	streamerPointer = addressStream[];
	# ----------------------------------------------------
	# --- Rx Metadata
	# ----------------------------------------------------
	# --- Create a pointer related to Metadata
	addressMD = Ref{Ptr{uhd_rx_metadata}}();
	# --- Cal the init
	@assert_uhd ccall((:uhd_rx_metadata_make, libUHD), uhd_error, (Ptr{Ptr{uhd_rx_metadata}},),addressMD);
	# --- Get the usable object
	metadataPointer = addressMD[];
	# --- Pointer for counting number of samples
	pointerSamples = Ref{Csize_t}(0);
	# ----------------------------------------------------
	# --- Create the USRP wrapper object
	# ----------------------------------------------------
	uhd  = UHDRxWrapper(true,pointerUSRP,streamerPointer,metadataPointer,addressStream,addressMD,pointerSamples);
	return uhd;
end

function openUHDRx(pointerUSRP,carrierFreq,samplingRate,gain,antenna="RX2";args="",uhdArgs="");
	# --- Init Rx stage
	uhd	  = initRxUHD(pointerUSRP);
	# ----------------------------------------------------
	# --- Creating Runtime structures
	# ----------------------------------------------------
	# --- Create structure for UHD argument
	# TODO Adding custom levels here for user API
	channel		   =  Ref{Csize_t}(0);
	a1			   =  Base.unsafe_convert(Cstring,"fc32");
	a2			   =  Base.unsafe_convert(Cstring,"sc16");
	a3			   =  Base.unsafe_convert(Cstring,uhdArgs);
	uhdArgs		   = uhd_stream_args_t(a1,a2,a3,channel,1);
	# ----------------------------------------------------
	# --- Sampling rate configuration
	# ----------------------------------------------------
	# --- Update the Rx sampling rate
	ccall((:uhd_usrp_set_rx_rate, libUHD), Cvoid, (Ptr{uhd_usrp}, Cdouble, Csize_t),pointerUSRP,samplingRate,0);
	# --- Get the Rx rate from the radio
	pointerRate  = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_rate, libUHD), Cvoid, (Ptr{uhd_usrp}, Csize_t, Ref{Cdouble}),pointerUSRP,0,pointerRate);
	updateRate  = pointerRate[];
	# --- Print a flag
	if updateRate != samplingRate
		@warnrx "Effective Rate is $(updateRate/1e6) MHz and not $(samplingRate/1e6) MHz\n"
	else
		# @inforx "Effective Rate is $(updateRate/1e6) MHz\n";
	end
	# ----------------------------------------------------
	# --- Carrier Frequency configuration
	# ----------------------------------------------------
	# --- Create structure for request
	a5			   =  Base.unsafe_convert(Cstring,"");
	tuneRequest	   = uhd_tune_request_t(carrierFreq,UHD_TUNE_REQUEST_POLICY_AUTO,carrierFreq,UHD_TUNE_REQUEST_POLICY_AUTO,200e6,a5);
	tunePointer	  = Ref{uhd_tune_request_t}(tuneRequest);
	pointerTuneResult	  = Ref{uhd_tune_result}();
	ccall((:uhd_usrp_set_rx_freq, libUHD), Cvoid, (Ptr{uhd_usrp}, Ptr{uhd_tune_request_t}, Csize_t, Ptr{uhd_tune_result}),pointerUSRP,tunePointer,0,pointerTuneResult);
	pointerCarrierFreq = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_freq, libUHD), Cvoid, (Ptr{uhd_usrp}, Csize_t, Ref{Cdouble}),pointerUSRP,0,pointerCarrierFreq);
	updateCarrierFreq	= pointerCarrierFreq[];
	if updateCarrierFreq != carrierFreq
		@warnrx "Effective carrier frequency is $(updateCarrierFreq/1e6) MHz and not $(carrierFreq/1e6) MHz\n"
	else
		# @inforx "Effective carrier frequency is $(updateCarrierFreq/1e6) MHz\n";
	end
	# ----------------------------------------------------
	# --- Gain configuration
	# ----------------------------------------------------
	# Update the UHD sampling rate
	ccall((:uhd_usrp_set_rx_gain, libUHD), Cvoid, (Ptr{uhd_usrp}, Cdouble, Csize_t, Cstring),pointerUSRP,gain,0,"");
	# Get the updated gain from UHD
	pointerGain	  = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_gain, libUHD), Cvoid, (Ptr{uhd_usrp}, Csize_t, Cstring,Ref{Cdouble}),pointerUSRP,0,"",pointerGain);
	updateGain	  = pointerGain[];
	# --- Print a flag
	if updateGain != gain
		@warnrx "Effective gain is $(updateGain) dB and not $(gain) dB\n"
	else
		# @inforx "Effective gain is $(updateGain) dB\n";
	end
	# ----------------------------------------------------
	# --- Antenna configuration
	# ----------------------------------------------------
	ccall((:uhd_usrp_set_rx_antenna, libUHD), Cvoid, (Ptr{uhd_usrp}, Cstring, Csize_t),pointerUSRP,antenna,0);
	# ----------------------------------------------------
	# --- Setting up streamer
	# ----------------------------------------------------
	# --- Setting up arguments
	pointerArgs	  = Ref{uhd_stream_args_t}(uhdArgs);
	ccall((:uhd_usrp_get_rx_stream, libUHD), Cvoid, (Ptr{uhd_usrp},Ptr{uhd_stream_args_t},Ptr{uhd_rx_streamer}),pointerUSRP,pointerArgs,uhd.pointerStreamer);
	# --- Getting number of samples ber buffer
	pointerSamples	  = Ref{Csize_t}(0);
	ccall((:uhd_rx_streamer_max_num_samps, libUHD), Cvoid, (Ptr{uhd_stream_args_t},Ref{Csize_t}),uhd.pointerStreamer,pointerSamples);
	nbSamples		  = pointerSamples[];
	# --- Create streamer master
    # streamCmd	= stream_cmd(UHD_STREAM_MODE_NUM_SAMPS_AND_DONE,nbSamples,true,0,0.0);
    # streamCmd	= stream_cmd(UHD_STREAM_MODE_START_CONTINUOUS,nbSamples,true,0,0.0);
	# pointerCmd	= Ref{stream_cmd}(streamCmd);
	# ccall((:uhd_rx_streamer_issue_stream_cmd, libUHD), Cvoid, (Ptr{uhd_stream_args_t},Ptr{stream_cmd}),uhd.pointerStreamer,pointerCmd);
	# ----------------------------------------------------
	# --- Create object and return
	# ----------------------------------------------------
	# --- Create the main Rx Object
	rx = UHDRx(uhd,updateCarrierFreq,updateRate,updateGain,antenna,nbSamples,0);
    # ----------------------------------------------------
    # --- Start streamer
    # ----------------------------------------------------
    restartStreamer(rx)
    return rx
end

"""
Restart the USRP streamer. In some cases (especially macOS) we have an issue with streamer congestion and we need to restart it.
By now, we have added the restart function in recv! method.
"""
@inline function restartStreamer(radio::UHDRx)
    # ----------------------------------------------------
    # --- Start the streamer
    # ----------------------------------------------------
    streamCmd	= stream_cmd(UHD_STREAM_MODE_START_CONTINUOUS,radio.packetSize,true,0,0.0);
    pointerCmd	= Ref{stream_cmd}(streamCmd);
    ccall((:uhd_rx_streamer_issue_stream_cmd, libUHD), Cvoid, (Ptr{uhd_stream_args_t},Ptr{stream_cmd}),radio.uhd.pointerStreamer,pointerCmd);
end

function updateSamplingRate!(radio::UHDRx,samplingRate)
	# ----------------------------------------------------
	# --- Sampling rate configuration
	# ----------------------------------------------------
	# @inforx  "Try to change rate from $(radio.samplingRate/1e6) MHz to $(samplingRate/1e6) MHz";
	# --- Update the Rx sampling rate
	ccall((:uhd_usrp_set_rx_rate, libUHD), Cvoid, (Ptr{uhd_usrp}, Cdouble, Csize_t),radio.uhd.pointerUSRP,samplingRate,0);
	# --- Get the Rx rate from the radio
	pointerRate  = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_rate, libUHD), Cvoid, (Ptr{uhd_usrp}, Csize_t, Ref{Cdouble}),radio.uhd.pointerUSRP,0,pointerRate);
	updateRate  = pointerRate[];
	# --- Print a flag
	if updateRate != samplingRate
		@warnrx "Effective Rate is $(updateRate/1e6) MHz and not $(samplingRate/1e6) MHz\n"
	else
		# @inforx "Effective Rate is $(updateRate/1e6) MHz\n";
	end
	radio.samplingRate = updateRate;
end

function updateGain!(radio::UHDRx,gain)
	# ----------------------------------------------------
	# --- Sampling rate configuration
	# ----------------------------------------------------
	# @inforx  "Try to change gain from $(radio.gain) dB to $(gain) dB";
	# Update the UHD sampling rate
	ccall((:uhd_usrp_set_rx_gain, libUHD), Cvoid, (Ptr{uhd_usrp}, Cdouble, Csize_t, Cstring),radio.uhd.pointerUSRP,gain,0,"");
	# Get the updated gain from UHD
	pointerGain	  = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_gain, libUHD), Cvoid, (Ptr{uhd_usrp}, Csize_t, Cstring,Ref{Cdouble}),radio.uhd.pointerUSRP,0,"",pointerGain);
	updateGain	  = pointerGain[];
	# --- Print a flag
	if updateGain != gain
		@warnrx "Effective gain is $(updateGain) dB and not $(gain) dB\n"
	else
		# @inforx "Effective gain is $(updateGain) dB\n";
	end
	radio.gain = updateGain;
	return updateGain;
end

function updateCarrierFreq!(radio::UHDRx,carrierFreq)
	# ----------------------------------------------------
	# --- Carrier Frequency configuration
	# ----------------------------------------------------
	# @inforx  "Try to change carrier frequency from $(radio.carrierFreq/1e6) MHz to $(carrierFreq/1e6) MHz";
	a5			   =  Base.unsafe_convert(Cstring,"");
	tuneRequest	   = uhd_tune_request_t(carrierFreq,UHD_TUNE_REQUEST_POLICY_AUTO,carrierFreq,UHD_TUNE_REQUEST_POLICY_AUTO,200e6,a5)
	# tuneRequest   = uhd_tune_request_t(carrierFreq,UHD_TUNE_REQUEST_POLICY_AUTO,UHD_TUNE_REQUEST_POLICY_AUTO);
	tunePointer	  = Ref{uhd_tune_request_t}(tuneRequest);
	pointerTuneResult	  = Ref{uhd_tune_result}();
	ccall((:uhd_usrp_set_rx_freq, libUHD), Cvoid, (Ptr{uhd_usrp}, Ptr{uhd_tune_request_t}, Csize_t, Ptr{uhd_tune_result}),radio.uhd.pointerUSRP,tunePointer,0,pointerTuneResult);
	pointerCarrierFreq = Ref{Cdouble}(0);
	# sleep(0.001);
	ccall((:uhd_usrp_get_rx_freq, libUHD), Cvoid, (Ptr{uhd_usrp}, Csize_t, Ref{Cdouble}),radio.uhd.pointerUSRP,0,pointerCarrierFreq);
	updateCarrierFreq	= pointerCarrierFreq[];
	if updateCarrierFreq != carrierFreq
		@warnrx "Effective carrier frequency is $(updateCarrierFreq/1e6) MHz and not $(carrierFreq/1e6) MHz\n"
	else
		# @inforx "Effective carrier frequency is $(updateCarrierFreq/1e6) MHz\n";
	end
	radio.carrierFreq = updateCarrierFreq;
	return updateCarrierFreq;
end

"""
Get a single buffer from the USRP device, and create all the necessary ressources

# --- Syntax

sig	  = recv(radio,nbSamples)
# --- Input parameters
- radio	  : UHD object [UHDRx]
- nbSamples : Desired number of samples [Int]
# --- Output parameters
- sig	  : baseband signal from radio [Array{Complex{CFloat}},radio.packetSize]
"""
function recv(radio,nbSamples);
	# --- Create the global container
	sigRx	= zeros(Complex{Cfloat},nbSamples);
	# --- Populate the buffer
	nbSamples = recv!(sigRx,radio);
	return sigRx
end

"""
Get a single buffer from the USRP device, using the Buffer structure

# --- Syntax

recv!(sig,radio,nbSamples)
# --- Input parameters
- sig	  : Complex signal to populate [Array{Complex{Cfloat}}]
- radio	  : UHD object [UHDRx]
- buffer  : Buffer object (obtained with setBuffer(radio)) [Buffer]
# --- Output parameters
-
"""
function recv!(sig,radio::UHDRx;nbSamples=0,offset=0)
    restartStreamer(radio)
	# --- Defined parameters for multiple buffer reception
	filled		= false;
	# --- Fill the input buffer @ a specific offset
	if offset == 0
		posT		= Csize_t(0);
	else
		posT 		= Csize_t(offset);
	end
	# --- Managing desired size and buffer size
	if nbSamples == 0
		# --- Fill all the buffer
		# x2 as input is complex and we feed real words
		nbSamples	= Csize_t(length(sig));
	else
		# ---  x2 as input is complex and we feed real words
		nbSamples 	= Csize_t(nbSamples);
		# --- Ensure that the allocation is possible
		@assert nbSamples < (length(sig)+posT) "Impossible to fill the buffer (number of samples > residual size";
	end
	while !filled
		# --- Get a buffer: We should have radio.packetSize or less
		# radio.packetSize is the complex size, so x2
		(posT+radio.packetSize> nbSamples) ? n = nbSamples - posT : n = radio.packetSize;
		# --- To avoid memcopy, we direclty feed the pointer at the appropriate solution
		ptr=Ref(Ptr{Cvoid}(pointer(sig,1+posT)));
		# --- Populate buffer with radio samples
		cSamples 	= populateBuffer!(radio,ptr,n);
		# cSamples  = populateBuffer!(radio,n);
		# --- Populate the complete buffer
		# sig[posT .+ (1:cSamples)] .= reinterpret(Complex{Cfloat},@view radio.buffer.x[1:2cSamples]);
		# sig[posT .+ (1:cSamples)] .= reinterpret(Complex{Cfloat},radio.buffer.x[1:2cSamples]);
		# --- Update counters
		posT += cSamples;
		# @show Int(cSamples),Int(posT)
		# --- Breaking flag
		(posT == nbSamples) ? filled = true : filled = false;
	end
	return posT
end

"""
Calling UHD function wrapper to fill a buffer. It is preferable to cal this function though the use of recv or recv!

# --- Syntax

recv!(sig,radio,nbSamples)
# --- Input parameters
- radio	  	: UHD object [UHDRx]
- ptr  		: Writable memory position [Ref{Ptr{Cvoid}}]
- nbSamples : Number of samples to acquire
# --- Output parameters
- nbSamp 	: Number of samples fill in buffer [Csize_t]
"""
function populateBuffer!(radio,ptr,nbSamples::Csize_t=0)
	# --- Getting number of samples
	# If not specified, we get back to radio.packetSize
	if (nbSamples == Csize_t(0))
		nbSamples = radio.packetSize;
	end
	#@assert nbSamples <= length(buffer.x) "Number of desired samples can not be greater than buffer size";
	# --- Effectively recover data
	# ccall((:uhd_rx_streamer_recv, libUHD), Cvoid,(Ptr{uhd_rx_streamer},Ptr{Ptr{Cvoid}},Csize_t,Ptr{Ptr{uhd_rx_metadata}},Cfloat,Cint,Ref{Csize_t}),radio.uhd.pointerStreamer,ptr,nbSamples,radio.uhd.addressMD,0.1,false,radio.uhd.pointerSamples);
	pointerSamples = Ref{Csize_t}(0);
	ccall((:uhd_rx_streamer_recv, libUHD), Cvoid,(Ptr{uhd_rx_streamer},Ptr{Ptr{Cvoid}},Csize_t,Ptr{Ptr{uhd_rx_metadata}},Cfloat,Cint,Ref{Csize_t}),radio.uhd.pointerStreamer,ptr,nbSamples,radio.uhd.addressMD,0.1,false,pointerSamples);
		# --- Pointer deferencing
	return pointerSamples[];
end#

"""
Returns the Error flag of the current UHD burst

# --- Syntax

flag = getError(radio)
# --- Input parameters
- radio : UHD object [UHDRx]
# --- Output parameters
- err	: Error Flag [error_code_t]
"""
function getError(radio::UHDRx)
	ptrErr = Ref{error_code_t}();
	ccall((:uhd_rx_metadata_error_code,libUHD), Cvoid,(Ptr{uhd_rx_metadata},Ref{error_code_t}),radio.uhd.pointerMD,ptrErr);
	return err = ptrErr[];
end

"""
Return the timestamp of the last UHD burst

# --- Syntax

(second,fracSecond) = getTimestamp(radio)
# --- Input parameters
- radio	  : UHD UHD object [UHDRx]
# --- Output parameters
- second  : Second value for the flag [Int]
- fracSecond : Fractional second value [Float64]
"""
function getTimestamp(radio::UHDRx)
	ptrFullSec = Ref{FORMAT_LONG}();
	ptrFracSec = Ref{Cdouble}();
	ccall( (:uhd_rx_metadata_time_spec,libUHD), Cvoid, (Ptr{uhd_rx_metadata},Ref{FORMAT_LONG},Ref{Cdouble}),radio.uhd.pointerMD,ptrFullSec,ptrFracSec);
	return (ptrFullSec[],ptrFracSec[]);
end

function Base.close(radio::UHDRx)
	# --- Checking realease nature
	# There is one flag to avoid double close (that leads to seg fault)
	if radio.released == 0
		@assert_uhd ccall((:uhd_rx_streamer_free, libUHD), uhd_error, (Ptr{Ptr{uhd_rx_streamer}},),radio.uhd.addressStream);
		@assert_uhd ccall((:uhd_rx_metadata_free, libUHD), uhd_error, (Ptr{Ptr{uhd_rx_metadata}},),radio.uhd.addressMD);
	else
		# print a warning
		@warn "UHD ressource was already released, abort call";
	end
	# --- Force flag value
	radio.released = 1;
end

function Base.print(radio::UHDRx)
	# Get the gain from UHD
	pointerGain	  = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_gain, libUHD), Cvoid, (Ptr{Cvoid}, Csize_t, Cstring,Ref{Cdouble}),radio.uhd.pointerUSRP,0,"",pointerGain);
	updateGain	  = pointerGain[];
	# Get the rate from UHD
	pointerRate	  = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_rate, libUHD), Cvoid, (Ptr{Cvoid}, Csize_t, Ref{Cdouble}),radio.uhd.pointerUSRP,0,pointerRate);
	updateRate	  = pointerRate[];
	# Get the freq from UHD
	pointerFreq	  = Ref{Cdouble}(0);
	ccall((:uhd_usrp_get_rx_freq, libUHD), Cvoid, (Ptr{Cvoid}, Csize_t, Ref{Cdouble}),radio.uhd.pointerUSRP,0,pointerFreq);
	updateFreq	  = pointerFreq[];
	# Print message
	strF  = @sprintf(" Carrier Frequency: %2.3f MHz\n Sampling Frequency: %2.3f MHz\n Rx Gain: %2.2f dB\n",updateFreq/1e6,updateRate/1e6,updateGain);
	@inforx "Current UHD Configuration in Rx mode\n$strF";
end


text:
using Test
using GeoPhyInv
using LinearMaps

for scenario in [:downhole, :pizza]
	println("@@@@@@@@@@@@TESTING ", scenario)
	for rfields in [[:p], [:vx], [:vz]]
		pa=SeisInvExpt(FdtdAcouBorn(), LS(), scenario, rfields=rfields)

		F=LinearMap(pa);

		x1=randn(size(F,2))
		x2=randn(size(F,2))
		x12=x1.+x2

		d12=F*x12
		d1=F*x1
		δmodKI1=copy(pa.paf.c.δmod[:KI])
		d2=F*x2
		δmodKI2=copy(pa.paf.c.δmod[:KI])

		d12new=d1.+d2

		f=squared_euclidean!(nothing, d12, d12new, nothing, norm_flag=true)

		@test f<1e-25

		function adjtest()
			x=randn(size(F,2))
			y=randn(size(F,1))
			a=LinearAlgebra.dot(y,F*x)
			b=LinearAlgebra.dot(x,adjoint(F)*y)
			c=LinearAlgebra.dot(x, transpose(F)*F*x)
			println("adjoint test: ", a, "\t", b)
			@test isapprox(a,b,rtol=1e-5)
			println("must be positive: ", c)
			@test c>0.0
		end

		for i in 1:1
			adjtest()
		end
	end
end


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

function HYPRE_StructVectorAssemble(vector::HYPRE_StructVector)
    ccall((:HYPRE_StructVectorAssemble,libHypre),HYPRE_Int,(HYPRE_StructVector,),vector)
end

function HYPRE_StructVectorGetValues(vector::HYPRE_StructVector,index,value)
    ccall((:HYPRE_StructVectorGetValues,libHypre),HYPRE_Int,(HYPRE_StructVector,Ptr{HYPRE_Int},Ptr{HYPRE_Complex}),vector,index,value)
end

function HYPRE_StructVectorGetBoxValues(vector::HYPRE_StructVector,ilower,iupper,values)
    ccall((:HYPRE_StructVectorGetBoxValues,libHypre),HYPRE_Int,(HYPRE_StructVector,Ptr{HYPRE_Int},Ptr{HYPRE_Int},Ptr{HYPRE_Complex}),vector,ilower,iupper,values)
end

function HYPRE_StructVectorPrint(filename,vector::HYPRE_StructVector,all::HYPRE_Int)
    ccall((:HYPRE_StructVectorPrint,libHypre),HYPRE_Int,(Cstring,HYPRE_StructVector,HYPRE_Int),filename,vector,all)
end

function HYPRE_StructVectorSetNumGhost(vector::HYPRE_StructVector,num_ghost)
    ccall((:HYPRE_StructVectorSetNumGhost,libHypre),HYPRE_Int,(HYPRE_StructVector,Ptr{HYPRE_Int}),vector,num_ghost)
end

function HYPRE_StructVectorSetConstantValues(vector::HYPRE_StructVector,values::HYPRE_Complex)
    ccall((:HYPRE_StructVectorSetConstantValues,libHypre),HYPRE_Int,(HYPRE_StructVector,HYPRE_Complex),vector,values)
end

function HYPRE_StructVectorGetMigrateCommPkg(from_vector::HYPRE_StructVector,to_vector::HYPRE_StructVector,comm_pkg)
    ccall((:HYPRE_StructVectorGetMigrateCommPkg,libHypre),HYPRE_Int,(HYPRE_StructVector,HYPRE_StructVector,Ptr{HYPRE_CommPkg}),from_vector,to_vector,comm_pkg)
end

function HYPRE_StructVectorMigrate(comm_pkg::HYPRE_CommPkg,from_vector::HYPRE_StructVector,to_vector::HYPRE_StructVector)
    ccall((:HYPRE_StructVectorMigrate,libHypre),HYPRE_Int,(HYPRE_CommPkg,HYPRE_StructVector,HYPRE_StructVector),comm_pkg,from_vector,to_vector)
end

function HYPRE_CommPkgDestroy(comm_pkg::HYPRE_CommPkg)
    ccall((:HYPRE_CommPkgDestroy,libHypre),HYPRE_Int,(HYPRE_CommPkg,),comm_pkg)
end

function HYPRE_StructVectorClone(x::HYPRE_StructVector,y_ptr)
    ccall((:HYPRE_StructVectorClone,libHypre),HYPRE_Int,(HYPRE_StructVector,Ptr{HYPRE_StructVector}),x,y_ptr)
end

function hypre_ProjectBox(box,index::hypre_Index,stride::hypre_Index)
    ccall((:hypre_ProjectBox,libHypre),HYPRE_Int,(Ptr{hypre_Box},hypre_Index,hypre_Index),box,index,stride)
end

function hypre_ProjectBoxArray(box_array,index::hypre_Index,stride::hypre_Index)
    ccall((:hypre_ProjectBoxArray,libHypre),HYPRE_Int,(Ptr{hypre_BoxArray},hypre_Index,hypre_Index),box_array,index,stride)
end

function hypre_ProjectBoxArrayArray(box_array_array,index::hypre_Index,stride::hypre_Index)
    ccall((:hypre_ProjectBoxArrayArray,libHypre),HYPRE_Int,(Ptr{hypre_BoxArrayArray},hypre_Index,hypre_Index),box_array_array,index,stride)
end

function hypre_StructAxpy(alpha::HYPRE_Complex,x,y)
    ccall((:hypre_StructAxpy,libHypre),HYPRE_Int,(HYPRE_Complex,Ptr{hypre_StructVector},Ptr{hypre_StructVector}),alpha,x,y)
end

function hypre_CommPkgCreate(comm_info,send_data_space,recv_data_space,num_values::HYPRE_Int,orders,reverse::HYPRE_Int,comm::MPI.Comm,comm_pkg_ptr)
    ccall((:hypre_CommPkgCreate,libHypre),HYPRE_Int,(Ptr{hypre_CommInfo},Ptr{hypre_BoxArray},Ptr{hypre_BoxArray},HYPRE_Int,Ptr{Ptr{HYPRE_Int}},HYPRE_Int,MPI.Comm,Ptr{Ptr{hypre_CommPkg}}),comm_info,send_data_space,recv_data_space,num_values,orders,reverse,comm,comm_pkg_ptr)
end

function hypre_CommTypeSetEntries(comm_type,boxnums,boxes,stride::hypre_Index,coord::hypre_Index,dir::hypre_Index,order,data_space,data_offsets)
    ccall((:hypre_CommTypeSetEntries,libHypre),HYPRE_Int,(Ptr{hypre_CommType},Ptr{HYPRE_Int},Ptr{hypre_Box},hypre_Index,hypre_Index,hypre_Index,Ptr{HYPRE_Int},Ptr{hypre_BoxArray},Ptr{HYPRE_Int}),comm_type,boxnums,boxes,stride,coord,dir,order,data_space,data_offsets)
end

function hypre_CommTypeSetEntry(box,stride::hypre_Index,coord::hypre_Index,dir::hypre_Index,order,data_box,data_box_offset::HYPRE_Int,comm_entry)
    ccall((:hypre_CommTypeSetEntry,libHypre),HYPRE_Int,(Ptr{hypre_Box},hypre_Index,hypre_Index,hypre_Index,Ptr{HYPRE_Int},Ptr{hypre_Box},HYPRE_Int,Ptr{hypre_CommEntryType}),box,stride,coord,dir,order,data_box,data_box_offset,comm_entry)
end

function hypre_InitializeCommunication(comm_pkg,send_data,recv_data,action::HYPRE_Int,tag::HYPRE_Int,comm_handle_ptr)
    ccall((:hypre_InitializeCommunication,libHypre),HYPRE_Int,(Ptr{hypre_CommPkg},Ptr{HYPRE_Complex},Ptr{HYPRE_Complex},HYPRE_Int,HYPRE_Int,Ptr{Ptr{hypre_CommHandle}}),comm_pkg,send_data,recv_data,action,tag,comm_handle_ptr)
end

function hypre_FinalizeCommunication(comm_handle)
    ccall((:hypre_FinalizeCommunication,libHypre),HYPRE_Int,(Ptr{hypre_CommHandle},),comm_handle)
end

function hypre_ExchangeLocalData(comm_pkg,send_data,recv_data,action::HYPRE_Int)
    ccall((:hypre_ExchangeLocalData,libHypre),HYPRE_Int,(Ptr{hypre_CommPkg},Ptr{HYPRE_Complex},Ptr{HYPRE_Complex},HYPRE_Int),comm_pkg,send_data,recv_data,action)
end

function hypre_StructCopy(x,y)
    ccall((:hypre_StructCopy,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},Ptr{hypre_StructVector}),x,y)
end

function hypre_StructPartialCopy(x,y,array_boxes)
    ccall((:hypre_StructPartialCopy,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},Ptr{hypre_StructVector},Ptr{hypre_BoxArrayArray}),x,y,array_boxes)
end

function hypre_StructGridCreate(comm::MPI.Comm,dim::HYPRE_Int,grid_ptr)
    ccall((:hypre_StructGridCreate,libHypre),HYPRE_Int,(MPI.Comm,HYPRE_Int,Ptr{Ptr{hypre_StructGrid}}),comm,dim,grid_ptr)
end

function hypre_StructGridRef(grid,grid_ref)
    ccall((:hypre_StructGridRef,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},Ptr{Ptr{hypre_StructGrid}}),grid,grid_ref)
end

function hypre_StructGridDestroy(grid)
    ccall((:hypre_StructGridDestroy,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},),grid)
end

function hypre_StructGridSetPeriodic(grid,periodic::hypre_Index)
    ccall((:hypre_StructGridSetPeriodic,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},hypre_Index),grid,periodic)
end

function hypre_StructGridSetExtents(grid,ilower::hypre_Index,iupper::hypre_Index)
    ccall((:hypre_StructGridSetExtents,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},hypre_Index,hypre_Index),grid,ilower,iupper)
end

function hypre_StructGridSetBoxes(grid,boxes)
    ccall((:hypre_StructGridSetBoxes,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},Ptr{hypre_BoxArray}),grid,boxes)
end

function hypre_StructGridSetBoundingBox(grid,new_bb)
    ccall((:hypre_StructGridSetBoundingBox,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},Ptr{hypre_Box}),grid,new_bb)
end

function hypre_StructGridSetIDs(grid,ids)
    ccall((:hypre_StructGridSetIDs,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},Ptr{HYPRE_Int}),grid,ids)
end

function hypre_StructGridSetBoxManager(grid,boxman)
    ccall((:hypre_StructGridSetBoxManager,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},Ptr{hypre_BoxManager}),grid,boxman)
end

function hypre_StructGridSetMaxDistance(grid,dist::hypre_Index)
    ccall((:hypre_StructGridSetMaxDistance,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},hypre_Index),grid,dist)
end

function hypre_StructGridAssemble(grid)
    ccall((:hypre_StructGridAssemble,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},),grid)
end

function hypre_GatherAllBoxes(comm::MPI.Comm,boxes,dim::HYPRE_Int,all_boxes_ptr,all_procs_ptr,first_local_ptr)
    ccall((:hypre_GatherAllBoxes,libHypre),HYPRE_Int,(MPI.Comm,Ptr{hypre_BoxArray},HYPRE_Int,Ptr{Ptr{hypre_BoxArray}},Ptr{Ptr{HYPRE_Int}},Ptr{HYPRE_Int}),comm,boxes,dim,all_boxes_ptr,all_procs_ptr,first_local_ptr)
end

function hypre_ComputeBoxnums(boxes,procs,boxnums_ptr)
    ccall((:hypre_ComputeBoxnums,libHypre),HYPRE_Int,(Ptr{hypre_BoxArray},Ptr{HYPRE_Int},Ptr{Ptr{HYPRE_Int}}),boxes,procs,boxnums_ptr)
end

function hypre_StructGridSetNumGhost(grid,num_ghost)
    ccall((:hypre_StructGridSetNumGhost,libHypre),HYPRE_Int,(Ptr{hypre_StructGrid},Ptr{HYPRE_Int}),grid,num_ghost)
end

function hypre_StructInnerProd(x,y)
    ccall((:hypre_StructInnerProd,libHypre),HYPRE_Real,(Ptr{hypre_StructVector},Ptr{hypre_StructVector}),x,y)
end

function hypre_PrintBoxArrayData(file,box_array,data_space,num_values::HYPRE_Int,dim::HYPRE_Int,data)
    ccall((:hypre_PrintBoxArrayData,libHypre),HYPRE_Int,(Ptr{Void},Ptr{hypre_BoxArray},Ptr{hypre_BoxArray},HYPRE_Int,HYPRE_Int,Ptr{HYPRE_Complex}),file,box_array,data_space,num_values,dim,data)
end

function hypre_PrintCCVDBoxArrayData(file,box_array,data_space,num_values::HYPRE_Int,center_rank::HYPRE_Int,stencil_size::HYPRE_Int,symm_elements,dim::HYPRE_Int,data)
    ccall((:hypre_PrintCCVDBoxArrayData,libHypre),HYPRE_Int,(Ptr{Void},Ptr{hypre_BoxArray},Ptr{hypre_BoxArray},HYPRE_Int,HYPRE_Int,HYPRE_Int,Ptr{HYPRE_Int},HYPRE_Int,Ptr{HYPRE_Complex}),file,box_array,data_space,num_values,center_rank,stencil_size,symm_elements,dim,data)
end

function hypre_PrintCCBoxArrayData(file,box_array,data_space,num_values::HYPRE_Int,data)
    ccall((:hypre_PrintCCBoxArrayData,libHypre),HYPRE_Int,(Ptr{Void},Ptr{hypre_BoxArray},Ptr{hypre_BoxArray},HYPRE_Int,Ptr{HYPRE_Complex}),file,box_array,data_space,num_values,data)
end

function hypre_ReadBoxArrayData(file,box_array,data_space,num_values::HYPRE_Int,dim::HYPRE_Int,data)
    ccall((:hypre_ReadBoxArrayData,libHypre),HYPRE_Int,(Ptr{Void},Ptr{hypre_BoxArray},Ptr{hypre_BoxArray},HYPRE_Int,HYPRE_Int,Ptr{HYPRE_Complex}),file,box_array,data_space,num_values,dim,data)
end

function hypre_ReadBoxArrayData_CC(file,box_array,data_space,stencil_size::HYPRE_Int,real_stencil_size::HYPRE_Int,constant_coefficient::HYPRE_Int,dim::HYPRE_Int,data)
    ccall((:hypre_ReadBoxArrayData_CC,libHypre),HYPRE_Int,(Ptr{Void},Ptr{hypre_BoxArray},Ptr{hypre_BoxArray},HYPRE_Int,HYPRE_Int,HYPRE_Int,HYPRE_Int,Ptr{HYPRE_Complex}),file,box_array,data_space,stencil_size,real_stencil_size,constant_coefficient,dim,data)
end

function hypre_StructMatrixExtractPointerByIndex(matrix,b::HYPRE_Int,index::hypre_Index)
    ccall((:hypre_StructMatrixExtractPointerByIndex,libHypre),Ptr{HYPRE_Complex},(Ptr{hypre_StructMatrix},HYPRE_Int,hypre_Index),matrix,b,index)
end

function hypre_StructMatrixCreate(comm::MPI.Comm,grid,user_stencil)
    ccall((:hypre_StructMatrixCreate,libHypre),Ptr{hypre_StructMatrix},(MPI.Comm,Ptr{hypre_StructGrid},Ptr{hypre_StructStencil}),comm,grid,user_stencil)
end

function hypre_StructMatrixRef(matrix)
    ccall((:hypre_StructMatrixRef,libHypre),Ptr{hypre_StructMatrix},(Ptr{hypre_StructMatrix},),matrix)
end

function hypre_StructMatrixDestroy(matrix)
    ccall((:hypre_StructMatrixDestroy,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},),matrix)
end

function hypre_StructMatrixInitializeShell(matrix)
    ccall((:hypre_StructMatrixInitializeShell,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},),matrix)
end

function hypre_StructMatrixInitializeData(matrix,data)
    ccall((:hypre_StructMatrixInitializeData,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},Ptr{HYPRE_Complex}),matrix,data)
end

function hypre_StructMatrixInitialize(matrix)
    ccall((:hypre_StructMatrixInitialize,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},),matrix)
end

function hypre_StructMatrixSetValues(matrix,grid_index::hypre_Index,num_stencil_indices::HYPRE_Int,stencil_indices,values,action::HYPRE_Int,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructMatrixSetValues,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},hypre_Index,HYPRE_Int,Ptr{HYPRE_Int},Ptr{HYPRE_Complex},HYPRE_Int,HYPRE_Int,HYPRE_Int),matrix,grid_index,num_stencil_indices,stencil_indices,values,action,boxnum,outside)
end

function hypre_StructMatrixSetBoxValues(matrix,set_box,value_box,num_stencil_indices::HYPRE_Int,stencil_indices,values,action::HYPRE_Int,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructMatrixSetBoxValues,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},Ptr{hypre_Box},Ptr{hypre_Box},HYPRE_Int,Ptr{HYPRE_Int},Ptr{HYPRE_Complex},HYPRE_Int,HYPRE_Int,HYPRE_Int),matrix,set_box,value_box,num_stencil_indices,stencil_indices,values,action,boxnum,outside)
end

function hypre_StructMatrixSetConstantValues(matrix,num_stencil_indices::HYPRE_Int,stencil_indices,values,action::HYPRE_Int)
    ccall((:hypre_StructMatrixSetConstantValues,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},HYPRE_Int,Ptr{HYPRE_Int},Ptr{HYPRE_Complex},HYPRE_Int),matrix,num_stencil_indices,stencil_indices,values,action)
end

function hypre_StructMatrixClearValues(matrix,grid_index::hypre_Index,num_stencil_indices::HYPRE_Int,stencil_indices,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructMatrixClearValues,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},hypre_Index,HYPRE_Int,Ptr{HYPRE_Int},HYPRE_Int,HYPRE_Int),matrix,grid_index,num_stencil_indices,stencil_indices,boxnum,outside)
end

function hypre_StructMatrixClearBoxValues(matrix,clear_box,num_stencil_indices::HYPRE_Int,stencil_indices,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructMatrixClearBoxValues,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},Ptr{hypre_Box},HYPRE_Int,Ptr{HYPRE_Int},HYPRE_Int,HYPRE_Int),matrix,clear_box,num_stencil_indices,stencil_indices,boxnum,outside)
end

function hypre_StructMatrixAssemble(matrix)
    ccall((:hypre_StructMatrixAssemble,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},),matrix)
end

function hypre_StructMatrixSetNumGhost(matrix,num_ghost)
    ccall((:hypre_StructMatrixSetNumGhost,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},Ptr{HYPRE_Int}),matrix,num_ghost)
end

function hypre_StructMatrixSetConstantCoefficient(matrix,constant_coefficient::HYPRE_Int)
    ccall((:hypre_StructMatrixSetConstantCoefficient,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},HYPRE_Int),matrix,constant_coefficient)
end

function hypre_StructMatrixSetConstantEntries(matrix,nentries::HYPRE_Int,entries)
    ccall((:hypre_StructMatrixSetConstantEntries,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},HYPRE_Int,Ptr{HYPRE_Int}),matrix,nentries,entries)
end

function hypre_StructMatrixClearGhostValues(matrix)
    ccall((:hypre_StructMatrixClearGhostValues,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},),matrix)
end

function hypre_StructMatrixPrint(filename,matrix,all::HYPRE_Int)
    ccall((:hypre_StructMatrixPrint,libHypre),HYPRE_Int,(Cstring,Ptr{hypre_StructMatrix},HYPRE_Int),filename,matrix,all)
end

function hypre_StructMatrixMigrate(from_matrix,to_matrix)
    ccall((:hypre_StructMatrixMigrate,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},Ptr{hypre_StructMatrix}),from_matrix,to_matrix)
end

function hypre_StructMatrixRead(comm::MPI.Comm,filename,num_ghost)
    ccall((:hypre_StructMatrixRead,libHypre),Ptr{hypre_StructMatrix},(MPI.Comm,Cstring,Ptr{HYPRE_Int}),comm,filename,num_ghost)
end

function hypre_StructMatrixClearBoundary(matrix)
    ccall((:hypre_StructMatrixClearBoundary,libHypre),HYPRE_Int,(Ptr{hypre_StructMatrix},),matrix)
end

function hypre_StructMatrixCreateMask(matrix,num_stencil_indices::HYPRE_Int,stencil_indices)
    ccall((:hypre_StructMatrixCreateMask,libHypre),Ptr{hypre_StructMatrix},(Ptr{hypre_StructMatrix},HYPRE_Int,Ptr{HYPRE_Int}),matrix,num_stencil_indices,stencil_indices)
end

function hypre_StructMatvecCreate()
    ccall((:hypre_StructMatvecCreate,libHypre),Ptr{Void},())
end

function hypre_StructMatvecSetup(matvec_vdata,A,x)
    ccall((:hypre_StructMatvecSetup,libHypre),HYPRE_Int,(Ptr{Void},Ptr{hypre_StructMatrix},Ptr{hypre_StructVector}),matvec_vdata,A,x)
end

function hypre_StructMatvecCompute(matvec_vdata,alpha::HYPRE_Complex,A,x,beta::HYPRE_Complex,y)
    ccall((:hypre_StructMatvecCompute,libHypre),HYPRE_Int,(Ptr{Void},HYPRE_Complex,Ptr{hypre_StructMatrix},Ptr{hypre_StructVector},HYPRE_Complex,Ptr{hypre_StructVector}),matvec_vdata,alpha,A,x,beta,y)
end

function hypre_StructMatvecCC0(alpha::HYPRE_Complex,A,x,y,compute_box_aa,stride::hypre_IndexRef)
    ccall((:hypre_StructMatvecCC0,libHypre),HYPRE_Int,(HYPRE_Complex,Ptr{hypre_StructMatrix},Ptr{hypre_StructVector},Ptr{hypre_StructVector},Ptr{hypre_BoxArrayArray},hypre_IndexRef),alpha,A,x,y,compute_box_aa,stride)
end

function hypre_StructMatvecCC1(alpha::HYPRE_Complex,A,x,y,compute_box_aa,stride::hypre_IndexRef)
    ccall((:hypre_StructMatvecCC1,libHypre),HYPRE_Int,(HYPRE_Complex,Ptr{hypre_StructMatrix},Ptr{hypre_StructVector},Ptr{hypre_StructVector},Ptr{hypre_BoxArrayArray},hypre_IndexRef),alpha,A,x,y,compute_box_aa,stride)
end

function hypre_StructMatvecCC2(alpha::HYPRE_Complex,A,x,y,compute_box_aa,stride::hypre_IndexRef)
    ccall((:hypre_StructMatvecCC2,libHypre),HYPRE_Int,(HYPRE_Complex,Ptr{hypre_StructMatrix},Ptr{hypre_StructVector},Ptr{hypre_StructVector},Ptr{hypre_BoxArrayArray},hypre_IndexRef),alpha,A,x,y,compute_box_aa,stride)
end

function hypre_StructMatvecDestroy(matvec_vdata)
    ccall((:hypre_StructMatvecDestroy,libHypre),HYPRE_Int,(Ptr{Void},),matvec_vdata)
end

function hypre_StructMatvec(alpha::HYPRE_Complex,A,x,beta::HYPRE_Complex,y)
    ccall((:hypre_StructMatvec,libHypre),HYPRE_Int,(HYPRE_Complex,Ptr{hypre_StructMatrix},Ptr{hypre_StructVector},HYPRE_Complex,Ptr{hypre_StructVector}),alpha,A,x,beta,y)
end

function hypre_StructScale(alpha::HYPRE_Complex,y)
    ccall((:hypre_StructScale,libHypre),HYPRE_Int,(HYPRE_Complex,Ptr{hypre_StructVector}),alpha,y)
end

function hypre_StructStencilCreate(dim::HYPRE_Int,size::HYPRE_Int,shape)
    ccall((:hypre_StructStencilCreate,libHypre),Ptr{hypre_StructStencil},(HYPRE_Int,HYPRE_Int,Ptr{hypre_Index}),dim,size,shape)
end

function hypre_StructStencilRef(stencil)
    ccall((:hypre_StructStencilRef,libHypre),Ptr{hypre_StructStencil},(Ptr{hypre_StructStencil},),stencil)
end

function hypre_StructStencilDestroy(stencil)
    ccall((:hypre_StructStencilDestroy,libHypre),HYPRE_Int,(Ptr{hypre_StructStencil},),stencil)
end

function hypre_StructStencilElementRank(stencil,stencil_element::hypre_Index)
    ccall((:hypre_StructStencilElementRank,libHypre),HYPRE_Int,(Ptr{hypre_StructStencil},hypre_Index),stencil,stencil_element)
end

function hypre_StructStencilSymmetrize(stencil,symm_stencil_ptr,symm_elements_ptr)
    ccall((:hypre_StructStencilSymmetrize,libHypre),HYPRE_Int,(Ptr{hypre_StructStencil},Ptr{Ptr{hypre_StructStencil}},Ptr{Ptr{HYPRE_Int}}),stencil,symm_stencil_ptr,symm_elements_ptr)
end

function hypre_StructVectorRef(vector)
    ccall((:hypre_StructVectorRef,libHypre),Ptr{hypre_StructVector},(Ptr{hypre_StructVector},),vector)
end

function hypre_StructVectorInitializeShell(vector)
    ccall((:hypre_StructVectorInitializeShell,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},),vector)
end

function hypre_StructVectorInitializeData(vector,data)
    ccall((:hypre_StructVectorInitializeData,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},Ptr{HYPRE_Complex}),vector,data)
end

function hypre_StructVectorSetValues(vector,grid_index::hypre_Index,values,action::HYPRE_Int,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructVectorSetValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},hypre_Index,Ptr{HYPRE_Complex},HYPRE_Int,HYPRE_Int,HYPRE_Int),vector,grid_index,values,action,boxnum,outside)
end

function hypre_StructVectorSetBoxValues(vector,set_box,value_box,values,action::HYPRE_Int,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructVectorSetBoxValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},Ptr{hypre_Box},Ptr{hypre_Box},Ptr{HYPRE_Complex},HYPRE_Int,HYPRE_Int,HYPRE_Int),vector,set_box,value_box,values,action,boxnum,outside)
end

function hypre_StructVectorClearValues(vector,grid_index::hypre_Index,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructVectorClearValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},hypre_Index,HYPRE_Int,HYPRE_Int),vector,grid_index,boxnum,outside)
end

function hypre_StructVectorClearBoxValues(vector,clear_box,boxnum::HYPRE_Int,outside::HYPRE_Int)
    ccall((:hypre_StructVectorClearBoxValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},Ptr{hypre_Box},HYPRE_Int,HYPRE_Int),vector,clear_box,boxnum,outside)
end

function hypre_StructVectorClearAllValues(vector)
    ccall((:hypre_StructVectorClearAllValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},),vector)
end

function hypre_StructVectorSetConstantValues(vector,values::HYPRE_Complex)
    ccall((:hypre_StructVectorSetConstantValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},HYPRE_Complex),vector,values)
end

function hypre_StructVectorSetFunctionValues(vector,fcn)
    ccall((:hypre_StructVectorSetFunctionValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},Ptr{Void}),vector,fcn)
end

function hypre_StructVectorClearGhostValues(vector)
    ccall((:hypre_StructVectorClearGhostValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},),vector)
end

function hypre_StructVectorClearBoundGhostValues(vector,force::HYPRE_Int)
    ccall((:hypre_StructVectorClearBoundGhostValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},HYPRE_Int),vector,force)
end

function hypre_StructVectorRead(comm::MPI.Comm,filename,num_ghost)
    ccall((:hypre_StructVectorRead,libHypre),Ptr{hypre_StructVector},(MPI.Comm,Cstring,Ptr{HYPRE_Int}),comm,filename,num_ghost)
end

function hypre_StructVectorMaxValue(vector,max_value,max_index,max_xyz_index::hypre_Index)
    ccall((:hypre_StructVectorMaxValue,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},Ptr{HYPRE_Real},Ptr{HYPRE_Int},hypre_Index),vector,max_value,max_index,max_xyz_index)
end

function hypre_StructVectorClone(vector)
    ccall((:hypre_StructVectorClone,libHypre),Ptr{hypre_StructVector},(Ptr{hypre_StructVector},),vector)
end

function HYPRE_StructSetupInterpreter(i)
    ccall((:HYPRE_StructSetupInterpreter,libHypre),HYPRE_Int,(Ptr{mv_InterfaceInterpreter},),i)
end

function HYPRE_StructSetupMatvec(mv)
    ccall((:HYPRE_StructSetupMatvec,libHypre),HYPRE_Int,(Ptr{HYPRE_MatvecFunctions},),mv)
end

function hypre_StructVectorSetRandomValues(vector,seed::HYPRE_Int)
    ccall((:hypre_StructVectorSetRandomValues,libHypre),HYPRE_Int,(Ptr{hypre_StructVector},HYPRE_Int),vector,seed)
end

function hypre_StructSetRandomValues(v,seed::HYPRE_Int)
    ccall((:hypre_StructSetRandomValues,libHypre),HYPRE_Int,(Ptr{Void},HYPRE_Int),v,seed)
end


text:
"""Test
Test to launch in complex-modeler/src_test folder for example D:\repo\complex-modeler\src_test>julia global_test.jl

# Arguments
- type of instance (GOCInput, MatpowerInput, IIDMInput)
if GOCInput : julia global_test.jl GOCInput <instances folder> <instance name> <scenario name> <epsilon>
if MatpowerInput or IIDMInput : julia global_test.jl MatpowerInput <instances folder> <instance name> <epsilon>

"""
#TODO:: option sur les print
function read_arguments(ARGS)
    if length(ARGS)==0
        error("Arguments must be :
        Argument 1 is the type of instance (GOCInput, MatpowerInput or IIDMInput)\n
         julia global_test.jl GOCInput <instances folder> <instance name> <scenario name> <epsilon>
         julia global_test.jl MatpowerInput <instances folder> <instance name> <epsilon>
         example : julia global_test.jl MatpowerInput ..\data_Matpower\matpower case9.m 1e-20
         julia global_test.jl IIDMInput <instances folder> <instance name> <epsilon>

        ")
    end
    typeofinput = ARGS[1]
    if typeofinput=="GOCInput"
        typeofinput = GOCInput
        if length(ARGS)!=5
            error("Arguments must be : julia global_test.jl GOCInput <instances folder> <instance name> <scenario name> <epsilon>")
        else
            instance_path = joinpath(pwd(), ARGS[2], ARGS[3],ARGS[4])
            eps = ARGS[5]
        end

    elseif typeofinput=="MatpowerInput"
        typeofinput = MatpowerInput
        if length(ARGS)!=4
            error("Arguments must be : julia global_test.jl MatpowerInput <instances folder> <instance name> <epsilon> ")
        else
            instance_path = joinpath(pwd(), ARGS[2], ARGS[3])
            eps = ARGS[4]
        end

    elseif typeofinput=="IIDMInput"
        typeofinput = IIDMInput
        if length(ARGS)!=4
            error("Arguments must be : julia global_test.jl IIDMInput <instances folder> <instance name> <epsilon> ")
        else
            instance_path = joinpath(pwd(), ARGS[2], ARGS[3])
            eps = ARGS[4]
        end

    else
        error()
    end
    return typeofinput, instance_path, eps
end

ROOT = pwd()
include(joinpath(ROOT,"..","src_PowSysMod", "PowSysMod_body.jl"))
# include("para_fct.jl")
typeofinput, instance_path, eps = read_arguments(ARGS)

function build_and_solve_instance(typeofinput, instance_path)
    nb_variables = nb_constraints = 0
    obj = feas = 0.0

    tic()
    OPFpbs = load_OPFproblems(typeofinput, instance_path)

    ## Introducing coupling constraints on generator output
    (typeofinput != GOCInput) || introduce_Sgenvariables!(OPFpbs)

    ## Bulding optimization problem
    pb_global = build_globalpb!(OPFpbs)
    pb_global_real = pb_cplx2real(pb_global)

    ## Reading GOC initial point
    init_point = Point()
    (typeofinput != GOCInput) || (init_point = solution_point(instance_path))
    init_point_real = cplx2real(init_point)

    ## Exporting real problem
    if typeofinput != GOCInput
        instance_name  = String(split(instance_path,'\\')[end])
        amplexportpath = joinpath("..","knitro_runs", "$(instance_name[1:end-2])")
    else
        folder,scenario = split(instance_path, '\\')[end-1:end]
        folder = String(folder)
        scenario = String(scenario)
        amplexportpath = joinpath("..","knitro_runs", "$(folder[9:end])_$(scenario)")
    end
    export_to_dat(pb_global_real, amplexportpath, init_point_real)
    t_buildexport = toq()

    _, t_knitro, _ = @timed run_knitro(amplexportpath, joinpath(pwd(),"..","src_ampl"))
    pt_knitro, ~ = read_Knitro_output(amplexportpath, pb_global_real)
    feas = get_minslack(pb_global_real, pt_knitro)
    obj = get_objective(pb_global_real, pt_knitro)

    nb_variables = length(pb_global_real.variables)
    nb_constraints = length(pb_global_real.constraints)

    return String(split(instance_path,'\\')[end]) => (nb_variables, nb_constraints, obj, feas[1], t_buildexport, t_knitro)
end

function main(ARGS)
    typeofinput, instance_path, eps = read_arguments(ARGS)

    (instance,(nb_variables, nb_constraints, obj, feas, t_buildexport, t_knitro)) = build_and_solve_instance(typeofinput, instance_path)
    println("NB variables : ",nb_variables)
    println("NB_constraints : ",nb_constraints)
    println("Objective : ",obj)
    println("Feasibility : ",feas)
    println("t_buildexport : ", t_buildexport)
    println("t_knitro : ", t_knitro)
end

main(ARGS)

max_stars_repo_name: Gimaju/GOC

max_issues_repo_name: Gimaju/GOC

max_forks_repo_name: Gimaju/GOC


text:
#
println("Dt) Test of the InternalConversion module with ASF from an internally generated initial- and final-state multiplet.")
#
setDefaults("print summary: open", "zzz-InternalConversion.sum")
wa = Atomic.Computation("xx",  Nuclear.Model(36.);
                        initialConfigs=[Configuration("1s^2 2s^2 2p^6")],
                        finalConfigs  =[Configuration("1s^2 2s^2 2p^5"), Configuration("1s^2 2s 2p^6") ],
                        process = InternalConv,
                        processSettings=InternalConversion.Settings() )

wb = perform(wa)
setDefaults("print summary: close", "")


text:
SURFACE(scale=1) = @compat Dict(
  :vertex         => Vec3(0),
  :offset         => GLBuffer(Float32[0,0, 0,1, 1,1, 1,0] * scale, 2),
  :index          => indexbuffer(GLuint[0,1,2,2,3,0]),
  :normal_vector  => 0f0,
  :xscale         => 1f0,
  :yscale         => 1f0,
  :zscale         => 1f0,
  :z              => 0f0,
  :drawingmode    => GL_TRIANGLES,
)

CIRCLE(r=0.4f0, x=0f0, y=0f0, points=6) = @compat Dict(
  :vertex         => Vec3(0),
  :offset         => GLBuffer(gencircle(r, x, y, points) , 2),
  :index          => indexbuffer(GLuint[i for i=0:points + 1]),
  :normal_vector  => 0f0,
  :xscale         => 1f0,
  :yscale         => 1f0,
  :zscale         => 1f0,
  :z              => 0f0,
  :drawingmode    => GL_TRIANGLE_FAN,
)
begin
local const cubedata = gencubenormals(Vec3(0), Vec3(1, 0, 0), Vec3(0,1, 0), Vec3(0,0,1))
CUBE() = @compat Dict(
  :vertex         => GLBuffer(cubedata[1]),
  :normal_vector  => GLBuffer(cubedata[3]),
  :index          => indexbuffer(cubedata[4]),

  :offset         => Vec2(0), # For other geometry, the texture lookup offset is zero
  :zscale         => 1f0,
  :z              => 0f0,
  :drawingmode    => GL_TRIANGLES
)
end
POINT() = @compat Dict(
  :vertex         => GLBuffer(Vec3[Vec3(0)]),
  :offset         => Vec2(0), # For other geometry, the texture lookup offset is zero
  :index          => indexbuffer(GLuint[0]),
  :normal_vector  => GLBuffer(Vec3[Vec3(0,0,1)]),
  :zscale         => 1f0,
  :z              => 0f0,
  :drawingmode    => GL_POINTS
)

function visualize(style::Style{:Default}, datapoints::Matrix{Float32}, attribute::Symbol, data::Dict{Symbol,Any})
  data[attribute]=datapoints
  surf(style, data)
end

function surf(::Style{:Default}, data::Dict{Symbol, Any})
  screen           = data[:screen]
  camera           = data[:screen].perspectivecam
  primitive        = data[:primitive]
  customattributes = Dict{Symbol, Any}()
  customview       = @compat Dict(
    "GLSL_EXTENSIONS" => "#extension GL_ARB_draw_instanced : enable"
  )

  # transform values to OpenGL types, and create the correct keys for the shader view
  xn, yn = (0,0)
  # Depending on what the primitivie is, additional values have to be calculated

  merge!(customattributes, primitive)
  customattributes[:projection]     = camera.projection
  customattributes[:view]           = camera.view
  customattributes[:normalmatrix]   = camera.normalmatrix

  for (key, value) in data
    if isa(value, Matrix)
      t = Texture(value, keepinram=true)
      customattributes[key] = t
      xn, yn = size(value)
    elseif isa(value, ASCIIString)
      customview[string(key)*"_calculation"] = value
      customview[string(key)*"_type"] = "uniform float "
    elseif isa(value, NTuple{2, Real})
      customattributes[key] = Vec2(first(value), last(value))
    else
      customattributes[key] = value #todo: check for unsupported types
    end
  end
  if !haskey(primitive, :xscale)
    customattributes[:xscale] = float32(1 / xn)
  end
  if !haskey(primitive, :yscale)
    customattributes[:yscale] = float32(1 / yn)
  end
  customattributes[:griddimensions] = Vec2(yn,xn)
  fragdatalocation = [(0, "fragment_color"),(1, "fragment_groupid")]
  program = TemplateProgram(
    joinpath(shaderdir, "surface.vert"), joinpath(shaderdir, "phongblinn.frag"),
    view=customview, attributes=customattributes, fragdatalocation=fragdatalocation
  )
  obj = instancedobject(customattributes, (xn)*(yn), program, primitive[:drawingmode])
  prerender!(obj, glEnable, GL_DEPTH_TEST, glDepthFunc, GL_LESS, glDisable, GL_CULL_FACE, enabletransparency)
  obj
end

function toopengl{T <: AbstractArray}(
          array::Dict{Symbol, Dict{Symbol, T}}, attribute::Symbol=:zscale;
          xscale=0.08f0, yscale=0.03f0, textscale = Vec2(1/200f0),
          xrange=(0,1), yrange=(0,1), xborder=0.05, yborder=0.05, gap=0.2, color=Vec4(0,0,0,1),
          camera=pcamera
        )

  result        = RenderObject[]
  mappedresult  = map(res->hcat( collect(values(res))...), values(array))
  xrangestart   = first(xrange) + xborder
  xrangeend     = last(xrange) - xborder
  yrange        = (first(yrange) + yborder, last(yrange) - yborder)

  L = length(mappedresult)
  xstep     = ((xrangeend-xrangestart) - ((L-1)*gap)) / L
  step      = 0f0

  for elem in mappedresult
    plot = map(x->Vector1{Float32}((x/10^8)/2), elem)

    start1 = xrangestart + (step*xstep) + (step*gap)
    xrange = (start1, (start1 + xstep))
    push!(result, toopengl(
      plot,
      attribute, primitive=CUBE(), xscale=xscale,
      yscale=yscale, color=color, xrange=xrange,
      yrange=yrange, camer=camera
    ))

    step += 1f0
  end

  rotq    = qrotation(Float32[0,0,1], pi/2f0)
  rotdir  = qrotation(Float32[0,0,1], -pi/2f0)

  ytext = foldl((v0,v1)-> v0*"\n"*v1, map(string, keys(results)))
  xtext = foldl((v0,v1)-> v0*"\n"*v1, map(string, keys(first(results)[2])))

  push!(result, toopengl(
    reverse(ytext), start=Vec3(xrangestart + (xstep/2),-0.1,0),
    scale=textscale, rotation=rotdir,
    textrotation=rotq, lineheight=xstep+gap, camer=camera
  ))
  push!(result, toopengl(
    string(xtext), start=Vec3(1,0f0,0), camer=camera, scale=textscale,
    lineheight=(rangelength(yrange) / (size((mappedresult[1]), 2)-1)),
  ))
end

function zdata(x1, y1, factor)
    x = (x1 - 0.5) * 15
    y = (y1 - 0.5) * 15

    Vec1((sin(x) + cos(y)) / 10)
end
function zcolor(z)
    a = Vec4(0,1,0,1)
    b = Vec4(1,0,0,1)
    return mix(a,b,z[1]*5)
end

function mix(x,y,a)
  return (x * (1-a[1])) + (y * a[1])
end

Base.middle(x::(Real, Real)) = (first(x)+last(x)) /2
rangelength(x::(Real, Real)) = abs(last(x)-first(x))

function normal(A, xrange, yrange)
  w,h = size(A)
  result = Array(Vector3{eltype(A[1])}, w,h)
  for x=1:w, y=1:h
    xs = stretch(float32(x), xrange, w)
    ys = stretch(float32(y), yrange, h)
    zs = A[x,y][1]

    current = Vector3(xs, ys, zs)

    #calculate indexes for surrounding zvalues
    indexes = reverse([(x-1,y-1), (x-1,y), (x-1,y+1), (x,y+1),
                (x+1,y+1), (x+1,y), (x+1,y-1), (x,y-1)])

    #Remove out of bounds
    indextmp = (Int, (Int,Int))[]
    holes = 0
    for (ind,(x1,y1)) in enumerate(indexes)
      if x1 >= 1 && x1 <= w && y1 >= 1 && y1 <= h
        push!(indextmp, (ind,(x1, y1)))
      else
        holes += 1
      end
    end
    #Put back into order, solving one special case (edges (N,N.  )
    if length(indextmp)==3 && holes > 0 && indextmp[1][1] == 1
      indextmp[1] = (999, indextmp[1][2])
    end
    indexes = map(x->x[2], sort(indextmp))
    #Construct the full surrounding difference Vectors with x,y,z coordinates
    differenceVecs = map(indexes) do elem
      xx    = stretch(float32(elem[1]), xrange, w) # treat indexes as coordinates by stretching them to the correct range
      yy    = stretch(float32(elem[2]), yrange, h)
      cVec  = current - Vector3(xx, yy, A[elem...][1])
    end

    #get the sum of the cross with the current Vector and normalize
    normalVec = unit(reduce((v0, a) -> begin
      a1 = a[2]
      a2 = differenceVecs[a[1] + 1]
      v0 + cross(a1, a2)
    end, Vec3(0), enumerate(differenceVecs[1:end-1])))

    result[x,y] = normalVec

  end
  result
end

function stretch(x, r::Range, normalizer = 1)
  T = typeof(x)
  convert(T, first(r) + ((x / normalizer) * (last(r) - first(r))))
end

function stretch(x, r::(Real, Real), normalizer = 1)
  T = typeof(x)
  convert(T, first(r) + ((x / normalizer) * (last(r) - first(r))))
end


text:
mutable struct ADC
    N::Int64
    T::Float64
    delay::Float64
    Δf::Float64
    ϕ::Float64
    function ADC(A,T,delay,Δf,ϕ)
      T < 0 || delay < 0 ? error("ADC timings must be positive.") : new(A, T, delay, Δf, ϕ)
    end
    function ADC(A,T,delay)
		T < 0 || delay < 0 ? error("ADC timings must be positive.") : new(A, T, delay, 0, 0)
    end
    function ADC(A,T)
		T < 0 ? error("ADC timings must be positive.") : new(A, T, 0, 0, 0)
    end
end

getproperty(x::Vector{ADC}, f::Symbol) = begin
  if f == :dur
		T, delay = x.T, x.delay
		ΔT = T .+ delay
		ΔT
  else
    getproperty.(x,f)
  end
end

function get_sample_times(seq)
    T0 = cumsum([0; durs(seq)], dims=1)
    times = []
    for i = 1:length(seq)
        if is_ADC_on(seq[i])
            δ = seq.ADC[i].delay
            T = seq.ADC[i].T
            N = seq.ADC[i].N
            t = range(0, T, N).+T0[i].+δ
            append!(times, t)
        end
    end
    times
end

function get_sample_phase_compensation(seq)
  phase = []
  for i = 1:length(seq)
      if is_ADC_on(seq[i])
          N = seq.ADC[i].N
          ϕ = seq.ADC[i].ϕ
          aux = ones(N) .* exp(1im*ϕ)
          append!(phase, aux)
      end
  end
  phase
end


text:
mutable struct Intersection{T<:AbstractFloat,O<:Intersectable{T}}
    o::Union{O,Nothing}
    ray::Ray{T}
    t::T
    u::T
    v::T
end

Intersection(ray::Ray{T},::Type{O}) where {T,O} =
    Intersection{T,O}(nothing, ray, convert(T, Inf), zero(T), zero(T))

function normal(i::Intersection)
    p = i.ray.pos + i.t*i.ray.dir
    normal(i.o, p, i)
end

Base.isless(a::Intersection, b::Intersection) = (a.t < b.t)

is_hit(a::Intersection) = a.o != nothing

export Intersection, normal


text:
const DATE_SHIFT = -Dates.value(Date(2000))

struct TimeStamp <: Dates.TimeType
    x::Int64
    function TimeStamp(y::Int64, m::Int64=1, d::Int64=1,
                       h::Int64=0, mi::Int64=0, s::Int64=0,
                       ms::Int64=0, us::Int64=0, ns::Int64=0)
        err = Dates.validargs(DateTime, y, m, d, h, mi, s, ms)
        # TODO: Check us and ns
        isnull(err) || throw(unsafe_get(err))
        qdays = DATE_SHIFT + Dates.totaldays(y, m, d)
        new(ns + 10^3*us + 10^6*ms + 10^9 * (s + 60mi + 3600h + 86400qdays))
    end
    TimeStamp(::Type{Int}, x::Integer) = new(x)
end

TimeStamp(y, m=1, d=1, h=0, mi=0, s=0, ms=0, us=0, ns=0) = TimeStamp(Int64(y),
    Int64(m), Int64(d), Int64(h), Int64(mi), Int64(s),
    Int64(ms), Int64(us), Int64(ns))

_cast(::Type{TimeStamp}, x::Int64) = TimeStamp(Int, x)
Dates.value(x::TimeStamp) = x.x

struct TimeSpan <: Dates.TimePeriod
    value::Int64
end

Dates.value(x::TimeSpan) = x.value

TimeSpan(x::TimeSpan) = x
# TODO: Make this a q-style 0D... display.
Base.string(x::TimeSpan) = string("Q.TimeSpan($(x.value))")
_cast(::Type{Int64}, x::TimeSpan) = x.value
Dates.tons(x::TimeSpan) = x.value

struct DateTimeF <: Dates.TimeType
    x::Float64
end

for T in [:Month, :Minute, :Second, :Time]
    @eval begin
        struct $T <: Dates.TimeType
            x::Int32
            $T(::Type{Int}, x::Integer) = new(x)
        end
        Dates.value(x::$T) = x.x
        _cast(::Type{$T}, x::Int32) = $T(Int, x)
    end
end

# Constructors
# TODO: Add argument checking
Month(y, m=1) = Month(Int32(y), Int32(m))
Month(y::Int32, m::Int32=1) = Month(Int, Int32(12)*(y-Int32(2000)) + m - 1)

Minute(h, mi=0) = Minute(Int32(h), Int32(mi))
Minute(h::Int32, mi::Int32=0) = Minute(Int, Int32(60)*h + mi)

Second(h, mi=0, s=0) = Second(Int32(h), Int32(mi), Int32(s))
Second(h::Int32, mi::Int32=0, s::Int32=0) = Second(Int,
    Int32(60)*(Int32(60)*h + mi) + s)

Time(h, mi=0, s=0, ms=0) = Time(Int32(h), Int32(mi), Int32(s), Int32(ms))
Time(h::Int32, mi::Int32=0, s::Int32=0, ms::Int32=0) = Time(Int,
    10^3*(Int32(60)*(Int32(60)*h + mi) + s) + ms)

# Accessors
using Base.Dates.value
Dates.year(m::Month) = fld(Int32(24000)+value(m), Int32(12))
Dates.month(m::Month) = 1 + mod(value(m), Int32(12))
Dates.days(m::Month) = Dates.totaldays(Dates.year(m), Dates.month(m), 1)
Dates.days(t::TimeStamp) = fld(Dates.value(t), Int64(86400)*10^9) - DATE_SHIFT

let T = TimeStamp
    Dates.hour(t::T) = mod(fld(value(t), Int64(3600)*10^9), Int64(24))
    Dates.minute(t::T) = mod(fld(value(t), Int64(60)*10^9), Int64(60))
    Dates.second(t::T) = mod(fld(value(t), Int64(10^9)), Int64(60))
    Dates.millisecond(t::T) = mod(fld(value(t), Int64(10^6)), Int64(10^3))
    Dates.microsecond(t::T) = mod(fld(value(t), Int64(10^3)), Int64(10^3))
    Dates.nanosecond(t::T) = mod(value(t), Int64(10^3))
end

let T = Minute
    Dates.hour(t::T) = fld(value(t), Int32(60))
    Dates.minute(t::T) = mod(value(t), Int32(60))
    Dates.second(t::T) = Int32(0)
    Dates.millisecond(t::T) = Int32(0)
    Dates.microsecond(t::T) = Int32(0)
    Dates.nanosecond(t::T) = Int32(0)
end

let T = Second
    Dates.hour(t::T) = fld(value(t), Int32(3600))
    Dates.minute(t::T) = mod(fld(value(t), Int32(60)), Int32(60))
    Dates.second(t::T) = mod(value(t), Int32(60))
    Dates.millisecond(t::T) = Int32(0)
    Dates.microsecond(t::T) = Int32(0)
    Dates.nanosecond(t::T) = Int32(0)
end

let T = Time
    Dates.hour(t::T) = fld(value(t), Int32(3600*10^3))
    Dates.minute(t::T) = mod(fld(value(t), Int32(60*10^3)), Int32(60))
    Dates.second(t::T) = mod(fld(value(t), Int32(10^3)), Int32(60))
    Dates.millisecond(t::T) = mod(value(t), Int32(10^3))
    Dates.microsecond(t::T) = Int32(0)
    Dates.nanosecond(t::T) = Int32(0)
end

# Text representation

Base.string(x::TimeStamp) = string(Dates.format(x,
    dateformat"YYYY.mm.ddDHH:MM:SS.s", 32),
    @sprintf("%03d%03d", Dates.microsecond(x), Dates.nanosecond(x)))

function Base.show(io::IO, x::TimeStamp)
    Dates.format(io, x, dateformat"YYYY.mm.ddDHH:MM:SS.s")
    @printf(io, "%03d%03d", Dates.microsecond(x), Dates.nanosecond(x))
end

Dates.default_format(::Type{Month}) = dateformat"YYYY.mm\m"
Dates.default_format(::Type{Minute}) = dateformat"HH:MM"
Dates.default_format(::Type{Second}) = dateformat"HH:MM:SS"
Dates.default_format(::Type{Time}) = dateformat"HH:MM:SS.s"

for T in [:Month, :Minute, :Second, :Time]
    @eval begin
        Base.string(x::$T) = Dates.format(x, Dates.default_format($T))
        Base.show(io::IO, x::$T) = Dates.format(io, x, Dates.default_format($T))
    end
end


text:
# The script s written for test moudle using

module soltest

importall Base

export functest,roro

# ---
function functest(x::Float64,y::Float64)
 return x^y
end

type roro
 x::Int
 sinxx
end

function sinxx(x)
 return sin(x)
end

end

max_stars_repo_name: dingzhw/RotorTrim

max_issues_repo_name: helicopterliu/RotorTrim

max_forks_repo_name: helicopterliu/RotorTrim


text:
using Test
import sbp
#using sbp.Table: latex

header = ["a", "b"]
a = zeros(4)
b = zeros(4)
b[1] = Inf
vars = [a, b]

@testset "Latex table" begin
table = sbp.Table.latex(header, vars, format="c")
ans = """
\\begin{tabular}{cc}
a & b \\\\
\\hline
\$0.0\$ & - \\\\
\$0.0\$ & \$0.0\$ \\\\
\$0.0\$ & \$0.0\$ \\\\
\$0.0\$ & \$0.0\$
\\end{tabular}
"""
@test join(table) == ans

end

max_stars_repo_name: ooreilly/sbpjl

max_issues_repo_name: ooreilly/sbpjl

max_forks_repo_name: ooreilly/sbpjl