text:
"""
    @runtime_ccall((function_name, library), returntype, (argtype1, ...), argvalue1, ...)

Extension of `ccall` that performs the lookup of `function_name` in `library` at run time.
This is useful in the case that `library` might not be available, in which case a function
that performs a `ccall` to that library would fail to compile.
After a slower first call to load the library and look up the function, no additional
overhead is expected compared to regular `ccall`.
"""
macro runtime_ccall(target, args...)
    # decode ccall function/library target
    Meta.isexpr(target, :tuple) || error("Expected (function_name, library) tuple")
    function_name, library = target.args

    # global const ref to hold the function pointer
    @gensym fptr_cache
    @eval __module__ begin
        # uses atomics (release store, acquire load) for thread safety.
        # see https://github.com/JuliaGPU/CUDAapi.jl/issues/106 for details
        const $fptr_cache = Threads.Atomic{UInt}(0)
    end

    return quote
        # use a closure to hold the lookup and avoid code bloat in the caller
        @noinline function cache_fptr!()
            library = Libdl.dlopen($(esc(library)))
            $(esc(fptr_cache))[] = Libdl.dlsym(library, $(esc(function_name)))

            $(esc(fptr_cache))[]
        end

        fptr = $(esc(fptr_cache))[]
        if fptr == 0        # folded into the null check performed by ccall
            fptr = cache_fptr!()
        end

        ccall(reinterpret(Ptr{Cvoid}, fptr), $(map(esc, args)...))
    end

    return
end


text:
# read the matpower data and process it in PowerModels.jl
using PowerModels, Gurobi, Ipopt, Random, Distributions;
# using JLD, HDF5;
using CSV;
using DataFrames;

# read in the list of hard cases
# list_file = readdir("./data/hard_case/Solvable");
list_file = readdir("./data/hard_case/Julia_Solvablez");

result_cat = Dict();
ErrorList = [];
NumList = [];
OptList = [];
InfeasList = [];

for itema in list_file
    #    if occursin("pglib",itema)
    try
        if occursin("case", itema)
            # result = run_dc_opf("./data/hard_case/"*itema,Gurobi.Optimizer);
            result = run_dc_opf("./data/hard_case/Julia_Solvable/" * itema,
                optimizer_with_attributes(Ipopt.Optimizer, "linear_solver" => "ma27"))
            result_cat[itema] = result["termination_status"]
        end
    catch
        push!(ErrorList, itema)
    end
end
# obtain the numerical issue cases
for iKey in keys(result_cat)
    if result_cat[iKey] == NUMERICAL_ERROR
        push!(NumList, iKey)
    end
end
# numerical issues are mostly caused by infeasibility as well

for iKey in keys(result_cat)
    if result_cat[iKey] == OPTIMAL
        push!(OptList, iKey)
    end
end

for iKey in keys(result_cat)
    if result_cat[iKey] == INFEASIBLE
        push!(InfeasList, iKey)
    end
end

# Result:
# 1. using Gurobi, there are cases that could be solved, which are put in "Solvable" folder
# 2. the rest of the cases are all infeasible or numerical issue
# 3. solving the rest of the cases using Ipopt yields LOCALLY_INFEASIBLE for all

##

# alter the load portfolio to generate hard case
# read in the data
const GUROBI_ENV = Gurobi.Env();
network_data = parse_file("./data/pglib_opf_case2746wop_k.m")
load_keys = [i for i in keys(network_data["load"])]

# test changing load at one bus
result_load_1 = Dict()
for i = 1:length(load_keys)
    network_data_new = deepcopy(network_data)
    network_data_new["load"][load_keys[i]]["pd"] *= 1.5
    result = run_dc_opf(network_data_new,
        optimizer_with_attributes(() -> Gurobi.Optimizer(GUROBI_ENV),
            "OutputFlag" => 0))
    result_load_1[load_keys[i]] = result["termination_status"]
end

# test changing load at all buses with a normal distribution deviation
σ_load = Dict()
load_distrn = Dict()
for i = 1:length(load_keys)
    σ_load[load_keys[i]] = network_data["load"][load_keys[i]]["pd"] * 0.03
    load_distrn[load_keys[i]] = Normal(0, σ_load[load_keys[i]])
end

result_load_2 = []
errorLoad = Dict()
for iterNo = 1:1000
    network_data_new = deepcopy(network_data)
    for i = 1:length(load_keys)
        network_data_new["load"][load_keys[i]]["pd"] += rand(load_distrn[load_keys[i]])
    end
    result = run_dc_opf(network_data_new,
        optimizer_with_attributes(() -> Gurobi.Optimizer(GUROBI_ENV),
            "OutputFlag" => 0))
    push!(result_load_2, result["termination_status"])
    if result["termination_status"] != OPTIMAL
        errorLoad[iterNo] = network_data_new["load"]
    end
end

save("errorLoad.csv", "errorLoad", errorLoad);

ext: jl

max_stars_repo_name: zhouliang-yu/Grid-ML

max_issues_repo_name: zhouliang-yu/Grid-ML

max_forks_repo_name: zhouliang-yu/Grid-ML


text:
module JSONRPC

import JSON
using Base: IOServer, IOError
using Parameters: @unpack
using Sockets: accept, connect, listen

include("core.jl")
include("serializers.jl")
include("server.jl")
include("client.jl")

end # module


text:
module Geometry
export volume, surfacearea, lateralarea

abstract type Solid end

# *******************************************
mutable struct Cone <: Solid
    height::Float32
    # one element implies start from one point
    # two elements for truncated cone volume
    radii::Array{Float32, 1}
    function Cone(depth, diameters)
        if length(diameters) > 2
            error("Too many diameter arguments in list")
        end
        if length(diameters) == 1
            push!(diameters,0.0)
        end
        new(depth, diameters / 2)
    end
end
mutable struct Cylinder <: Solid
    height::Float32
    radius::Float32
    function Cylinder(depth, diameter)
        new(depth, (diameter / 2.0))
    end
end
struct Cube <: Solid
    side::Float32
end
struct RectangularPrism <: Solid
    height::Float32
    width::Float32
    depth::Float32
end

function volume(c::Solid)
    tc = typeof(c)
    if tc == Cone
        rads = (c.radii[1]^2 + c.radii[1]*c.radii[2] + c.radii[2]^2)
        return (1/3)*(pi*rads*c.height)
    elseif tc == Cylinder
        return (1/1)*(pi*(c.radius^2)*c.height)
    elseif tc == Cube
        return (1/1)*(c.side^3)
    elseif tc == RectangularPrism
        return (1/1) * (c.height * c.width * c.depth)
    end
    return nothing
end

function lateralarea(c::Solid)
    tc = typeof(c)
    if tc == Cone
        return pi * (c.radii[1] + c.radii[2]) * (((c.radii[1] - c.radii[2])^2 + c.height^2)^(1/2))
    elseif tc == Cylinder
        return 2*pi*c.radius*c.height
    elseif tc == Cube
        return (1/1)*4*(c.side^2)
    elseif tc == RectangularPrism
        return (1/1) * (2 * (c.height * c.width) + 2 * (c.height * c.depth))
    end
    return nothing
end

function surfacearea(c::Solid)
    tc = typeof(c)
    if tc == Cone
        return lateralarea(c) + pi * (c.radii[1]^2 + c.radii[2]^2)
    elseif tc == Cylinder
        return lateralarea(c) + 2*pi*(c.radius^2)
    elseif tc == Cube
        return (1/1)*6*(c.side^2)
    elseif tc == RectangularPrism
        return lateralarea(c) + (1/1) * (2 * (c.width * c.depth))
    end
    return nothing

end

end


text:
# =============================================================================
# Calculate quantites of differents coin
# Luis Lopez Diaz - llopeza@uninorte.edu.co
# =============================================================================
# Input data
m = 1800;                       # Money in $
# =============================================================================
if m < 0
    error("Money needs to be positive.");
    return;
end
if ~(typeof(m) == Int)
    error("Money needs to be integer.");
    return;
end
# =============================================================================
# List of coins availables
coins = [1000 500 200 100 50];  # Available coins in sort
nCoins = length(coins);         # Number of coins
qCoins = zeros(1,nCoins);       # Vector for number of coins
for i in 1:nCoins
    global m;
    if m/coins[i] >= 1
        qCoins[i] = div(m,coins[i]);    # Calculate quantites of coins i
        m = m - qCoins[i]*coins[i];     # Updating value of money
    end
end
if m > 0
    error("Not posible to reach with coins this money.");
    return;
end
# =============================================================================
# Printing results
println("Total number of coins: ", sum(qCoins));
for i in 1:nCoins
    if qCoins[i] != 0
        println(coins[i], " coins: ",qCoins[i]);
    end
end