licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.3.6 | 727f129ba765e0fc550f4e776c7c8145a7efcba0 | docs | 3680 | # BaytesSMC
<!---

[](xxx)
[](xxx)
-->
[](https://paschermayr.github.io/BaytesSMC.jl/)
[](https://github.com/paschermayr/BaytesSMC.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/paschermayr/BaytesSMC.jl)
[](https://github.com/SciML/ColPrac)
BaytesSMC.jl is a library to perform SMC proposal steps on `ModelWrapper` structs, see [ModelWrappers.jl](https://github.com/paschermayr/ModelWrappers.jl). Kernels that are defined in [BaytesMCMC.jl](https://github.com/paschermayr/BaytesMCMC.jl) and [BaytesFilters.jl](https://github.com/paschermayr/BaytesFilters.jl) can be
used inside this library.
BaytesSMC.jl supports sequential parameter estimation frameworks such as IBIS and SMC2. This can be achieved via data tempering, which is explained in more detail in the upcoming Baytes.jl library. Moreover, a SMC variant for batch data is provided as well, where tempering of the objective function is used until the temperature reaches 1.0.
<!---
[BaytesMCMC.jl](xxx)
[BaytesFilters.jl](xxx)
[BaytesPMCMC.jl](xxx)
[BaytesSMC.jl](xxx)
[Baytes.jl](xxx)
-->
## First steps
All standard Baytes.jl functions call can be used in BaytesSMC.jl. To start with, we have
to define parameter and an objective function first.
Let us use the model initially defined in the [ModelWrappers.jl](https://github.com/paschermayr/ModelWrappers.jl) introduction:
```julia
using ModelWrappers, BaytesSMC
using Distributions, Random, UnPack
_rng = Random.GLOBAL_RNG
#Create Model and data
myparameter = (μ = Param(Normal(), 0.0, ), σ = Param(Gamma(), 1.0, ))
mymodel = ModelWrapper(myparameter)
data = randn(1000)
#Create objective for both μ and σ and define a target function for it
myobjective = Objective(mymodel, data, (:μ, :σ))
function (objective::Objective{<:ModelWrapper{BaseModel}})(θ::NamedTuple)
@unpack data = objective
lprior = Distributions.logpdf(Distributions.Normal(),θ.μ) + Distributions.logpdf(Distributions.Exponential(), θ.σ)
llik = sum(Distributions.logpdf( Distributions.Normal(θ.μ, θ.σ), data[iter] ) for iter in eachindex(data))
return lprior + llik
end
```
A particle in the SMC framework corresponds to a full model. We will assign assign a NUTS sampler for each particle, and propose new parameter via SMC in the standard Bayes.jl framework:
```julia
using BaytesMCMC
smc = SMC(_rng, MCMC(NUTS,(:μ, :σ,)), myobjective)
propose!(_rng, smc, mymodel, data)
```
## Customization
Construction is highly flexible, and can be tweaked via keyword assignments in the following helper structs:
```julia
kerneldefault = SMCDefault(Ntuning = 50, jittermin = 1, jittermax = 10)
samplingdefault = SampleDefault(chains = 10)
SMC(_rng, MCMC(NUTS,(:μ, :σ,)), myobjective, kerneldefault, samplingdefault)
```
`kerneldefault` consists of tuning parameter that are specific for SMC,
`samplingdefault` consists of tuning parameter that are observed over the whole sampling process. The latter is explained in more detail in Baytes.jl.
## Going Forward
This package is still highly experimental - suggestions and comments are always welcome!
<!---
# Citing Baytes.jl
If you use Baytes.jl for your own research, please consider citing the following publication: ...
-->
| BaytesSMC | https://github.com/paschermayr/BaytesSMC.jl.git |
|
[
"MIT"
] | 0.3.6 | 727f129ba765e0fc550f4e776c7c8145a7efcba0 | docs | 184 | ```@meta
CurrentModule = BaytesSMC
```
# BaytesSMC
Documentation for [BaytesSMC](https://github.com/paschermayr/BaytesSMC.jl).
```@index
```
```@autodocs
Modules = [BaytesSMC]
```
| BaytesSMC | https://github.com/paschermayr/BaytesSMC.jl.git |
|
[
"MIT"
] | 0.3.6 | 727f129ba765e0fc550f4e776c7c8145a7efcba0 | docs | 32 | # Introduction
Yet to be done.
| BaytesSMC | https://github.com/paschermayr/BaytesSMC.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 360 | using MDBM
using Documenter
makedocs(;
modules=[MDBM],
authors="Daniel Bachrathy",
repo="https://github.com/bachrathyd/MDBM.jl/blob/{commit}{path}#L{line}",
sitename="MDBM.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 424 | using MDBM
using LinearAlgebra, Arpack
function fooeig(x)
mymx=Matrix{Float64}(I,5,5);
mymx[2,1]=x;
mymx[1,2]=x+5;
abs(eigs(mymx, nev = 2)[1][1])-3
end
eig_problem=MDBM_Problem(fooeig,[Axis(-10:10)])
println(" X solution // Function val")
for k=1:12
solve!(eig_problem,1)
Xsol=getinterpolatedsolution(eig_problem)
print(Xsol[1])
print(" // ")
println(maximum(abs.(fooeig.(Xsol[1]))))
end
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 349 | using MDBM
using PyPlot
pygui(true)
#Solution of an uncertain implicit equation
function foo(x,y)
x^2.0+y^2.0-2.0^2.0+randn()
end
for k = 1:5
mymdbm=MDBM_Problem(foo,[-3.0:3.0,-3.0:3.0])
solve!(mymdbm,5)
x_sol,y_sol=getinterpolatedsolution(mymdbm)
fig = figure(1)#;clf()
scatter(x_sol,y_sol,s=4);
fig = figure(2)#;clf()
hist(x_sol,100)
end
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 1414 | using MDBM
using PyPlot
pygui(true)
### Axis with vector valued nodes
# Task: find the solution along the eges of a triangle
# the function which defines the region on the plane of the triangle
fig = figure(1);clf()
Circ_mdbm=MDBM_Problem((x,y,r)->x*x+y*y-r*r,[-2.0:2.0,-2.0:2.0,0.75:0.2:1.25])
solve!(Circ_mdbm,3);
x_sol,y_sol=getinterpolatedsolution(Circ_mdbm)
scatter(x_sol,y_sol,s=2);
# Computing along the edge of a triangle:
# The ticks of the ax1 is the nodes of the triangle
ax1=Axis([[-1.0,1.0],[-1.0,-1.0],[1.5,-0.5],[-1.0,1.0]],"v")
ax2=Axis(0.75:0.2:1.25,"r")
#plotting the tirangle
for k in 1:length(ax1.ticks)-1
plot([ax1.ticks[k][1],ax1.ticks[k+1][1]],[ax1.ticks[k][2],ax1.ticks[k+1][2]])
end
function foo_Vect_Float(v,r)
norm(v)-r
end
Vect_mdbm=MDBM_Problem(foo_Vect_Float,[ax1,ax2])
# the tree nodes of the triangle is not a proper initial mesh, so ax1 it is refined 3 times
refine!(Vect_mdbm,directions=[1,1,1])
scatter([P[1] for P in Vect_mdbm.axes[1]],[P[2] for P in Vect_mdbm.axes[1]],s=20)
solve!(Vect_mdbm,4)
#solution points
V_sol,r_sol=getinterpolatedsolution(Vect_mdbm) #Note V_sol is a Vector of Vectors
scatter([P[1] for P in V_sol],[P[2] for P in V_sol],s=6);
#Plotting the result in 3D along the first and second element of the vector (from ax1) + the redial coordinate (from ax2)
fig = figure(2);clf()
scatter3D([P[1] for P in V_sol],[P[2] for P in V_sol],r_sol,s=6);
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 1438 | # __precompile__()
"""
Multi-Dimensional Bisection Method (MDBM) is an efficient and robust root-finding algorithm,
which can be used to determine whole high-dimensional sub-manifolds (points, curves, surfaces…)
of the roots of implicit non-linear equation systems, even in cases, where the number of unknowns
surpasses the number of equations.
# Examples
```julia
include("MDBM.jl")
using Reexport
@reexport using .MDBM
using PyPlot;
pygui(true);
function foo(x,y)
x^2.0+y^2.0-2.0^2.0
end
function c(x,y) #only the c>0 domain is analysed
x-y
end
ax1=Axis([-5,-2.5,0,2.5,5],"x") # initial grid in x direction
ax2=Axis(-5:2:5.0,"y") # initial grid in y direction
mymdbm=MDBM_Problem(foo,[ax1,ax2],constraint=c)
iteration=5 #number of refinements (resolution doubling)
solve!(mymdbm,iteration)
#points where the function foo was evaluated
x_eval,y_eval=getevaluatedpoints(mymdbm)
#interpolated points of the solution (approximately where foo(x,y) == 0 and c(x,y)>0)
x_sol,y_sol=getinterpolatedsolution(mymdbm)
fig = figure(1);clf()
scatter(x_eval,y_eval,s=5)
scatter(x_sol,y_sol,s=5)
```
"""
module MDBM
using StaticArrays
using LinearAlgebra
export MDBM_Problem, Axis,
solve!, interpolate!, refine!, checkneighbour!,
axesextend!, getinterpolatedsolution, getevaluatedpoints, getevaluatedfunctionvalues, getevaluatedconstraintvalues,
connect, triangulation
include("MDBM_types.jl")
include("MDBM_functions.jl")
end
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 22103 | function axdoubling!(ax::Axis)
#WRONG: sort!(append!(ax.ticks, ax.ticks[1:end - 1] + diff(ax.ticks) / 2); alg = QuickSort)
#the axis could be in a non-sorted form
doubleindex=(2:2*length(ax.ticks)).÷2
doubleindex[2:2:end] .+=length(ax.ticks)
append!(ax.ticks, ax.ticks[1:end - 1] + diff(ax.ticks) / 2)
ax.ticks[1:end].=ax.ticks[doubleindex];
end
"""
axesextend!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, axisnumber::Integer; prepend::AbstractArray=[], append::AbstractArray=[])
Extend parameter space of the selected Axis by prepend and append the grid.
Note, that the resolution and the monotonically is not checked.
# Examples
extending the second parameter of the mdbm problem:
```jldoctest
julia> axesextend!(mymdbm,2,prepend=-6.2:0.05:-2.2,append=2.2:0.2:3);
```
"""
function axesextend!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, axisnumber::Integer; prepend::AbstractArray = [], append::AbstractArray = []) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
preplength = length(prepend);
if preplength > 0
prepend!(mdbm.axes[axisnumber].ticks, prepend)
for nc in mdbm.ncubes
nc.corner[axisnumber] += preplength;
end
end
if length(append) > 0
append!(mdbm.axes[axisnumber].ticks, append)
end
end
# function corner(nc::NCube{IT,FT,N}, T01)::Vector{MVector} where IT where FT where N
function corner(nc::NCube{IT,FT,N}, T01) where IT where FT where N
[nc.corner .+ nc.size .* T for T in T01]
end
# function corner(ncubes::Vector{NCube{IT,FT,N}}, T01)::Vector{Vector{MVector}} where IT where FT where N
function corner(ncubes::Vector{NCube{IT,FT,N}}, T01) where IT where FT where N
[corner(nc, T01) for nc in ncubes]
# [nc.corner .+ nc.size .* T for nc in ncubes for T in T01]
end
# function corner(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})::Vector{Vector{SVector}} where fcT where N where Nf where Nc
function corner(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
[corner(nc, mdbm.T01) for nc in mdbm.ncubes]
end
function getcornerval(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}#get it for all
#getcornerval.(mdbm.ncubes,Ref(mdbm))
map(x->((mdbm.fc) ∘ (mdbm.axes))(x...), Base.Iterators.flatten(corner(mdbm)))
end
function getcornerval(ncubes::NCube{IT,FT,N}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
#PostionsVectors=(mdbm.axes.(corner(nc,mdbm.T01)))
# (mdbm.fc).( (mdbm.axes).(corner(nc,mdbm.T01)) )
map(x->((mdbm.fc) ∘ (mdbm.axes))(x...), corner(ncubes, mdbm.T01))
end
function T01maker(valk::Val{kdim}) where {kdim}
SVector{2^kdim}([
SVector{kdim}([isodd(x ÷ (2^y)) for y in 0:(kdim - 1)])
for x in 0:(2^kdim - 1)])
end
function T11pinvmaker(valk::Val{kdim}) where {kdim}
T11pinv = ([isodd(x ÷ (2^y)) for y in 0:kdim , x in 0:(2^kdim - 1)] * 2.0 .- 1.0) / (2^kdim)
SMatrix{kdim + 1,2^kdim}(T11pinv)
end
function issingchange(FunTupleVector::AbstractVector, Nf::Integer, Nc::Integer)::Bool
all([
[
any((c)->!isless(c[1][fi], zero(c[1][fi])), FunTupleVector)
for fi in 1:Nf#length(FunTupleVector[1][1])
]#any positive (or zeros) value (!isless)
[
any((c)->!isless(zero(c[1][fi]), c[1][fi]), FunTupleVector)
for fi in 1:Nf#length(FunTupleVector[1][1])
]#anany negative (or zero) value
[
any((c)->!isless(c[2][fi], zero(c[2][fi])), FunTupleVector)
for fi in 1:Nc#length(FunTupleVector[1][2])
]#any positive (or zeros) value (!isless)
])#check for all condition
end
function _interpolate!(ncubes::Vector{NCube{IT,FT,N}}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, ::Type{Val{0}}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
isbracketing = map(nc->issingchange(getcornerval(nc, mdbm), Nf, Nc), ncubes) #TODO: parallelize
deleteat!(ncubes,.!isbracketing)#removeing the non-bracketing ncubes
for nc in ncubes
nc.posinterp[:] .= zero(FT)
end
return nothing
end
function _interpolate!(ncubes::Vector{NCube{IT,FT,N}}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, ::Type{Val{1}}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
for nc in ncubes
FunTupleVector = getcornerval(nc, mdbm)
if Nc==0 || all(
any((c)->!isless(c[2][fi], zero(c[2][fi])), FunTupleVector)
for fi in 1:length(FunTupleVector[1][2])
)# check the constraint: do wh have to compute at all?!?
As = zero(MVector{Nf + Nc,FT})
ns = zero(MMatrix{N,Nf + Nc,FT})
#for f---------------------
for kf = 1:Nf#length(FunTupleVector[1][1])
solloc = mdbm.T11pinv * [FunTupleVector[kcubecorner][1][kf] for kcubecorner = 1:length(FunTupleVector)]
As[kf] = solloc[end];
ns[:,kf] .= solloc[1:end - 1];
end
#for c---if needed: that is, it is close to the boundary--------
activeCostraint = 0;
for kf = 1:Nc#length(FunTupleVector[1][2])
#TODO: mivan a többszörös C teljesülése esetén!?!??!# ISSUE
if any((c)->!isless(zero(c[2][kf]), c[2][kf]), FunTupleVector) && length(As) < N # use a constraint till it reduces the dimension to zero (point) and no further
solloc = mdbm.T11pinv * [FunTupleVector[kcubecorner][2][kf] for kcubecorner = 1:length(FunTupleVector)]
activeCostraint += 1;
As[Nf + activeCostraint] = solloc[end];
ns[:,Nf + activeCostraint] .= solloc[1:end - 1];
end
end
if (Nf + activeCostraint) == 0
nc.posinterp[:] .= zero(FT)
else
# first two leads to error in the fucntion of constant due to the behaviour of pinv (eg. [1 0;0 1;0 0]/[1 0; 0 0; 0 0])
# nc.posinterp[:] .= transpose(view(ns, :, 1:(Nf + activeCostraint))) \ view(As, 1:(Nf + activeCostraint));#TEST
# nc.posinterp[:] .= transpose(ns[:, 1:(Nf + activeCostraint)]) \ As[1:(Nf + activeCostraint)];#TEST
# nc.posinterp[:] .= ns[:, 1:(Nf + activeCostraint)] * ((transpose(ns[:, 1:(Nf + activeCostraint)]) * ns[:, 1:(Nf + activeCostraint)]) \ view(As, 1:(Nf + activeCostraint)));
a = ns[:, 1:(Nf + activeCostraint)]
d = view(As, 1:(Nf + activeCostraint))
A = transpose(a) * a
if rank(A) == minimum(size(A))
nc.posinterp[:] .= a * (A \ d)
else
nc.posinterp[:] .= 1000.0
end
end
#for c---------------------
else
nc.posinterp[:] .= 1000.0;#put it outside the cube!
end
end
#TODO: what if it falls outside of the n-cube, it should be removed ->what shall I do with the bracketing cubes?
# Let the user define it
# filter!((nc)->sum((abs.(nc.posinterp)).^10.0)<(1.5 ^10.0),mdbm.ncubes)#1e6~=(2.0 ^20.0)
normp = 5.0
ncubetolerance = 0.7
filter!((nc)->norm(nc.posinterp, normp) < 1.0 + ncubetolerance, mdbm.ncubes)
#filter!((nc)->!any(isnan.(nc.posinterp)),mdbm.ncubes)
return nothing
end
function _interpolate!(ncubes::Vector{NCube{IT,FT,N}}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, ::Type{Val{Ninterp}}) where {fcT, IT, FT, N, Ninterp, Nf, Nc, t01T, t11T, aT}
error("order $(Ninterp) interpolation is not supperted (yet)")
end
"""
interpolate!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}; interpolationorder::Int=1)
Interpolate the solution within the n-cube with order `interpolationorder`.
- `interpolationorder=0` provide the midpoint of the n-cube
- `interpolationorder=1` preform a linear fit and provide closest solution point to the mindpoint of the n-cube
"""
function interpolate!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}; interpolationorder::Int = 1) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
_interpolate!(mdbm.ncubes, mdbm, Val{interpolationorder})
end
"""
refine!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}; directions::Vector{T}=collect(Int64,1:N)) where N where Nf where Nc where T<:Integer
Double the resolution of the axes along the provided `directions` then halving the `ncubes` accordingly.
# Examples
```jldoctest
julia> refine!(mymdbm)
julia> refine!(mymdbm,[1,1,2])
```
"""
function refine!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}; directions::Vector{T} = collect(Int64, 1:N)) where {T<:Integer, fcT, IT, FT, N, Ninterp, Nf, Nc, t01T, t11T, aT}
doubling!(mdbm, directions)
refinencubes!(mdbm.ncubes, directions)
return nothing
end
"""
doubling!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, directions::Vector{T}) where T<:Integer where N where Nf where Nc
Double the resolution of the axes along the provided `directions`, then set the new size of the n-cubes.
# Examples
```jldoctest
julia> doubling!(mymdbm)
julia> doubling!(mymdbm,[1,2])
```
"""
function doubling!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, directions::Vector{T}) where T <: Integer where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
axdoubling!.(mdbm.axes[directions])
for nc in mdbm.ncubes
for dir in directions
nc.corner[dir] = (nc.corner[dir] - 1) * 2 + 1
nc.size[dir] *= 2
end
end
end
"""
refinencubes!(ncubes::Vector{NCube{IT,FT,N}}, directions::Vector{T})
Halving the `ncubes` along the provided `directions`.
# Examples
```jldoctest
julia> refinencubes!(mymdbm.ncubes)
julia> refinencubes!(mymdbm.ncubes,mymdbm,[1,2])
```
"""
function refinencubes!(ncubes::Vector{NCube{IT,FT,N}}, directions::Vector{T}) where IT where FT where N where T <: Integer where t01T #{IT,FT,N} where IT where FT where N
for dir in directions
for nc in ncubes
nc.size[dir] /= 2
end
NumofNCubes = length(ncubes)
append!(ncubes, deepcopy(ncubes))
for nc in ncubes[1:NumofNCubes]
nc.corner[dir] = nc.corner[dir] + nc.size[dir]
end
end
sort!(ncubes; alg = QuickSort)
return nothing
end
"""
getinterpolatedsolution(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})
Provide the interpolated coordinates of the all the detected solution (approximately where foo(x,y) == 0 and c(x,y)>0).
"""
function getinterpolatedsolution(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
[
[
(typeof(mdbm.axes[i].ticks).parameters[1])((mdbm.axes[i].ticks[nc.corner[i]] * (1.0 - (nc.posinterp[i] + 1.0) / 2.0) +
mdbm.axes[i].ticks[nc.corner[i] + 1] * ((nc.posinterp[i] + 1.0) / 2.0)))
for nc in mdbm.ncubes]#::Vector{typeof(mdbm.axes[i].ticks).parameters[1]}
for i in 1:length(mdbm.axes)]
end
"""
getinterpolatedsolution(ncubes::Vector{NCube{IT,FT,N}},mdbm::MDBM_Problem{N,Nf,Nc})
Provide the interpolated coordinates of the detected solution for the selected n-cubes (approximately where foo(x,y) == 0 and c(x,y)>0).
"""
function getinterpolatedsolution(ncubes::Vector{NCube{IT,FT,N}}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
[
[
(typeof(mdbm.axes[i].ticks).parameters[1])(
(mdbm.axes[i].ticks[nc.corner[i]]*(1.0-(nc.posinterp[i]+1.0)/2.0)+
mdbm.axes[i].ticks[nc.corner[i]+1]*((nc.posinterp[i]+1.0)/2.0))
)
for nc in ncubes]#::Vector{typeof(mdbm.axes[i].ticks).parameters[1]}
for i in 1:length(mdbm.axes)]
end
"""
getinterpolatedsolution(nc::NCube{IT,FT,N}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})
Provide the interpolated coordinates of the solution inside the provided n-cube `nc` (approximately where foo(x,y) == 0 and c(x,y)>0).
"""
function getinterpolatedsolution(nc::NCube{IT,FT,N}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
[
(typeof(mdbm.axes[i].ticks).parameters[1])((mdbm.axes[i].ticks[nc.corner[i]] * (1.0 - (nc.posinterp[i] + 1.0) / 2.0) +
mdbm.axes[i].ticks[nc.corner[i] + 1] * ((nc.posinterp[i] + 1.0) / 2.0)))#::Vector{typeof(mdbm.axes[i].ticks).parameters[1]}
for i in 1:length(mdbm.axes)]
end
"""
getevaluatedpoints(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})
Provide all the coordinates where the function is evaluated.
"""
function getevaluatedpoints(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
[[x.callargs[i] for x in mdbm.fc.fvalarg] for i in 1:N]
end
"""
getevaluatedpoints(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})
Provide the functionvalues for all the coordinates where the function is evaluated.
(see: `getevaluatedpoints`)
"""
function getevaluatedfunctionvalues(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
[x.funval for x in mdbm.fc.fvalarg]
end
"""
getevaluatedconstraintvalues(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})
Provide the constraints values for all the coordinates where the function is evaluated.
(see: `getevaluatedpoints`)
"""
function getevaluatedconstraintvalues(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
[x.cval for x in mdbm.fc.fvalarg]
end
# function generateneighbours(ncubes::Vector{NCube},mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where N where Nf where Nc
function generateneighbours(ncubes::Vector{NCube{IT,FT,N}}, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
#TODO: Let the user select the method
#-------all faceing/cornering neightbours----------------
# #neighbourind=1:2^length(mdbm.axes) #cornering neightbours also - unnecessary
# neighbourind=2 .^(0:(length(mdbm.axes)-1)) .+ 1 #neighbour only on the side
# T101=[-mdbm.T01[neighbourind]...,mdbm.T01[neighbourind]...]
#
# nc_neighbour = Array{typeof(mdbm.ncubes[1])}(undef,0)
# NumofNCubes=length(ncubes)
# for iT in 1:length(T101)
# append!(nc_neighbour,deepcopy(ncubes))
# for nci in ((1+NumofNCubes*(iT-1)):(NumofNCubes+NumofNCubes*(iT-1)))
# nc_neighbour[nci].corner[:]=nc_neighbour[nci].corner+T101[iT].*nc_neighbour[nci].size
# end
# end
#-------all faceing/cornering neightbours----------------
#-------direcational neightbours----------------
nc_neighbour = Array{typeof(mdbm.ncubes[1])}(undef, 0)
Nface = 2^N
indpos = [[mdbm.T01[i][dir] for i in 1:Nface] for dir in 1:N]
indneg = [[!mdbm.T01[i][dir] for i in 1:Nface] for dir in 1:N]
for nc in ncubes
fcvals = getcornerval(nc, mdbm)
for dir in 1:N
# indpos=[mdbm.T01[i][dir] for i in 1:Nface]
# indneg=[!mdbm.T01[i][dir] for i in 1:Nface]
if issingchange(fcvals[indpos[dir]], Nf, Nc)
push!(nc_neighbour, deepcopy(nc))
nc_neighbour[end].corner[dir] += nc_neighbour[end].size[dir]
end
if issingchange(fcvals[indneg[dir]], Nf, Nc)
push!(nc_neighbour, deepcopy(nc))
nc_neighbour[end].corner[dir] -= nc_neighbour[end].size[dir]
end
end
end
#-------direcational neightbours----------------
filter!(nc->!(any(nc.corner .< 1) || any((nc.corner + nc.size) .> [length.(mdbm.axes)...])), nc_neighbour)#remove the overhanging ncubes
sort!(nc_neighbour; alg = QuickSort)
unique!(nc_neighbour)
return nc_neighbour
end
"""
checkneighbour!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}; interpolationorder::Int=0, maxiteration::Int=0)
Check the face-neighbouring n-cubes to discover the lost (missing) part of the solutions.
It is possible, that the sub-manifold (e.g.: curve) of the solution is not completely detected (it is interrupted).
This way the missing part can be explored similarly to a continuation method (with minimal function evaluation).
It works only if the dimension of the solution object is larger the zero (the maifold is not a set of poins).
# Arguments
- `interpolationorder::Int=0`: interpolation order method of the neighbours checked
- `maxiteration::Int=0~: the max number of steps in the 'continuation-like' exploring. If zero, then infinity steps are allowed
"""
function checkneighbour!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}; interpolationorder::Int = 0, maxiteration::Int = 0) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}#only for unite size cubes
if isempty(mdbm.ncubes)
println("There is no bracketing n-cubes to check!")
else
ncubes2check = mdbm.ncubes
numberofiteration = 0;
while !isempty(ncubes2check) && (maxiteration == 0 ? true : numberofiteration < maxiteration)
numberofiteration += 1
ncubes2check = generateneighbours(ncubes2check, mdbm)
deleteat!(ncubes2check, is_sorted_in_sorted(ncubes2check, mdbm.ncubes))#delete the ones which is already presented
_interpolate!(ncubes2check, mdbm, Val{interpolationorder})#remove the non-bracketing, only proper new bracketing cubes remained
append!(mdbm.ncubes, deepcopy(ncubes2check))
sort!(mdbm.ncubes; alg = QuickSort)
end
end
end
"""
connect(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT})
Provide the edge connection (as a list of point-paris) of the solution point-cloud based on the face-neighbouring n-cubes.
"""
function connect(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
#---------- line connection (no corener neighbour is needed) --------------
DT1 = Array{Tuple{Int64,Int64}}(undef, 0)
for inc in 1:length(mdbm.ncubes)
ncneigh = generateneighbours([mdbm.ncubes[inc]], mdbm)
indinresults = index_sorted_in_sorted(ncneigh, mdbm.ncubes)#delete the ones which is already presented
append!(DT1, [(inc, x) for x in indinresults if x != 0])
end
filter!(d->(d[2] > d[1]), DT1)#TODO: eleve csak ez egyik irányban levő szomszédokat kellene keresni!!!
sort!(DT1; alg = QuickSort)
unique!(DT1)
return DT1
end
"""
triangulation(DT1::Array{Tuple{Int64,Int64}})::Array{Tuple{Int64,Int64,Int64}}
Provide the triangulation (as a list of point-triplets) of the solution point-cloud based on the face-neighbouring n-cubes.
DT1 is the result of the edge connection performed by `connect`.
"""
function triangulation(DT1::Array{Tuple{Int64,Int64}})::Array{Tuple{Int64,Int64,Int64}}
#DT=sort!()[DT1;[(d[2],d[1]) for d in DT1]]);
DT = sort!([DT1;[d[[2,1]] for d in DT1]])#both direction of line connection is necessay!
#L=[filter(d->d[1]==i,DT) for i in 1:length(mdbm.ncubes)]
L = [
[dd[2] for dd in filter(d->d[1] == i, DT)] for i in 1:maximum(DT1)[2]]
DT4 = Array{Tuple{Int64,Int64,Int64,Int64}}(undef, 0)#quadratic patch
for i in 1:size(L, 1)
for j in L[i]#filter((L{i}>i) for i in )
if i > j#i must be the larges value to remove the repetition of the some surface segment
for k in L[j]#(L{j}>i) it seems to be slower
if i > k# there is no backstep, and i must be the largest (Equivalent: %((k~=i) && (i>k))%back step is not allowed
for m in L[k]
if ((m != j) && (j > m)) #&& (i>m) #back step is not allowed, and i must be the largest
if any(i .== L[m])
push!(DT4, (i, j, k, m))
end
end
end
end
end
end
end
end
return [[dt[[1,2,3]] for dt in DT4];[dt[[3,1,4]] for dt in DT4]]#DT2 triangular patch from the quadratic patch
end
"""
solve!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, iteration::Int; interpolationorder::Int=1)
Refine the `MDBM_Problem` `iteration` times, then perform a neighbour check.
`interpolationorder` defines the interpolation method within the n-cubes.
# Examples
```julia
julia> solve!(mymdbm,4)
```
"""
function solve!(mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}, iteration::Int; interpolationorder::Int = 1) where {fcT ,N ,Nf ,Nc ,t01T ,t11T ,IT ,FT,aT}
interpolate!(mdbm, interpolationorder = interpolationorder)
for k = 1:iteration
refine!(mdbm)
interpolate!(mdbm, interpolationorder = interpolationorder)
end
checkneighbour!(mdbm)
interpolate!(mdbm, interpolationorder = interpolationorder)
return mdbm
end
function index_sorted_in_sorted(a::AbstractVector, b::AbstractVector)::Array{Int64,1}
# index of a[i] in b (0 if not present)
# a and b must be sorted
containingindex = zeros(Int64, length(a))
startindex = 1;
for ind2check in 1:length(a)
detectedrange = searchsorted(b[startindex:end], a[ind2check])
startindex = max(detectedrange.stop, detectedrange.start) + startindex - 1
containingindex[ind2check] = isempty(detectedrange) ? 0 : startindex
if startindex > length(b)
break
end
end
return containingindex
end
function is_sorted_in_sorted(a::AbstractVector, b::AbstractVector)::Array{Bool,1}
# is a[i] in b
# a and b must be sorted
iscontained = falses(length(a))
startindex = 1;
for ind2check in 1:length(a)
detectedrange = searchsorted(b[startindex:end], a[ind2check])
etectedrange = searchsorted(view(b,startindex:length(b)), a[ind2check]) # still: it is the critical line!!!
iscontained[ind2check] = !isempty(detectedrange)
startindex = max(detectedrange.stop, detectedrange.start) + startindex - 1
if startindex > length(b)
break
end
end
return iscontained
end
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 7570 |
struct MDBMcontainer{RTf,RTc,AT}
funval::RTf
cval::RTc
callargs::AT
end
#TODO memoization for multiple functions Vector{Function}
struct MemF{fT,cT,RTf,RTc,AT} <:Function
f::fT
c::cT
fvalarg::Vector{MDBMcontainer{RTf,RTc,AT}}#funval,callargs
memoryacc::Vector{Int64} #number of function value call for already evaluated parameters
MemF(f::fT,c::cT,cont::Vector{MDBMcontainer{RTf,RTc,AT}}) where {fT,cT,RTf,RTc,AT}=new{fT,cT,RTf,RTc,AT}(f,c,cont,[Int64(0)])
end
(memfun::MemF{fT,cT,RTf,RTc,AT})(::Type{RTf},::Type{RTc},args...,) where {fT,cT,RTf,RTc,AT} =( memfun.f(args...,)::RTf, memfun.c(args...,)::RTc)
function (memfun::MemF{fT,cT,RTf,RTc,AT})(args...,) where {fT,cT,RTf,RTc,AT}
location=searchsortedfirst(memfun.fvalarg,args,lt=(x,y)->isless(x.callargs,y));
if length(memfun.fvalarg)<location
x=memfun(RTf,RTc,args...,);
push!(memfun.fvalarg,MDBMcontainer{RTf,RTc,AT}(x...,args))
return x
elseif memfun.fvalarg[location].callargs!=args
x=memfun(RTf,RTc,args...,);
insert!(memfun.fvalarg, location, MDBMcontainer{RTf,RTc,AT}(x...,args))
return x
else
memfun.memoryacc[1]+=1;
return (memfun.fvalarg[location].funval,memfun.fvalarg[location].cval);
end
end
function (memfun::MemF{fT,cT,RTf,RTc,AT})(args::Tuple) where {fT,cT,RTf,RTc,AT}
memfun(args...,)
end
"""
Axis{T}
Represent the parameter space in a discretized grid (vector) in `ticks`.
"""
struct Axis{T} <: AbstractVector{T}
ticks::Vector{T}
name
function Axis(T::Type,a::AbstractVector,name=:unknown)
new{T}(T.(a), name)
end
end
Base.getindex(ax::Axis{T}, ind) where T = ax.ticks[ind]::T
Base.setindex!(ax::Axis, X, inds...) = setindex!(ax.ticks, X, inds...)
Base.size(ax::Axis) = size(ax.ticks)
function Axis(a::AbstractVector{T}, name=:unknown) where T<:Real
Axis(Float64, a, name)
end
function Axis(a::AbstractVector{T}, name=:unknown) where T
Axis(T, a, name)
end
function Axis(a, name=:unknown) where T
Axis([a...], name)
end
function Axis(a::Axis)
a
end
struct Axes{N,aT}
axs::aT
end
function Axes(axs...)
axstosave=Axis.(axs)
Axes{length(axstosave),typeof(axstosave)}(Axis.(axstosave))
end
(axs::Axes)(ind...) = getindex.(axs.axs,ind)
# (axs::Axes)(ind::AbstractVector{<:Integer}) = axs(ind...)
Base.getindex(axs::Axes,inds...) = axs.axs[inds...]
Base.getindex(axs::Axes,inds::Vector{Integer}) = axs.axs[inds]
Base.iterate(axs::Axes) = iterate(axs.axs)
Base.iterate(axs::Axes,i) = iterate(axs.axs,i)
Base.size(::Axes{N,aT}) where {N,aT} = (N,)
Base.size(::Axes{N,aT},::Integer) where {N,aT} = N
Base.length(::Axes{N,aT}) where {N,aT} = N
struct NCube{IT,FT,N}
corner::MVector{N,IT} #"bottom-left" #Integer index of the axis
size::MVector{N,IT}#Integer index of the axis
posinterp::MVector{N,FT}#relative coordinate within the cube "(-1:1)" range
bracketingncube::Bool
# gradient ::MVector{MVector{T}}
# curvnorm::Vector{T}
end
Base.isless(a::NCube{IT,FT,N},b::NCube{IT,FT,N}) where IT where FT where N = Base.isless([a.corner,a.size],[b.corner,b.size])
Base.isequal(a::NCube{IT,FT,N},b::NCube{IT,FT,N}) where IT where FT where N = all([a.corner==b.corner,a.size==b.size])
import Base.==
==(a::NCube{IT,FT,N},b::NCube{IT,FT,N}) where IT where FT where N = all([a.corner==b.corner,a.size==b.size])
"""
struct MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT}
Store the main data for the Multi-Dimensional Bisection Method.
# Examples
```julia
include("MDBM.jl")
using Reexport
@reexport using .MDBM
function foo(x,y)
x^2.0+y^2.0-2.0^2.0
end
function c(x,y) #only the c>0 domain is analysed
x-y
end
ax1=Axis([-5,-2.5,0,2.5,5],"x") # initial grid in x direction
ax2=Axis(-5:2:5.0,"y") # initial grid in y direction
mymdbm=MDBM_Problem(foo,[ax1,ax2],constraint=c)
```
"""
struct MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}
"(memoized) function and constraint in a Tuple"
fc::fcT
"The vector of discretized parameters space"
axes::Axes{N,aT}
"the bracketing n-cubes (which contains a solution)"
ncubes::Vector{NCube{IT,FT,N}}
T01::t01T#
T11pinv::t11T
end
function MDBM_Problem(fc::fcT,axes,ncubes::Vector{NCube{IT,FT,N}},Nf,Nc) where fcT<:Function where IT<:Integer where FT<:AbstractFloat where N
T01=T01maker(Val(N))
T11pinv=T11pinvmaker(Val(N))
MDBM_Problem{fcT,N,Nf,Nc,typeof(T01),typeof(T11pinv),IT,FT,typeof((axes...,))}(fc,Axes(axes...),
[NCube{IT,FT,N}(SVector{N,IT}([x...]),SVector{N,IT}(ones(IT,length(x))),SVector{N,FT}(zeros(IT,length(x))),true) for x in Iterators.product((x->1:(length(x.ticks)-1)).(axes)...,)][:]
,T01,T11pinv)
end
function MDBM_Problem(f::Function, axes0::AbstractVector{<:Axis};constraint::Function=(x...,)->nothing, memoization::Bool=true,
#Nf=length(f(getindex.(axes0,1)...)),
Nf=f(getindex.(axes0,1)...) === nothing ? 0 : length(f(getindex.(axes0,1)...)),
Nc=constraint(getindex.(axes0,1)...) === nothing ? 0 : length(constraint(getindex.(axes0,1)...)))#Float16(1.), nothing
axes=deepcopy.(axes0);
argtypesofmyfunc=map(x->typeof(x).parameters[1], axes);#Argument Type
AT=Tuple{argtypesofmyfunc...};
type_f=Base.return_types(f,AT)
if length(type_f)==0
error("input of the function is not compatible with the provided axes")
else
RTf=type_f[1];#Return Type of f
end
type_con=Base.return_types(constraint, AT)
if length(type_con)==0
error("input of the constraint function is not compatible with the provided axes")
else
RTc=type_con[1];#Return Type of the constraint function
end
if memoization
fun=MemF(f, constraint,Array{MDBMcontainer{RTf,RTc,AT}}(undef, 0));
else
fun=(x)->(f(x...), constraint(x...));
end
Ndim=length(axes)
MDBM_Problem(fun, axes, Vector{NCube{Int64,Float64,Ndim}}(undef, 0), Nf, Nc)
end
function MDBM_Problem(f::Function, a::AbstractVector{<:AbstractVector};constraint::Function=(x...,)->nothing, memoization::Bool=true,
#Nf=length(f(getindex.(axes0,1)...)),
Nf=f(getindex.(a,1)...) === nothing ? 0 : length(f(getindex.(a,1)...)),
Nc=constraint(getindex.(a,1)...) === nothing ? 0 : length(constraint(getindex.(a,1)...)))
axes=[Axis(ax) for ax in a]
MDBM_Problem(f, axes, constraint = constraint, memoization=memoization, Nf=Nf, Nc=Nc)#,Vector{NCube{Int64,Float64,Val(Ndim)}}(undef, 0))
end
function Base.show(io::IO, mdbm::MDBM_Problem{fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}) where {fcT,N,Nf,Nc,t01T,t11T,IT,FT,aT}
println(io,"Multi-Dimensional Bisection Method Problem")
println(io," parameter dimension: ", N)#typeof(mdbm).parameters[2])#N
println(io," co-dimension: ", Nf)#typeof(mdbm).parameters[3])#Nf
println(io," number of constraints: ", Nc)#typeof(mdbm).parameters[4])#Nc
println(io,"Axes:")
for k in 1:length(mdbm.axes)
println(io," axis #",k,": elements: ",length(mdbm.axes[k]),"; elementtype: ", typeof(mdbm.axes[k][1]),"; first: ", mdbm.axes[k][1],"; last: ",mdbm.axes[k][end])
end
println(io,"number of bracketing n-cubes: ", length(mdbm.ncubes))
println()
if (typeof(mdbm.fc) <: MemF)
println(io,"number of function evaluation: ", length(mdbm.fc.fvalarg))
println(io,"number of memoized function call: ", mdbm.fc.memoryacc[1])
#println(io,"Ration of function evaluation compared to 'brute-force method': ", length(mdbm.fc.fvalarg)/prod(length.(mdbm.axes)))
else
println(io,"non-memoized version")
end
end
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | code | 792 | using MDBM
using Test
function tests()
@testset "Testing the Multi-Dimensional Bisection Method (MDBM) object" begin
@test begin
foo(x,y)=x^2.0+y^2.0-4.0^2.0
c(x,y)=x-y
ax1=Axis([-5,-2.5,0,2.5,5],"x")
ax2=Axis(-5:2:5.0,"b")
mymdbm=MDBM_Problem(foo,[ax1,ax2],constraint=c)
true
end
@test begin
mymdbm=MDBM_Problem((x,y)->x^2.0+y^2.0-4.0^2.0,[-5:5,-5:5])
true
end
end
@testset "Testing the MDBM solve!" begin
@test begin
mymdbm=MDBM_Problem((x,y)->x^2.0+y^2.0-4.0^2.0,[-5:5,-5:5])
iteration=2 #number of refinements (resolution doubling)
solve!(mymdbm,iteration)
true
end
end
end
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | docs | 6826 | # MDBM.jl
[](http://numfocus.org)
Multi-Dimensional Bisection Method (MDBM) is an efficient and robust root-finding algorithm, which can be used to determine whole high-dimensional submanifolds (points, curves, surfaces…) of the roots of implicit non-linear equation systems, especially in cases, where the number of unknowns surpasses the number of equations.
<a href="https://www.codecogs.com/eqnedit.php?latex=f_i(x_j)=0&space;\quad&space;i=1...k&space;\quad&space;j=1...l,&space;\quad&space;k&space;\leq&space;l" target="_blank"><img src="https://latex.codecogs.com/gif.latex?f_i(x_j)=0&space;\quad&space;i=1...k&space;\quad&space;j=1...l,&space;\quad&space;k&space;\leq&space;l" title="f_i(x_j)=0 \quad i=1...k \quad j=1...l, \quad k \leq l" /></a>
This type of problems can be found in many different field of science, just to mention a few:
- differential geometry (isolines, isosurfaces in higher dimensions)
- analysis of linkages (mechanical: workspace of robots)
- stability computation, stabilyzability diagrams
This method is an alternative to the contour plot or to isosurfaces in higher dimension, however, it has as the advantage of being able to handle multiple functions at once. <br>
In addition, it uses far less function evaluation than the brute-force approach, making it much faster and more memory efficient, especially for complex tasks.
## Introduction
The bisection method - or the so-called interval halving method - is one of the simplest root-finding algorithms which is used to find zeros of continuous non-linear functions.
This method is very robust and it always tends to the solution if the signs of the function values are different at the borders of the chosen initial interval.
Geometrically, root-finding algorithms of __f__(__x__)=0 find one intersection point of the graph of the function with the axis of the independent variable.
In many applications, this 1-dimensional intersection problem must be extended to higher dimensions, e.g.: intersections of surfaces in a 3D space (volume), which can be described as a system on non-linear implicit equations. In higher dimensions, the existence of multiple solutions becomes very important, since the intersection of two surfaces can create multiple intersection curves.
MDBM algorithm can handle:
* multiple solutions
* arbitrary number of variable (typically: 3-6)
* arbitrary number of implicit equations
* multiple constraints in the parameter space
* degenerated functions
while providing the gradients of the equations for the roots by means of first order interpolation (and convergence rate).
## Citing
The software in this ecosystem was developed as part of academic research. If you use the MDBM.jl package as part of your research, teaching, or other work, I would be grateful if you could cite my corresponding publication: <https://pp.bme.hu/me/article/view/1236/640>
## Web:
<https://www.mm.bme.hu/~bachrathy/research_EN.html>
# Quick start
Preparation
```julia
using MDBM
using PyPlot;
pygui(true);
```
## Example 1
Computation of a circle section defined by the implicit equation `foo(x,y) == 0` and by the constraint `c(x,y) > 0`
```julia
function foo(x,y)
x^2.0+y^2.0-2.0^2.0
end
function c(x,y) #only the c>0 domain is analysed
x-y
end
ax1=Axis([-5,-2.5,0,2.5,5],"x") # initial grid in x direction
ax2=Axis(-5:2:5.0,"y") # initial grid in y direction
mymdbm=MDBM_Problem(foo,[ax1,ax2],constraint=c)
iteration=5 #number of refinements (resolution doubling)
solve!(mymdbm,iteration)
#points where the function foo was evaluated
x_eval,y_eval=getevaluatedpoints(mymdbm)
#interpolated points of the solution (approximately where foo(x,y) == 0 and c(x,y)>0)
x_sol,y_sol=getinterpolatedsolution(mymdbm)
fig = figure(1);clf()
scatter(x_eval,y_eval,s=5)
scatter(x_sol,y_sol,s=5)
```
<img src="assets/circe_2D_points.png"
alt="solution "/>
Perform the line connection
```julia
myDT1=connect(mymdbm);
for i in 1:length(myDT1)
dt=myDT1[i]
P1=getinterpolatedsolution(mymdbm.ncubes[dt[1]],mymdbm)
P2=getinterpolatedsolution(mymdbm.ncubes[dt[2]],mymdbm)
plot([P1[1],P2[1]],[P1[2],P2[2]], color="k")
end
```
<img src="assets/circe_2D_line.png"
alt="solution "/>
## Example 2
Intersection of two sphere in 3D
```julia
using LinearAlgebra
axes=[-2:2,-2:2,-2:2]
fig = figure(3);clf()
#Sphere1
fS1(x...) = norm(x,2.0)-1
Sphere1mdbm=MDBM_Problem(fS1,axes)
solve!(Sphere1mdbm,4)
a_sol,b_sol,c_sol=getinterpolatedsolution(Sphere1mdbm)
plot3D(a_sol,b_sol,c_sol,linestyle="", marker=".", markersize=1);
#Sphere2
fS2(x...) = norm(x .- 0.5, 2.0) -1.0
Sphere2mdbm=MDBM_Problem(fS2,axes)
solve!(Sphere2mdbm,4)
a_sol,b_sol,c_sol=getinterpolatedsolution(Sphere2mdbm)
plot3D(a_sol,b_sol,c_sol,linestyle="", marker=".", markersize=1);
#Intersection
fS12(x...) = (fS1(x...), fS2(x...))
Intersectmdbm=MDBM_Problem(fS12,axes)
solve!(Intersectmdbm,6)
a_sol,b_sol,c_sol=getinterpolatedsolution(Intersectmdbm)
plot3D(a_sol,b_sol,c_sol,color="k",linestyle="", marker=".", markersize=2);
```
<img src="assets/sphere_intersection.png"
alt="solution "/>
## Example 3
Mandelbrot set (example for a non-smooth problem)
```julia
function mandelbrot(x,y)
c=x+y*im
z=Complex(zero(c))
k=0
maxiteration=1000
while (k<maxiteration && abs(z)<4)
z=z^2+c
k=k+1
end
return abs(z)-2
end
Mandelbrotmdbm=MDBM_Problem(mandelbrot,[-5:2,-2:2])
solve!(Mandelbrotmdbm,9)
a_sol,b_sol=getinterpolatedsolution(Mandelbrotmdbm)
fig = figure(3);clf()
plot(a_sol,b_sol,linestyle="", marker=".", markersize=1)
```
<img src="assets/Mandelbrot.png"
alt="solution "/>
## History
I am an assistant professor at the Budapest University of Technology and Economics, at the Faculty of Mechanical Engineering, the Department of Applied Mechanics.
During my studies and research, I have to determine stability charts of models described by delayed differential equations, which are typically formed as a "3 parameter / 2 implicit equation" problem. I have faced the difficulty that there is no applicable solution in any available software (e.g.: Mathematica, Matlab,...) which could easily be used in engineering problems.
Due to this reason, I have started to develop the Multi-Dimensional Bisection Method since 2006 in Matlab, and I have been improving it since, by adding new features from time to time.
I hope that others also find this package a useful tool in their work.
Best regards,
Dr. Daniel Bachrathy
#

MDBM is a fiscally sponsored project of [NumFOCUS](https://numfocus.org), a
nonprofit dedicated to supporting the open source scientific computing
community.
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.1.5 | 21860fcff00b8daf031f9b3250ed0a106b6df0c9 | docs | 92 | ```@meta
CurrentModule = MDBM
```
# MDBM
```@index
```
```@autodocs
Modules = [MDBM]
```
| MDBM | https://github.com/bachrathyd/MDBM.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 485 |
#
# Stress test to check for memory leaks (#24)
#
using Mongoc
client = Mongoc.Client() # default locahost:27017
db = client["testDB"]
collection=db["testCollection"]
document = Mongoc.BSON()
document["name"] = "Felipe"
document["age"] = 35
document["preferences"] = [ "Music", "Computer", "Photography" ]
# generate some entries
for i in 1:100000
push!(collection, document)
end
# read bson documents from collection
for i in 1:10000
for entry in collection
end
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 605 |
using Documenter, Mongoc
makedocs(
sitename = "Mongoc.jl",
modules = [ Mongoc ],
pages = [ "Home" => "index.md",
"Tutorial" => "tutorial.md",
"CRUD Operations" => "crud.md",
"Authentication" => "authentication.md",
"Transactions" => "transaction.md",
"Connection Pool" => "connection_pool.md",
"GridFS" => "gridfs.md",
"Logging" => "logging.md",
"API Reference" => "api.md",
]
)
deploydocs(
repo = "github.com/felipenoris/Mongoc.jl.git",
target = "build",
)
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 727 |
module Mongoc
using MongoC_jll
import Base.UUID
using Dates, DecFP, Serialization
#
# utility functions for date conversion
#
# offsets an additional year from UNIXEPOCH in milliseconds.
const ISODATE_OFFSET = Dates.UNIXEPOCH + 24 * 60 * 60 * 1000 * 365
isodate2datetime(millis::Int64) = Dates.epochms2datetime(millis + ISODATE_OFFSET)
datetime2isodate(dt::DateTime) = Dates.datetime2epochms(dt) - ISODATE_OFFSET
include("bson.jl")
include("types.jl")
include("c_api.jl")
include("client.jl")
include("clientpool.jl")
include("database.jl")
include("collection.jl")
include("session.jl")
include("streams.jl")
include("gridfs.jl")
function __init__()
mongoc_init()
atexit(mongoc_cleanup)
end
end # module Mongoc
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 29518 |
#
# Types
#
# BSONType mirrors C enum bson_type_t.
primitive type BSONType 8 end # 1 byte
Base.convert(::Type{T}, t::BSONType) where {T<:Number} = reinterpret(UInt8, t)
Base.convert(::Type{BSONType}, n::T) where {T<:Number} = reinterpret(BSONType, n)
BSONType(u::UInt8) = convert(BSONType, u)
#
# Constants for BSONType
#
const BSON_TYPE_EOD = BSONType(0x00)
const BSON_TYPE_DOUBLE = BSONType(0x01)
const BSON_TYPE_UTF8 = BSONType(0x02)
const BSON_TYPE_DOCUMENT = BSONType(0x03)
const BSON_TYPE_ARRAY = BSONType(0x04)
const BSON_TYPE_BINARY = BSONType(0x05)
const BSON_TYPE_UNDEFINED = BSONType(0x06)
const BSON_TYPE_OID = BSONType(0x07)
const BSON_TYPE_BOOL = BSONType(0x08)
const BSON_TYPE_DATE_TIME = BSONType(0x09)
const BSON_TYPE_NULL = BSONType(0x0A)
const BSON_TYPE_REGEX = BSONType(0x0B)
const BSON_TYPE_DBPOINTER = BSONType(0x0C)
const BSON_TYPE_CODE = BSONType(0x0D)
const BSON_TYPE_SYMBOL = BSONType(0x0E)
const BSON_TYPE_CODEWSCOPE = BSONType(0x0F)
const BSON_TYPE_INT32 = BSONType(0x10)
const BSON_TYPE_TIMESTAMP = BSONType(0x11)
const BSON_TYPE_INT64 = BSONType(0x12)
const BSON_TYPE_DECIMAL128 = BSONType(0x13)
const BSON_TYPE_MAXKEY = BSONType(0x7F)
const BSON_TYPE_MINKEY = BSONType(0xFF)
# BSONSubType mirrors C enum bson_subtype_t.
primitive type BSONSubType 8 end
Base.convert(::Type{T}, t::BSONSubType) where {T<:Number} = reinterpret(UInt8, t)
Base.convert(::Type{BSONSubType}, n::T) where {T<:Number} = reinterpret(BSONSubType, n)
BSONSubType(u::UInt8) = convert(BSONSubType, u)
#
# Constants for BSONSubType
#
const BSON_SUBTYPE_BINARY = BSONSubType(0x00)
const BSON_SUBTYPE_FUNCTION = BSONSubType(0x01)
const BSON_SUBTYPE_BINARY_DEPRECATED = BSONSubType(0x02)
const BSON_SUBTYPE_UUID_DEPRECATED = BSONSubType(0x03)
const BSON_SUBTYPE_UUID = BSONSubType(0x04)
const BSON_SUBTYPE_MD5 = BSONSubType(0x05)
const BSON_SUBTYPE_USER = BSONSubType(0x80)
#=
BSONIter mirrors C struct bson_iter_t and can be allocated in the stack.
According to [libbson documentation](http://mongoc.org/libbson/current/bson_iter_t.html),
it is meant to be used on the stack and can be discarded at any time
as it contains no external allocation.
The contents of the structure should be considered private
and may change between releases, however the structure size will not change.
Inspecting its size in C, we get:
```c
sizeof(bson_iter_t) == 80
```
=#
primitive type BSONIter 80 * 8 end # 80 bytes
"""
A `BSONObjectId` represents a unique identifier
for a BSON document.
# Example
The following generates a new `BSONObjectId`.
```julia
julia> Mongoc.BSONObjectId()
```
# C API
`BSONObjectId` instances addresses are passed
to libbson/libmongoc API using `Ref(oid)`,
and are owned by the Julia process.
Mirrors C struct `bson_oid_t`:
```c
typedef struct {
uint8_t bytes[12];
} bson_oid_t;
```
"""
struct BSONObjectId
bytes::NTuple{12, UInt8}
end
function BSONObjectId()
oid_ref = Ref{BSONObjectId}()
bson_oid_init(oid_ref, C_NULL)
return oid_ref[]
end
function BSONObjectId(oid_string::String)
if !bson_oid_is_valid(oid_string)
error("'$oid_string' is not a valid ObjectId.")
end
oid_ref = Ref{BSONObjectId}()
bson_oid_init_from_string(oid_ref, oid_string)
return oid_ref[]
end
function BSONObjectId(oid::BSONObjectId)
return BSONObjectId(oid.bytes)
end
Base.copy(oid::BSONObjectId) = BSONObjectId(oid)
"""
`BSONError` is the default `Exception`
for BSON/MongoDB function call errors.
# C API
Mirrors C struct `bson_error_t`.
`BSONError` instances addresses are passed
to libbson/libmongoc API using `Ref(error)`,
and are owned by the Julia process.
```c
typedef struct {
uint32_t domain;
uint32_t code;
char message[504];
} bson_error_t;
```
"""
struct BSONError <: Exception
domain::UInt32
code::UInt32
message::NTuple{504, UInt8}
end
"""
`BSONCode` is a BSON element
with JavaScript source code.
# Example
```julia
julia> bson = Mongoc.BSON("source" => Mongoc.BSONCode("function() = 1"))
BSON("{ "source" : { "\$code" : "function() = 1" } }")
```
"""
struct BSONCode
code::String
end
"""
`BSONTimestamp` is a special internal type used by MongoDB replication and sharding.
"""
struct BSONTimestamp
timestamp::UInt32
increment::UInt32
end
"""
A `BSON` represents a document in *Binary JSON* format,
defined at http://bsonspec.org/.
In Julia, you can manipulate a `BSON` instance
just like a `Dict`.
# Example
```julia
bson = Mongoc.BSON()
bson["name"] = "my name"
bson["num"] = 10.0
```
# C API
`BSON` is a wrapper for C struct `bson_t`.
"""
mutable struct BSON <: AbstractDict{String, Any}
handle::Ptr{Cvoid}
function BSON(handle::Ptr{Cvoid}; enable_finalizer::Bool=true)
new_bson = new(handle)
if enable_finalizer
finalizer(destroy!, new_bson)
end
return new_bson
end
end
function destroy!(bson::BSON)
if bson.handle != C_NULL
bson_destroy(bson.handle)
bson.handle = C_NULL
end
nothing
end
"""
Wrapper for bson_value_t.
See [`Mongoc.get_as_bson_value`](@ref).
"""
mutable struct BSONValue
handle::Ptr{Cvoid}
end
function Base.deepcopy_internal(x::BSON, stackdict::IdDict)
if haskey(stackdict, x)
return stackdict[x]
end
y = BSON(bson_copy(x.handle))
stackdict[x] = y
return y
end
abstract type AbstractBSONReader end
mutable struct BSONReader <: AbstractBSONReader
handle::Ptr{Cvoid}
data::Vector{UInt8}
function BSONReader(handle::Ptr{Cvoid}, data::Vector{UInt8})
new_reader = new(handle, data)
finalizer(destroy!, new_reader)
return new_reader
end
end
BSONReader(handle::Ptr{Cvoid}) = BSONReader(handle, Vector{UInt8}())
function destroy!(reader::BSONReader)
if reader.handle != C_NULL
bson_reader_destroy(reader.handle)
reader.handle = C_NULL
end
nothing
end
const DEFAULT_BSON_WRITER_BUFFER_CAPACITY = 2^10
# buffer_handle must be a valid pointer to a Buffer object.
# A reference to this buffer must be kept from outside this function
# to avoid GC on it.
function unsafe_buffer_realloc(buffer_ptr::Ptr{UInt8}, num_bytes::Csize_t, writer_objref::Ptr{Cvoid})
local writer::BSONWriter = unsafe_pointer_to_objref(writer_objref)
@assert buffer_ptr == pointer(writer.buffer) "Is this the same BSONWriter?"
current_len = length(writer.buffer)
inc = num_bytes - current_len
if inc > 0
append!(writer.buffer, [ UInt8(0) for i in 1:inc ])
end
@assert length(writer.buffer) == num_bytes
writer.buffer_length_ref[] = num_bytes
return pointer(writer.buffer)
end
mutable struct BSONWriter
handle::Ptr{Cvoid}
buffer::Vector{UInt8}
buffer_handle_ref::Ref{Ptr{UInt8}}
buffer_length_ref::Ref{Csize_t}
function BSONWriter(initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY,
buffer_offset::Integer=0)
buffer = zeros(UInt8, initial_buffer_capacity)
new_writer = new(C_NULL, buffer, Ref(pointer(buffer)), Ref(Csize_t(initial_buffer_capacity)))
finalizer(destroy!, new_writer)
realloc_func = @cfunction(unsafe_buffer_realloc, Ptr{UInt8}, (Ptr{UInt8}, Csize_t, Ptr{Cvoid}))
handle = bson_writer_new(new_writer.buffer_handle_ref,
new_writer.buffer_length_ref,
Csize_t(buffer_offset),
realloc_func,
pointer_from_objref(new_writer))
if handle == C_NULL
error("Failed to create a BSONWriter.")
end
new_writer.handle = handle
return new_writer
end
end
function destroy!(writer::BSONWriter)
if writer.handle != C_NULL
bson_writer_destroy(writer.handle)
writer.handle = C_NULL
end
nothing
end
#
# API
#
Base.String(oid::BSONObjectId) = bson_oid_to_string(oid)
Base.convert(::Type{BSONObjectId}, oid_string::String) = BSONObjectId(oid_string)
Base.String(code::BSONCode) = code.code
Base.convert(::Type{BSONCode}, code_string::String) = BSONCode(code_string)
Base.show(io::IO, oid::BSONObjectId) = print(io, "BSONObjectId(\"", String(oid), "\")")
Base.show(io::IO, bson::BSON) = print(io, "BSON(\"", as_json(bson), "\")")
Base.show(io::IO, code::BSONCode) = print(io::IO, "BSONCode(\"$(code.code)\")")
function Base.show(io::IO, err::BSONError)
print(io, "BSONError: domain=$(Int(err.domain)), code=$(Int(err.code)), message=")
for c in err.message
c_char = Char(c)
if c_char == '\0'
break
else
print(io, c_char)
end
end
end
Base.showerror(io::IO, err::BSONError) = show(io, err)
function get_time(oid::BSONObjectId)
return Dates.unix2datetime(bson_oid_get_time_t(oid))
end
function BSON()
handle = bson_new()
if handle == C_NULL
error("Failed to create a new BSON document.")
end
return BSON(handle)
end
function BSON(json_string::String)
handle = bson_new_from_json(json_string)
if handle == C_NULL
error("Failed parsing JSON to BSON. $json_string.")
end
return BSON(handle)
end
function BSON(vector::Vector)
result = BSON()
for (i, v) in enumerate(vector)
result[string(i-1)] = v
end
return result
end
function BSON(args::Pair...)
result = BSON()
for (k, v) in args
result[k] = v
end
return result
end
BSON(dict::AbstractDict) = BSON(dict...)
"""
as_json(bson::BSON; canonical::Bool=false) :: String
Converts a `bson` object to a JSON string.
# Example
```julia
julia> document = Mongoc.BSON("{ \"hey\" : 1 }")
BSON("{ "hey" : 1 }")
julia> Mongoc.as_json(document)
"{ \"hey\" : 1 }"
julia> Mongoc.as_json(document, canonical=true)
"{ \"hey\" : { \"\$numberInt\" : \"1\" } }"
```
# C API
* [`bson_as_canonical_extended_json`](http://mongoc.org/libbson/current/bson_as_canonical_extended_json.html)
* [`bson_as_relaxed_extended_json`](http://mongoc.org/libbson/current/bson_as_relaxed_extended_json.html)
"""
function as_json(bson::BSON; canonical::Bool=false) :: String
local bson_cstring::Cstring
if canonical
bson_cstring = bson_as_canonical_extended_json(bson.handle)
else
bson_cstring = bson_as_relaxed_extended_json(bson.handle)
end
if bson_cstring == C_NULL
error("Couldn't convert bson to json.")
end
result = unsafe_string(bson_cstring)
bson_free(convert(Ptr{Cvoid}, bson_cstring))
return result
end
Base.length(document::BSON) = bson_count_keys(document.handle)
#
# Read values from BSON
#
has_field(bson::BSON, key::AbstractString) = bson_has_field(bson.handle, key)
Base.haskey(bson::BSON, key::AbstractString) = has_field(bson, key)
function bson_iter_init(document::BSON)
iter_ref = Ref{BSONIter}()
ok = bson_iter_init(iter_ref, document.handle)
if !ok
error("Couldn't create iterator for BSON document.")
end
return iter_ref
end
abstract type BSONIteratorMode end
struct IterateKeys <: BSONIteratorMode
end
# get the current value from iter_ref according to the mode
_get(iter_ref::Ref{BSONIter}, ::Type{IterateKeys}) =
unsafe_string(bson_iter_key(iter_ref))
struct IterateValues <: BSONIteratorMode
end
_get(iter_ref::Ref{BSONIter}, ::Type{IterateValues}) =
get_value(iter_ref)
struct IterateKeyValuePairs <: BSONIteratorMode
end
_get(iter_ref::Ref{BSONIter}, ::Type{IterateKeyValuePairs}) =
_get(iter_ref, IterateKeys) => _get(iter_ref, IterateValues)
struct BSONIterator{M<:BSONIteratorMode}
bson_iter_ref::Ref{BSONIter}
document::BSON
BSONIterator(document::BSON, ::Type{M}) where {M<:BSONIteratorMode} =
new{M}(bson_iter_init(document), document)
end
Base.IteratorSize(::Type{BSONIterator{M}}) where M = Base.HasLength()
Base.length(iter::BSONIterator) = length(iter.document)
Base.IteratorEltype(::Type{BSONIterator{M}}) where M = Base.EltypeUnknown()
Base.IteratorEltype(::Type{BSONIterator{IterateKeys}}) = Base.HasEltype()
Base.eltype(::Type{BSONIterator{IterateKeys}}) = String
Base.iterate(itr::BSONIterator{M}, state::Nothing = nothing) where M =
bson_iter_next(itr.bson_iter_ref) ?
(_get(itr.bson_iter_ref, M), state) : nothing
function Base.iterate(doc::BSON,
itr::BSONIterator = BSONIterator(doc, IterateKeyValuePairs))
next = iterate(itr)
return isnothing(next) ? nothing : (first(next), itr)
end
Base.keys(doc::BSON) = BSONIterator(doc, IterateKeys)
Base.values(doc::BSON) = BSONIterator(doc, IterateValues)
"""
as_dict(document::BSON) :: Dict{String}
Converts a BSON document to a Julia `Dict`.
"""
as_dict(document::BSON) = convert(Dict, document)
function as_dict(iter_ref::Ref{BSONIter})
result = Dict{String, Any}()
while bson_iter_next(iter_ref)
result[unsafe_string(bson_iter_key(iter_ref))] = get_value(iter_ref)
end
return result
end
"""
get_array(doc::BSON, key::AbstractString, ::Type{T})
Get an array from the document with a specified type `T`. This allows obtaining
a type-stable return value. Note that if an array element cannot be converted
to the specified type, an error will be thrown.
"""
function get_array(document::BSON, key::AbstractString, ::Type{T}) where T
iter_ref = Ref{BSONIter}()
ok = bson_iter_init_find(iter_ref, document.handle, key)
if !ok
error("Key $key not found.")
end
bson_type = bson_iter_type(iter_ref)
if bson_type != BSON_TYPE_ARRAY
error("Not a BSON array!")
end
return get_array(iter_ref, T)
end
function get_array(iter_ref::Ref{BSONIter}, ::Type{T}) where T
bson_type = bson_iter_type(iter_ref)
@assert bson_type == BSON_TYPE_ARRAY
child_iter_ref = Ref{BSONIter}()
ok = bson_iter_recurse(iter_ref, child_iter_ref)
if !ok
error("Couldn't iterate array inside BSON.")
end
result_array = Vector{T}()
while bson_iter_next(child_iter_ref)
push!(result_array, get_value(child_iter_ref))
end
return result_array
end
function get_value(iter_ref::Ref{BSONIter})
bson_type = bson_iter_type(iter_ref)
if bson_type == BSON_TYPE_UTF8
return unsafe_string(bson_iter_utf8(iter_ref))
elseif bson_type == BSON_TYPE_INT64
return bson_iter_int64(iter_ref)
elseif bson_type == BSON_TYPE_INT32
return bson_iter_int32(iter_ref)
elseif bson_type == BSON_TYPE_DOUBLE
return bson_iter_double(iter_ref)
elseif bson_type == BSON_TYPE_DECIMAL128
return bson_iter_decimal128(iter_ref)
elseif bson_type == BSON_TYPE_OID
# converts Ptr{BSONObjectId} to BSONObjectId
return unsafe_load(bson_iter_oid(iter_ref))
elseif bson_type == BSON_TYPE_BOOL
return bson_iter_bool(iter_ref)
elseif bson_type == BSON_TYPE_DATE_TIME
millis = Int64(bson_iter_date_time(iter_ref))
return isodate2datetime(millis)
elseif bson_type == BSON_TYPE_TIMESTAMP
return bson_iter_timestamp(iter_ref)
elseif bson_type == BSON_TYPE_ARRAY
return get_array(iter_ref, Any)
elseif bson_type == BSON_TYPE_DOCUMENT
child_iter_ref = Ref{BSONIter}()
ok = bson_iter_recurse(iter_ref, child_iter_ref)
if !ok
error("Couldn't iterate document inside BSON.")
end
return as_dict(child_iter_ref)
elseif bson_type == BSON_TYPE_BINARY
subtype_ref = Ref{BSONSubType}()
length_ref = Ref{UInt32}()
buffer_ref = Ref{Ptr{UInt8}}()
bson_iter_binary(iter_ref, subtype_ref, length_ref, buffer_ref)
result_data = Vector{UInt8}(undef, length_ref[])
unsafe_copyto!(pointer(result_data), buffer_ref[], length_ref[])
is_uuid = subtype_ref[] == BSON_SUBTYPE_UUID || subtype_ref[] == BSON_SUBTYPE_UUID_DEPRECATED
if is_uuid && length(result_data) == 16
return UUID(reinterpret(UInt128, result_data)[1])
end
return result_data
elseif bson_type == BSON_TYPE_CODE
return BSONCode(unsafe_string(bson_iter_code(iter_ref)))
elseif bson_type == BSON_TYPE_NULL
return nothing
else
error("BSON Type not supported: $bson_type.")
end
end
function Base.getindex(document::BSON, key::AbstractString)
iter_ref = Ref{BSONIter}()
bson_iter_init_find(iter_ref, document.handle, key) || throw(KeyError(key))
return get_value(iter_ref)
end
function Base.get(document::BSON, key::AbstractString, default::Any)
iter_ref = Ref{BSONIter}()
return bson_iter_init_find(iter_ref, document.handle, key) ? get_value(iter_ref) : default
end
"""
get_as_bson_value(doc, key) :: BSONValue
Returns a value stored in a bson document `doc`
as a `BSONValue`.
See also [Mongoc.BSONValue](@ref).
"""
function get_as_bson_value(document::BSON, key::AbstractString) :: BSONValue
iter_ref = Ref{BSONIter}()
bson_iter_init_find(iter_ref, document.handle, key) || throw(KeyError(key))
return get_as_bson_value(iter_ref)
end
function get_as_bson_value(iter_ref::Ref{BSONIter})
# this BSONValue may be valid only during
# the lifetime of the BSON document
return BSONValue(bson_iter_value(iter_ref))
end
#
# Write values to BSON
#
function Base.setindex!(document::BSON, value::BSONObjectId, key::AbstractString)
ok = bson_append_oid(document.handle, key, -1, value)
if !ok
error("Couldn't append oid to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::Int64, key::AbstractString)
ok = bson_append_int64(document.handle, key, -1, value)
if !ok
error("Couldn't append Int64 to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::Int32, key::AbstractString)
ok = bson_append_int32(document.handle, key, -1, value)
if !ok
error("Couldn't append Int32 to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::AbstractString, key::AbstractString)
ok = bson_append_utf8(document.handle, key, -1, value, -1)
if !ok
error("Couldn't append String to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::Bool, key::AbstractString)
ok = bson_append_bool(document.handle, key, -1, value)
if !ok
error("Couldn't append Bool to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::Float64, key::AbstractString)
ok = bson_append_double(document.handle, key, -1, value)
if !ok
error("Couldn't append Float64 to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::Dec128, key::AbstractString)
ok = bson_append_decimal128(document.handle, key, -1, value)
if !ok
error("Couldn't append Dec128 to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::DateTime, key::AbstractString)
ok = bson_append_date_time(document.handle, key, -1, datetime2isodate(value))
if !ok
error("Couldn't append DateTime to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::BSON, key::AbstractString)
ok = bson_append_document(document.handle, key, -1, value.handle)
if !ok
error("Couldn't append Sub-Document BSON to BSON document.")
end
nothing
end
Base.setindex!(document::BSON, value::Dict, key::AbstractString) = setindex!(document, BSON(value), key)
function Base.setindex!(document::BSON, value::Vector{T}, key::AbstractString) where T
sub_document = BSON(value)
ok = bson_append_array(document.handle, key, -1, sub_document.handle)
if !ok
error("Couldn't append array to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::BSONCode, key::AbstractString)
ok = bson_append_code(document.handle, key, -1, value.code)
if !ok
error("Couldn't append String to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::Date, key::AbstractString)
error("BSON format does not support `Date` type. Use `DateTime` instead.")
end
function Base.setindex!(document::BSON, value::Vector{UInt8}, key::AbstractString)
ok = bson_append_binary(document.handle, key, -1, BSON_SUBTYPE_BINARY, value, UInt32(length(value)))
if !ok
error("Couldn't append array to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, value::UUID, key::AbstractString)
value = [reinterpret(UInt8, [value.value])...]
ok = bson_append_binary(document.handle, key, -1, BSON_SUBTYPE_UUID, value, UInt32(length(value)))
if !ok
error("Couldn't append uuid to BSON document.")
end
nothing
end
function Base.setindex!(document::BSON, ::Nothing, key::AbstractString)
ok = bson_append_null(document.handle, key, -1)
if !ok
error("Couldn't append missing value to BSON document.")
end
nothing
end
#
# Write/Read BSON to/from IO
#
function _get_number_of_bytes_written_to_buffer(buffer::Vector{UInt8}) :: Int64
isempty(buffer) && return 0
# the first 4 bytes in data is a size int32
doc_size = reinterpret(Int32, buffer[1:4])[1]
local total_size::Int64 = 0
while doc_size != 0
total_size += doc_size
if length(buffer) < total_size + 4
break
end
doc_size = reinterpret(Int32, buffer[total_size+1:total_size+4])[1]
end
return total_size
end
function _get_number_of_bytes_written_to_buffer(writer::BSONWriter)
_get_number_of_bytes_written_to_buffer(writer.buffer)
end
function bson_writer(f::Function, io::IO;
initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)
writer = BSONWriter(initial_buffer_capacity)
try
f(writer)
@assert bson_writer_get_length(writer.handle) == _get_number_of_bytes_written_to_buffer(writer)
for byte_index in 1:bson_writer_get_length(writer.handle)
write(io, writer.buffer[byte_index])
end
flush(io)
finally
destroy!(writer)
end
nothing
end
function write_bson(f::Function, writer::BSONWriter)
bson_handle_ref = Ref{Ptr{Cvoid}}(C_NULL)
ok = bson_writer_begin(writer.handle, bson_handle_ref)
if !ok
error("Failed to write bson document to IO: there was not enough space in buffer. Increase the buffer initial capacity.")
end
bson = BSON(bson_handle_ref[], enable_finalizer=false)
f(bson)
bson_writer_end(writer.handle)
end
"""
write_bson(io::IO, bson::BSON;
initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)
Writes a single BSON document to `io` in binary format.
"""
function write_bson(io::IO, bson::BSON;
initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)
bson_writer(io, initial_buffer_capacity=initial_buffer_capacity) do writer
write_bson(writer) do dest
bson_copy_to_noinit(bson.handle, dest.handle)
end
end
nothing
end
struct BufferedBSON
bson_data::Vector{UInt8}
end
function BufferedBSON(bson::BSON)
io = IOBuffer()
write_bson(io, bson)
return BufferedBSON(take!(io))
end
BSON(buff::BufferedBSON) :: BSON = read_bson(buff.bson_data)[1]
function Serialization.serialize(s::AbstractSerializer, bson::BSON)
Serialization.serialize_type(s, BSON)
Serialization.serialize(s.io, BufferedBSON(bson))
end
function Serialization.deserialize(s::AbstractSerializer, ::Type{BSON})
BSON(Serialization.deserialize(s.io))
end
Base.write(io::IO, bson::BSON) = serialize(io, bson)
Base.read(io::IO, ::Type{BSON}) = deserialize(io)::BSON
"""
write_bson(io::IO, bson_list::Vector{BSON};
initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)
Writes a vector of BSON documents to `io` in binary format.
# Example
```julia
list = Vector{Mongoc.BSON}()
let
src = Mongoc.BSON()
src["id"] = 1
src["name"] = "1st"
push!(list, src)
end
let
src = Mongoc.BSON()
src["id"] = 2
src["name"] = "2nd"
push!(list, src)
end
open("documents.bson", "w") do io
Mongoc.write_bson(io, list)
end
```
"""
function write_bson(io::IO, bson_list::Vector{BSON};
initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)
bson_writer(io, initial_buffer_capacity=initial_buffer_capacity) do writer
for src_bson in bson_list
write_bson(writer) do dest
bson_copy_to_noinit(src_bson.handle, dest.handle)
end
end
end
nothing
end
"""
read_bson(io::IO) :: Vector{BSON}
Reads all BSON documents from `io`.
This method will continue to read from `io` until
it reaches eof.
"""
read_bson(io::IO) :: Vector{BSON} = read_bson(read(io))
"""
read_bson(data::Vector{UInt8}) :: Vector{BSON}
Parses a vector of bytes to a vector of BSON documents.
Useful when reading BSON as binary from a stream.
"""
function read_bson(data::Vector{UInt8}) :: Vector{BSON}
reader = BSONReader(data)
try
return read_bson(reader)
finally
destroy!(reader)
end
end
function BSONReader(data::Vector{UInt8})
if isempty(data)
error("input data is empty")
end
data_shrinked = data[1:_get_number_of_bytes_written_to_buffer(data)]
reader_handle = bson_reader_new_from_data(pointer(data_shrinked), length(data_shrinked))
if reader_handle == C_NULL
error("Failed to create a BSONReader.")
end
return BSONReader(reader_handle, data_shrinked)
end
"""
read_bson(filepath::AbstractString) :: Vector{BSON}
Reads all BSON documents from a file located at `filepath`.
This will open a `Mongoc.BSONReader` pointing to the file
and will parse file contents to BSON documents.
"""
function read_bson(filepath::AbstractString) :: Vector{BSON}
reader = BSONReader(filepath)
try
return read_bson(reader)
finally
destroy!(reader)
end
end
function BSONReader(filepath::AbstractString)
@assert isfile(filepath) "$filepath not found."
err_ref = Ref{BSONError}()
reader_handle = bson_reader_new_from_file(filepath, err_ref)
if reader_handle == C_NULL
throw(err_ref[])
end
return BSONReader(reader_handle)
end
"""
read_next_bson(reader::BSONReader) :: Union{Nothing, BSON}
Reads the next BSON document available in the stream pointed by `reader`.
Returns `nothing` if reached the end of the stream.
"""
function read_next_bson(reader::BSONReader) :: Union{Nothing, BSON}
reached_eof_ref = Ref(false)
bson_handle = bson_reader_read(reader.handle, reached_eof_ref)
if bson_handle == C_NULL
if !reached_eof_ref[]
@warn("Finished reading BSON from stream, but didn't reach stream's eof.")
end
return nothing
end
bson_copy_handle = bson_copy(bson_handle) # creates a copy with its own lifetime
return BSON(bson_copy_handle)
end
mutable struct BSONJSONReader <: AbstractBSONReader
handle::Ptr{Cvoid}
function BSONJSONReader(handle::Ptr{Cvoid})
new_reader = new(handle)
finalizer(destroy!, new_reader)
return new_reader
end
end
function destroy!(reader::BSONJSONReader)
if reader.handle != C_NULL
bson_json_reader_destroy(reader.handle)
reader.handle = C_NULL
end
nothing
end
function BSONJSONReader(filepath::AbstractString)
@assert isfile(filepath) "$filepath not found."
err_ref = Ref{BSONError}()
reader_handle = bson_json_reader_new_from_file(filepath, err_ref)
if reader_handle == C_NULL
throw(err_ref[])
end
return BSONJSONReader(reader_handle)
end
function read_next_bson(reader::BSONJSONReader, buffer::BSON=BSON()) :: Union{Nothing, BSON}
err_ref = Ref{BSONError}()
ok = bson_json_reader_read(reader.handle, buffer.handle, err_ref)
if ok == 1 # successful and data was read
bson_copy_handle = bson_copy(buffer.handle)
return BSON(bson_copy_handle)
elseif ok == 0 # successful and no data was read
return nothing
elseif ok == -1 # there was an error
throw(err_ref[])
else # unexpected
error("Unexpected result from bson_json_reader_read: $ok.")
end
end
function Base.iterate(reader::AbstractBSONReader, state=nothing)
next_bson = read_next_bson(reader)
if next_bson == nothing
return nothing
else
return (next_bson, nothing)
end
end
Base.collect(reader::AbstractBSONReader) = read_bson(reader)
"""
read_bson(reader::BSONReader) :: Vector{BSON}
Reads all BSON documents from a `reader`.
"""
function read_bson(reader::AbstractBSONReader) :: Vector{BSON}
result = Vector{BSON}()
for bson in reader
push!(result, bson)
end
return result
end
"""
read_bson_from_json(filepath::AbstractString) :: Vector{BSON}
Reads a JSON file into a list of BSON documents.
The file should contain a sequence of valid JSON documents.
# Example of a valid JSON file
```json
{ "num" : 1, "str" : "two" }
{ "num" : 2, "str" : "three" }
```
"""
function read_bson_from_json(filepath::AbstractString) :: Vector{BSON}
reader = BSONJSONReader(filepath)
try
return read_bson(reader)
finally
destroy!(reader)
end
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 39995 |
#
# libbson
#
function bson_oid_init(oid_ref::Ref{BSONObjectId}, context::Ptr{Cvoid})
ccall((:bson_oid_init, libbson), Cvoid, (Ref{BSONObjectId}, Ptr{Cvoid}), oid_ref, context)
end
function bson_oid_init_from_string(oid_ref::Ref{BSONObjectId}, oid_string::AbstractString)
ccall((:bson_oid_init_from_string, libbson), Cvoid,
(Ref{BSONObjectId}, Cstring),
oid_ref, oid_string)
end
function bson_oid_to_string(oid::BSONObjectId) :: String
buffer_len = 25
buffer = zeros(UInt8, buffer_len)
ccall((:bson_oid_to_string, libbson), Cvoid,
(Ref{BSONObjectId}, Ref{UInt8}),
Ref(oid), Ref(buffer, 1))
@assert buffer[end] == 0
return String(buffer[1:end-1])
end
function bson_oid_compare(oid1::BSONObjectId, oid2::BSONObjectId)
ccall((:bson_oid_compare, libbson), Cint,
(Ref{BSONObjectId}, Ref{BSONObjectId}),
Ref(oid1), Ref(oid2))
end
function bson_oid_get_time_t(oid::BSONObjectId)
ccall((:bson_oid_get_time_t, libbson), Clong, (Ref{BSONObjectId},), Ref(oid))
end
function bson_oid_is_valid(str::String)
str_length = Csize_t(length(str))
ccall((:bson_oid_is_valid, libbson), Bool, (Cstring, Csize_t), str, str_length)
end
function bson_append_oid(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::BSONObjectId)
ccall((:bson_append_oid, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Ref{BSONObjectId}),
bson_document, key, key_length, value)
end
function bson_append_int32(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Int32)
ccall((:bson_append_int32, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Cint),
bson_document, key, key_length, value)
end
function bson_append_int64(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Int64)
ccall((:bson_append_int64, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Clonglong),
bson_document, key, key_length, value)
end
function bson_append_utf8(bson_document::Ptr{Cvoid},
key::AbstractString, key_length::Int, value::AbstractString, len::Int)
ccall((:bson_append_utf8, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Cstring, Cint),
bson_document, key, key_length, value, len)
end
function bson_append_bool(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Bool)
ccall((:bson_append_bool, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Bool),
bson_document, key, key_length, value)
end
function bson_append_double(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Float64)
ccall((:bson_append_double, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Cdouble),
bson_document, key, key_length, value)
end
function bson_append_decimal128(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Dec128)
ccall((:bson_append_decimal128, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Ref{Dec128}),
bson_document, key, key_length, Ref(value))
end
function bson_append_date_time(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Int64)
ccall((:bson_append_date_time, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Clonglong),
bson_document, key, key_length, value)
end
function bson_append_document(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Ptr{Cvoid})
ccall((:bson_append_document, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Ptr{Cvoid}),
bson_document, key, key_length, value)
end
function bson_append_array(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::Ptr{Cvoid})
ccall((:bson_append_array, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Ptr{Cvoid}),
bson_document, key, key_length, value)
end
function bson_append_binary(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int,
subtype::BSONSubType, value::Vector{UInt8}, val_length::UInt32)
ccall((:bson_append_binary, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, BSONSubType, Ptr{Cvoid}, Culong),
bson_document, key, key_length, subtype, value, val_length)
end
function bson_append_code(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int, value::String)
ccall((:bson_append_code, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint, Cstring),
bson_document, key, key_length, value)
end
function bson_append_null(bson_document::Ptr{Cvoid}, key::AbstractString, key_length::Int)
ccall((:bson_append_null, libbson), Bool,
(Ptr{Cvoid}, Cstring, Cint),
bson_document, key, key_length)
end
function bson_new()
ccall((:bson_new, libbson), Ptr{Cvoid}, ())
end
function bson_new_from_json(data::String, len::Int=-1)
ccall((:bson_new_from_json, libbson), Ptr{Cvoid},
(Ptr{UInt8}, Cssize_t, Ptr{Cvoid}),
data, len, C_NULL)
end
function bson_destroy(bson_document::Ptr{Cvoid})
ccall((:bson_destroy, libbson), Cvoid, (Ptr{Cvoid},), bson_document)
end
function bson_as_canonical_extended_json(bson_document::Ptr{Cvoid})
ccall((:bson_as_canonical_extended_json, libbson), Cstring,
(Ptr{Cvoid}, Ptr{Cvoid}),
bson_document, C_NULL)
end
function bson_as_relaxed_extended_json(bson_document::Ptr{Cvoid})
ccall((:bson_as_relaxed_extended_json, libbson), Cstring,
(Ptr{Cvoid}, Ptr{Cvoid}),
bson_document, C_NULL)
end
function bson_copy(bson_document::Ptr{Cvoid})
ccall((:bson_copy, libbson), Ptr{Cvoid}, (Ptr{Cvoid},), bson_document)
end
function bson_has_field(bson_document::Ptr{Cvoid}, key::AbstractString)
ccall((:bson_has_field, libbson), Bool, (Ptr{Cvoid}, Cstring), bson_document, key)
end
function bson_count_keys(bson_document::Ptr{Cvoid})
ccall((:bson_count_keys, libbson), UInt32, (Ptr{Cvoid},), bson_document)
end
function bson_iter_init(iter_ref::Ref{BSONIter}, bson_document::Ptr{Cvoid})
ccall((:bson_iter_init, libbson), Bool, (Ref{BSONIter}, Ptr{Cvoid}), iter_ref, bson_document)
end
function bson_iter_next(iter_ref::Ref{BSONIter})
ccall((:bson_iter_next, libbson), Bool, (Ref{BSONIter},), iter_ref)
end
function bson_iter_find(iter_ref::Ref{BSONIter}, key::AbstractString)
ccall((:bson_iter_find, libbson), Bool, (Ref{BSONIter}, Cstring), iter_ref, key)
end
function bson_iter_init_find(iter_ref::Ref{BSONIter}, bson_document::Ptr{Cvoid}, key::AbstractString)
ccall((:bson_iter_init_find, libbson), Bool,
(Ref{BSONIter}, Ptr{Cvoid}, Cstring),
iter_ref, bson_document, key)
end
function bson_iter_type(iter_ref::Ref{BSONIter})
ccall((:bson_iter_type, libbson), BSONType, (Ref{BSONIter},), iter_ref)
end
function bson_iter_key(iter_ref::Ref{BSONIter})
ccall((:bson_iter_key, libbson), Cstring, (Ref{BSONIter},), iter_ref)
end
function bson_iter_int32(iter_ref::Ref{BSONIter})
ccall((:bson_iter_int32, libbson), Int32, (Ref{BSONIter},), iter_ref)
end
function bson_iter_int64(iter_ref::Ref{BSONIter})
ccall((:bson_iter_int64, libbson), Int64, (Ref{BSONIter},), iter_ref)
end
function bson_iter_utf8(iter_ref::Ref{BSONIter})
ccall((:bson_iter_utf8, libbson), Cstring, (Ref{BSONIter}, Ptr{Cvoid}), iter_ref, C_NULL)
end
function bson_iter_bool(iter_ref::Ref{BSONIter})
ccall((:bson_iter_bool, libbson), Bool, (Ref{BSONIter},), iter_ref)
end
function bson_iter_double(iter_ref::Ref{BSONIter})
ccall((:bson_iter_double, libbson), Float64, (Ref{BSONIter},), iter_ref)
end
function bson_iter_decimal128(iter_ref::Ref{BSONIter})
x = Ref{Dec128}()
success = ccall((:bson_iter_decimal128, libbson), Bool, (Ref{BSONIter}, Ref{Dec128}), iter_ref, x)
success || error("Unexpected data type when iterating decimal128")
x[]
end
function bson_iter_oid(iter_ref::Ref{BSONIter})
ccall((:bson_iter_oid, libbson), Ptr{BSONObjectId}, (Ref{BSONIter},), iter_ref)
end
function bson_iter_date_time(iter_ref::Ref{BSONIter})
ccall((:bson_iter_date_time, libbson), Clonglong, (Ref{BSONIter},), iter_ref)
end
function bson_iter_timestamp(iter_ref::Ref{BSONIter}) :: BSONTimestamp
timestamp = Ref{UInt32}()
increment = Ref{UInt32}()
ccall(
(:bson_iter_timestamp, libbson),
Cvoid,
(Ref{BSONIter}, Ref{UInt32}, Ref{UInt32}),
iter_ref, timestamp, increment
)
return BSONTimestamp(timestamp[], increment[])
end
function bson_iter_recurse(iter_ref::Ref{BSONIter}, child_iter_ref::Ref{BSONIter})
ccall((:bson_iter_recurse, libbson), Bool, (Ref{BSONIter}, Ref{BSONIter}), iter_ref, child_iter_ref)
end
function bson_iter_code(iter_ref::Ref{BSONIter})
ccall((:bson_iter_code, libbson), Cstring, (Ref{BSONIter}, Ptr{UInt32}), iter_ref, C_NULL)
end
function bson_iter_binary(iter_ref::Ref{BSONIter}, length_ref::Ref{UInt32}, buffer_ref::Ref{Ptr{UInt8}})
bsonsubtype_ref = Ref(BSON_SUBTYPE_BINARY)
bson_iter_binary(iter_ref, bsonsubtype_ref, length_ref, buffer_ref)
end
function bson_iter_binary(iter_ref::Ref{BSONIter}, bsonsubtype_ref::Ref{BSONSubType}, length_ref::Ref{UInt32}, buffer_ref::Ref{Ptr{UInt8}})
ccall((:bson_iter_binary, libbson), Cvoid,
(Ref{BSONIter}, Ref{BSONSubType}, Ref{UInt32}, Ref{Ptr{UInt8}}),
iter_ref, bsonsubtype_ref, length_ref, buffer_ref)
end
function bson_iter_value(iter_ref::Ref{BSONIter})
ccall((:bson_iter_value, libbson), Ptr{Cvoid}, (Ref{BSONIter},), iter_ref)
end
function bson_free(mem::Ptr{Cvoid})
ccall((:bson_free, libbson), Cvoid, (Ptr{Cvoid},), mem)
end
function bson_reader_destroy(bson_reader_handle::Ptr{Cvoid})
ccall((:bson_reader_destroy, libbson), Cvoid, (Ptr{Cvoid},), bson_reader_handle)
end
function bson_reader_new_from_file(filepath::AbstractString, bson_error_ref::Ref{BSONError})
ccall((:bson_reader_new_from_file, libbson), Ptr{Cvoid},
(Cstring, Ref{BSONError}),
filepath, bson_error_ref)
end
function bson_reader_new_from_data(data::Ptr{UInt8}, data_length::Integer)
ccall((:bson_reader_new_from_data, libbson), Ptr{Cvoid}, (Ptr{UInt8}, Csize_t), data, data_length)
end
function bson_reader_read(bson_reader_handle::Ptr{Cvoid}, reached_eof_ref::Ref{Bool})
ccall((:bson_reader_read, libbson), Ptr{Cvoid},
(Ptr{Cvoid}, Ref{Bool}),
bson_reader_handle, reached_eof_ref)
end
function bson_writer_destroy(bson_writer_handle::Ptr{Cvoid})
ccall((:bson_writer_destroy, libbson), Cvoid, (Ptr{Cvoid},), bson_writer_handle)
end
function bson_writer_begin(bson_writer_handle::Ptr{Cvoid}, bson_document_handle_ref::Ref{Ptr{Cvoid}})
ccall((:bson_writer_begin, libbson), Bool,
(Ptr{Cvoid}, Ref{Ptr{Cvoid}}),
bson_writer_handle, bson_document_handle_ref)
end
function bson_writer_end(bson_writer_handle::Ptr{Cvoid})
ccall((:bson_writer_end, libbson), Cvoid, (Ptr{Cvoid},), bson_writer_handle)
end
function bson_writer_new(buffer_handle_ref::Ref{Ptr{UInt8}}, buffer_length_ref::Ref{Csize_t},
offset::Csize_t, realloc_func::Ptr{Cvoid}, realloc_func_ctx::Ptr{Cvoid})
ccall((:bson_writer_new, libbson), Ptr{Cvoid},
(Ref{Ptr{UInt8}}, Ref{Csize_t}, Csize_t, Ptr{Cvoid}, Ptr{Cvoid}),
buffer_handle_ref, buffer_length_ref, offset, realloc_func, realloc_func_ctx)
end
function bson_writer_get_length(bson_writer_handle::Ptr{Cvoid})
ccall((:bson_writer_get_length, libbson), Csize_t, (Ptr{Cvoid},), bson_writer_handle)
end
function bson_copy_to(src_bson_handle::Ptr{Cvoid}, dst_bson_handle::Ptr{Cvoid})
ccall((:bson_copy_to, libbson), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}), src_bson_handle, dst_bson_handle)
end
function bson_copy_to_noinit(src_bson_handle::Ptr{Cvoid}, dst_bson_handle::Ptr{Cvoid})
# This hack will create a key that is not present in src_bson
# since bson_copy_to_excluding_noinit requires at least one `exclude` arg.
# This is needed because there's no `bson_copy_to_noinit` in libbson.
function exclude_key(bson_handle::Ptr{Cvoid})
new_exclude_key() = "___" * string(Int(rand(UInt16)))
exclude = new_exclude_key()
bson = BSON(bson_handle, enable_finalizer=false) # disable finalizer
while haskey(bson, exclude)
exclude = new_exclude_key()
end
return exclude
end
exclude = exclude_key(src_bson_handle)
bson_copy_to_excluding_noinit(src_bson_handle, dst_bson_handle, exclude)
end
function bson_copy_to_excluding_noinit(src_bson_handle::Ptr{Cvoid}, dst_bson_handle::Ptr{Cvoid},
exclude::AbstractString)
@ccall libbson.bson_copy_to_excluding_noinit(src_bson_handle::Ptr{Cvoid},
dst_bson_handle::Ptr{Cvoid},
exclude::Cstring;
C_NULL::Cstring)::Cvoid
end
function bson_json_reader_new_from_file(filepath::AbstractString, bson_error_ref::Ref{BSONError})
ccall((:bson_json_reader_new_from_file, libbson), Ptr{Cvoid},
(Cstring, Ref{BSONError}),
filepath, bson_error_ref
)
end
function bson_json_reader_destroy(reader_handle::Ptr{Cvoid})
ccall((:bson_json_reader_destroy, libbson), Cvoid,
(Ptr{Cvoid},),
reader_handle)
end
function bson_json_reader_read(reader_handle::Ptr{Cvoid}, bson_handle::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:bson_json_reader_read, libbson), Cint,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
reader_handle, bson_handle, bson_error_ref)
end
#
# libmongoc
#
function mongoc_init()
ccall((:mongoc_init, libmongoc), Cvoid, ())
end
function mongoc_cleanup()
ccall((:mongoc_cleanup, libmongoc), Cvoid, ())
end
function mongoc_uri_new_with_error(uri_string::String, bson_error_ref::Ref{BSONError})
ccall((:mongoc_uri_new_with_error, libmongoc), Ptr{Cvoid},
(Cstring, Ref{BSONError}),
uri_string, bson_error_ref)
end
function mongoc_uri_destroy(uri_handle::Ptr{Cvoid})
ccall((:mongoc_uri_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), uri_handle)
end
function mongoc_client_new_from_uri(uri_handle::Ptr{Cvoid})
ccall((:mongoc_client_new_from_uri, libmongoc), Ptr{Cvoid}, (Ptr{Cvoid},), uri_handle)
end
function mongoc_client_destroy(client_handle::Ptr{Cvoid})
ccall((:mongoc_client_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), client_handle)
end
function mongoc_client_set_appname(client_handle::Ptr{Cvoid}, appname::String)
ccall((:mongoc_client_set_appname, libmongoc), Bool, (Ptr{Cvoid}, Cstring), client_handle, appname)
end
function mongoc_client_get_database(client_handle::Ptr{Cvoid}, db_name::String)
ccall((:mongoc_client_get_database, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Cstring),
client_handle, db_name)
end
function mongoc_client_find_databases_with_opts(client_handle::Ptr{Cvoid}, bson_opts::Ptr{Cvoid})
ccall((:mongoc_client_find_databases_with_opts, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}),
client_handle, bson_opts)
end
function mongoc_client_start_session(client_handle::Ptr{Cvoid}, session_options_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_client_start_session, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
client_handle, session_options_handle, bson_error_ref)
end
function mongoc_client_session_destroy(session_handle::Ptr{Cvoid})
ccall((:mongoc_client_session_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), session_handle)
end
function mongoc_client_session_append(session_handle::Ptr{Cvoid}, bson_opts::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_client_session_append, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
session_handle, bson_opts, bson_error_ref)
end
function mongoc_client_session_start_transaction(session_handle::Ptr{Cvoid},
transaction_options_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_client_session_start_transaction, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
session_handle, transaction_options_handle, bson_error_ref)
end
function mongoc_client_session_abort_transaction(session_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_client_session_abort_transaction, libmongoc), Bool,
(Ptr{Cvoid}, Ref{BSONError}),
session_handle, bson_error_ref)
end
function mongoc_client_session_commit_transaction(session_handle::Ptr{Cvoid}, bson_reply::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_client_session_commit_transaction, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
session_handle, bson_reply, bson_error_ref)
end
function mongoc_client_session_in_transaction(session_handle::Ptr{Cvoid})
ccall((:mongoc_client_session_in_transaction, libmongoc), Bool, (Ptr{Cvoid},), session_handle)
end
function mongoc_client_pool_new(uri_handle::Ptr{Cvoid})
ccall((:mongoc_client_pool_new, libmongoc), Ptr{Cvoid}, (Ptr{Cvoid},), uri_handle)
end
function mongoc_client_pool_destroy(client_pool_handle::Ptr{Cvoid})
ccall((:mongoc_client_pool_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), client_pool_handle)
end
function mongoc_client_pool_pop(client_pool_handle::Ptr{Cvoid})
ccall((:mongoc_client_pool_pop, libmongoc), Ptr{Cvoid}, (Ptr{Cvoid},), client_pool_handle)
end
function mongoc_client_pool_try_pop(client_pool_handle::Ptr{Cvoid})
ccall((:mongoc_client_pool_try_pop, libmongoc), Ptr{Cvoid}, (Ptr{Cvoid},), client_pool_handle)
end
function mongoc_client_pool_push(client_pool_handle::Ptr{Cvoid}, client_handle::Ptr{Cvoid})
ccall((:mongoc_client_pool_push, libmongoc), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}), client_pool_handle, client_handle)
end
function mongoc_client_pool_max_size(client_pool_handle::Ptr{Cvoid}, max_pool_size::UInt32)
ccall((:mongoc_client_pool_max_size, libmongoc), Cvoid, (Ptr{Cvoid}, UInt32), client_pool_handle, max_pool_size)
end
function mongoc_session_opts_new()
ccall((:mongoc_session_opts_new, libmongoc), Ptr{Cvoid}, ())
end
function mongoc_session_opts_destroy(session_options_handle::Ptr{Cvoid})
ccall((:mongoc_session_opts_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), session_options_handle)
end
function mongoc_session_opts_get_causal_consistency(session_options_handle::Ptr{Cvoid})
ccall((:mongoc_session_opts_get_causal_consistency, libmongoc), Bool,
(Ptr{Cvoid},),
session_options_handle)
end
function mongoc_session_opts_set_causal_consistency(session_options_handle::Ptr{Cvoid},
casual_consistency::Bool)
ccall((:mongoc_session_opts_set_causal_consistency, libmongoc), Cvoid,
(Ptr{Cvoid}, Bool),
session_options_handle, casual_consistency)
end
function mongoc_database_destroy(database_handle::Ptr{Cvoid})
ccall((:mongoc_database_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), database_handle)
end
function mongoc_database_get_collection(database_handle::Ptr{Cvoid}, collection_name::String)
ccall((:mongoc_database_get_collection, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Cstring),
database_handle, collection_name)
end
function mongoc_database_find_collections_with_opts(database_handle::Ptr{Cvoid}, bson_opts::Ptr{Cvoid})
ccall((:mongoc_database_find_collections_with_opts, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}),
database_handle, bson_opts)
end
function mongoc_database_command_simple(database_handle::Ptr{Cvoid}, bson_command::Ptr{Cvoid},
read_prefs::Ptr{Cvoid}, bson_reply::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_database_command_simple, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
database_handle, bson_command, read_prefs, bson_reply, bson_error_ref)
end
function mongoc_database_write_command_with_opts(database_handle::Ptr{Cvoid}, bson_command::Ptr{Cvoid},
bson_opts_handle::Ptr{Cvoid},
bson_reply_ref::Ref{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_database_write_command_with_opts, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{Cvoid}, Ref{BSONError}),
database_handle, bson_command, bson_opts_handle, bson_reply_ref, bson_error_ref)
end
function mongoc_database_read_command_with_opts(database_handle::Ptr{Cvoid}, bson_command::Ptr{Cvoid},
read_prefs_handle::Ptr{Cvoid}, bson_opts_handle::Ptr{Cvoid},
bson_reply_ref::Ref{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_database_read_command_with_opts, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{Cvoid}, Ref{BSONError}),
database_handle, bson_command, read_prefs_handle, bson_opts_handle, bson_reply_ref, bson_error_ref)
end
function mongoc_database_add_user(database_handle::Ptr{Cvoid}, username::String, password::String,
bson_roles::Ptr{Cvoid}, bson_custom_data::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_database_add_user, libmongoc), Bool,
(Ptr{Cvoid}, Cstring, Cstring, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
database_handle, username, password, bson_roles, bson_custom_data, bson_error_ref)
end
function mongoc_database_remove_user(database_handle::Ptr{Cvoid}, username::String,
bson_error_ref::Ref{BSONError})
ccall((:mongoc_database_remove_user, libmongoc), Bool,
(Ptr{Cvoid}, Cstring, Ref{BSONError}),
database_handle, username, bson_error_ref)
end
function mongoc_database_drop_with_opts(database_handle::Ptr{Cvoid},
opts_handle::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_database_drop_with_opts, libmongoc),
Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
database_handle, opts_handle, bson_error_ref
)
end
function mongoc_collection_command_simple(collection_handle::Ptr{Cvoid}, bson_command::Ptr{Cvoid},
read_prefs::Ptr{Cvoid}, bson_reply::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_command_simple, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_command, read_prefs, bson_reply, bson_error_ref)
end
function mongoc_collection_read_command_with_opts(collection_handle::Ptr{Cvoid}, bson_command::Ptr{Cvoid},
read_prefs::Ptr{Cvoid}, bson_opts_handle::Ptr{Cvoid},
bson_reply::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_command_simple, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_command, read_prefs, bson_opts_handle, bson_reply, bson_error_ref)
end
function mongoc_collection_destroy(collection_handle::Ptr{Cvoid})
ccall((:mongoc_collection_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), collection_handle)
end
function mongoc_collection_insert_one(collection_handle::Ptr{Cvoid}, bson_document::Ptr{Cvoid},
bson_options::Ptr{Cvoid}, bson_reply::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_insert_one, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_document, bson_options, bson_reply, bson_error_ref)
end
function mongoc_collection_find_with_opts(collection_handle::Ptr{Cvoid}, bson_filter::Ptr{Cvoid},
bson_opts::Ptr{Cvoid}, read_prefs::Ptr{Cvoid})
ccall((:mongoc_collection_find_with_opts, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}),
collection_handle, bson_filter, bson_opts, read_prefs)
end
function mongoc_collection_count_documents(collection_handle::Ptr{Cvoid}, bson_filter::Ptr{Cvoid},
bson_opts::Ptr{Cvoid}, read_prefs::Ptr{Cvoid},
bson_reply::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_count_documents, libmongoc), Int64,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_filter, bson_opts, read_prefs, bson_reply, bson_error_ref)
end
function mongoc_collection_create_bulk_operation_with_opts(collection_handle::Ptr{Cvoid},
bson_opts::Ptr{Cvoid})
ccall((:mongoc_collection_create_bulk_operation_with_opts, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}),
collection_handle, bson_opts)
end
function mongoc_collection_delete_one(collection_handle::Ptr{Cvoid}, bson_selector::Ptr{Cvoid},
bson_opts::Ptr{Cvoid}, bson_reply::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_delete_one, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_selector, bson_opts, bson_reply, bson_error_ref)
end
function mongoc_collection_delete_many(collection_handle::Ptr{Cvoid}, bson_selector::Ptr{Cvoid},
bson_opts::Ptr{Cvoid}, bson_reply::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_delete_many, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_selector, bson_opts, bson_reply, bson_error_ref)
end
function mongoc_collection_update_one(collection_handle::Ptr{Cvoid}, bson_selector::Ptr{Cvoid},
bson_update::Ptr{Cvoid}, bson_opts::Ptr{Cvoid},
bson_reply::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_update_one, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_selector, bson_update, bson_opts, bson_reply, bson_error_ref)
end
function mongoc_collection_update_many(collection_handle::Ptr{Cvoid}, bson_selector::Ptr{Cvoid},
bson_update::Ptr{Cvoid}, bson_opts::Ptr{Cvoid},
bson_reply::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_update_many, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_selector, bson_update, bson_opts, bson_reply, bson_error_ref)
end
function mongoc_collection_replace_one(collection_handle::Ptr{Cvoid}, bson_selector::Ptr{Cvoid},
bson_replacement::Ptr{Cvoid}, bson_opts::Ptr{Cvoid},
bson_reply::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_replace_one, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_selector, bson_replacement, bson_opts, bson_reply, bson_error_ref)
end
function mongoc_collection_aggregate(collection_handle::Ptr{Cvoid}, flags::QueryFlags,
bson_pipeline::Ptr{Cvoid}, bson_opts::Ptr{Cvoid},
read_prefs::Ptr{Cvoid})
ccall((:mongoc_collection_aggregate, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Cint, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}),
collection_handle, flags, bson_pipeline, bson_opts, read_prefs)
end
function mongoc_cursor_destroy(cursor_handle::Ptr{Cvoid})
ccall((:mongoc_cursor_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), cursor_handle)
end
function mongoc_cursor_next(cursor_handle::Ptr{Cvoid}, bson_document_ref::Ref{Ptr{Cvoid}})
ccall((:mongoc_cursor_next, libmongoc), Bool,
(Ptr{Cvoid}, Ref{Ptr{Cvoid}}),
cursor_handle, bson_document_ref)
end
function mongoc_cursor_set_limit(cursor_handle::Ptr{Cvoid}, limit::Int)
ccall((:mongoc_cursor_set_limit, libmongoc), Bool, (Ptr{Cvoid}, Int64), cursor_handle, limit)
end
function mongoc_cursor_get_batch_size(cursor_handle::Ptr{Cvoid})
ccall((:mongoc_cursor_get_batch_size, libmongoc), UInt32, (Ptr{Cvoid},), cursor_handle)
end
function mongoc_cursor_set_batch_size(cursor_handle::Ptr{Cvoid}, batch_size::Integer)
ccall(
(:mongoc_cursor_set_batch_size, libmongoc),
Cvoid,
(Ptr{Cvoid}, UInt32,),
cursor_handle, UInt32(batch_size)
)
end
function mongoc_cursor_error(cursor_handle::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_cursor_error, libmongoc), Bool,
(Ptr{Cvoid}, Ref{BSONError}),
cursor_handle, bson_error_ref)
end
function mongoc_bulk_operation_destroy(bulk_operation_handle::Ptr{Cvoid})
ccall((:mongoc_bulk_operation_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), bulk_operation_handle)
end
function mongoc_bulk_operation_insert_with_opts(bulk_operation_handle::Ptr{Cvoid},
bson_document::Ptr{Cvoid},
bson_options::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_bulk_operation_insert_with_opts, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bulk_operation_handle, bson_document, bson_options, bson_error_ref)
end
function mongoc_bulk_operation_replace_one_with_opts(bulk_operation_handle::Ptr{Cvoid},
bson_selector::Ptr{Cvoid},
bson_replacement::Ptr{Cvoid},
bson_options::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_bulk_operation_replace_one_with_opts, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bulk_operation_handle, bson_selector, bson_replacement, bson_options, bson_error_ref)
end
function mongoc_bulk_operation_update_one_with_opts(
bulk_operation_handle::Ptr{Cvoid},
bson_selector::Ptr{Cvoid},
bson_document::Ptr{Cvoid},
bson_options::Ptr{Cvoid},
bson_error_ref::Ref{BSONError}
)
ccall(
(:mongoc_bulk_operation_update_one_with_opts, libmongoc),
Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bulk_operation_handle, bson_selector, bson_document, bson_options, bson_error_ref
)
end
function mongoc_bulk_operation_execute(bulk_operation_handle::Ptr{Cvoid}, bson_reply::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_bulk_operation_execute, libmongoc), UInt32,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bulk_operation_handle, bson_reply, bson_error_ref)
end
function mongoc_collection_drop_with_opts(collection_handle::Ptr{Cvoid},
bson_opts_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_drop_with_opts, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, bson_opts_handle, bson_error_ref)
end
function mongoc_find_and_modify_opts_new()
ccall((:mongoc_find_and_modify_opts_new, libmongoc),
Ptr{Cvoid},
())
end
function mongoc_find_and_modify_opts_destroy(handle::Ptr{Cvoid})
ccall((:mongoc_find_and_modify_opts_destroy, libmongoc),
Cvoid,
(Ptr{Cvoid},),
handle)
end
function mongoc_find_and_modify_opts_set_update(opts_handle::Ptr{Cvoid},
bson_handle::Ptr{Cvoid})
ccall((:mongoc_find_and_modify_opts_set_update, libmongoc),
Bool,
(Ptr{Cvoid}, Ptr{Cvoid}),
opts_handle, bson_handle)
end
function mongoc_find_and_modify_opts_set_sort(opts_handle::Ptr{Cvoid},
bson_handle::Ptr{Cvoid})
ccall((:mongoc_find_and_modify_opts_set_sort, libmongoc),
Bool,
(Ptr{Cvoid}, Ptr{Cvoid}),
opts_handle, bson_handle)
end
function mongoc_find_and_modify_opts_set_fields(opts_handle::Ptr{Cvoid},
bson_handle::Ptr{Cvoid})
ccall((:mongoc_find_and_modify_opts_set_fields, libmongoc),
Bool,
(Ptr{Cvoid}, Ptr{Cvoid}),
opts_handle, bson_handle)
end
function mongoc_find_and_modify_opts_set_flags(opts_handle::Ptr{Cvoid},
flags::FindAndModifyFlags)
ccall((:mongoc_find_and_modify_opts_set_flags, libmongoc),
Bool,
(Ptr{Cvoid}, FindAndModifyFlags),
opts_handle, flags)
end
function mongoc_find_and_modify_opts_set_bypass_document_validation(
opts_handle::Ptr{Cvoid}, bypass::Bool)
ccall((:mongoc_find_and_modify_opts_set_bypass_document_validation, libmongoc),
Bool,
(Ptr{Cvoid}, Bool),
opts_handle, bypass)
end
function mongoc_collection_find_and_modify_with_opts(collection_handle::Ptr{Cvoid},
query_bson_handle::Ptr{Cvoid}, opts_handle::Ptr{Cvoid},
result_bson_handle::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_collection_find_and_modify_with_opts, libmongoc),
Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
collection_handle, query_bson_handle,
opts_handle, result_bson_handle, bson_error_ref)
end
function mongoc_gridfs_bucket_new(database_handle::Ptr{Cvoid}, bson_opts_handle::Ptr{Cvoid},
read_prefs::Ptr{Cvoid}, bson_error_ref::Ref{BSONError})
ccall((:mongoc_gridfs_bucket_new, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
database_handle, bson_opts_handle, read_prefs, bson_error_ref)
end
function mongoc_gridfs_bucket_destroy(bucket_handle::Ptr{Cvoid})
ccall((:mongoc_gridfs_bucket_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), bucket_handle)
end
function mongoc_stream_destroy(stream_handle::Ptr{Cvoid})
ccall((:mongoc_stream_destroy, libmongoc), Cvoid, (Ptr{Cvoid},), stream_handle)
end
function mongoc_stream_flush(stream_handle::Ptr{Cvoid})
ccall((:mongoc_stream_flush, libmongoc), Cint, (Ptr{Cvoid},), stream_handle)
end
function mongoc_stream_close(stream_handle::Ptr{Cvoid})
ccall((:mongoc_stream_close, libmongoc), Cint, (Ptr{Cvoid},), stream_handle)
end
function mongoc_stream_file_new_for_path(path::AbstractString, flags::Integer, mode::Integer)
ccall((:mongoc_stream_file_new_for_path, libmongoc), Ptr{Cvoid},
(Cstring, Cint, Cint),
path, flags, mode)
end
function mongoc_stream_read(
stream_handle::Ptr{Cvoid},
buffer_handle::Ptr{UInt8},
count::Integer,
min_bytes::Integer,
timeout_msec::Integer)
ccall((:mongoc_stream_read, libmongoc), Csize_t,
(Ptr{Cvoid}, Ptr{UInt8}, Csize_t, Csize_t, Cint),
stream_handle, buffer_handle, count, min_bytes, timeout_msec)
end
function mongoc_stream_write(
stream_handle::Ptr{Cvoid},
buffer_handle::Ptr{UInt8},
count::Integer,
timeout_msec::Integer)
ccall((:mongoc_stream_write, libmongoc), Csize_t,
(Ptr{Cvoid}, Ptr{UInt8}, Csize_t, Cint),
stream_handle, buffer_handle, count, timeout_msec)
end
function mongoc_gridfs_bucket_upload_from_stream_with_id(
bucket_handle::Ptr{Cvoid},
bson_value_file_id_handle::Ptr{Cvoid},
filename::AbstractString,
source_stream_handle::Ptr{Cvoid},
bson_opts_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError}
)
ccall((:mongoc_gridfs_bucket_upload_from_stream_with_id, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Cstring, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bucket_handle, bson_value_file_id_handle, filename, source_stream_handle,
bson_opts_handle, bson_error_ref)
end
function mongoc_gridfs_bucket_download_to_stream(
bucket_handle::Ptr{Cvoid},
bson_value_file_id_handle::Ptr{Cvoid},
destination_stream_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError}
)
ccall((:mongoc_gridfs_bucket_download_to_stream, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bucket_handle, bson_value_file_id_handle, destination_stream_handle, bson_error_ref)
end
function mongoc_gridfs_bucket_open_download_stream(
bucket_handle::Ptr{Cvoid},
bson_value_file_id_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError}
)
ccall((:mongoc_gridfs_bucket_open_download_stream, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bucket_handle, bson_value_file_id_handle, bson_error_ref)
end
function mongoc_gridfs_bucket_open_upload_stream_with_id(
bucket_handle::Ptr{Cvoid},
bson_value_file_id_handle::Ptr{Cvoid},
filename::AbstractString,
bson_opts_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_gridfs_bucket_open_upload_stream_with_id, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}, Cstring, Ptr{Cvoid}, Ref{BSONError}),
bucket_handle, bson_value_file_id_handle, filename,
bson_opts_handle, bson_error_ref)
end
function mongoc_gridfs_bucket_abort_upload(stream_handle::Ptr{Cvoid})
ccall((:mongoc_gridfs_bucket_abort_upload, libmongoc), Bool,
(Ptr{Cvoid},), stream_handle)
end
function mongoc_gridfs_bucket_find(
bucket_handle::Ptr{Cvoid},
bson_filter_handle::Ptr{Cvoid},
bson_opts_handle::Ptr{Cvoid})
ccall((:mongoc_gridfs_bucket_find, libmongoc), Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}),
bucket_handle, bson_filter_handle, bson_opts_handle)
end
function mongoc_gridfs_bucket_delete_by_id(
bucket_handle::Ptr{Cvoid},
bson_value_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError})
ccall((:mongoc_gridfs_bucket_delete_by_id, libmongoc), Bool,
(Ptr{Cvoid}, Ptr{Cvoid}, Ref{BSONError}),
bucket_handle, bson_value_handle, bson_error_ref)
end
function mongoc_gridfs_bucket_stream_error(
stream_handle::Ptr{Cvoid},
bson_error_ref::Ref{BSONError}
)
ccall((:mongoc_gridfs_bucket_stream_error, libmongoc), Bool,
(Ptr{Cvoid}, Ref{BSONError}),
stream_handle, bson_error_ref)
end
function mongoc_set_log_handler(
cfunction::Ptr{Cvoid},
userdata::Ptr{Cvoid} = C_NULL
)
ccall(
(:mongoc_log_set_handler, libmongoc), Cvoid,
(Ptr{Cvoid}, Ptr{Cvoid}),
cfunction, userdata)
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 3746 |
Base.show(io::IO, uri::URI) = print(io, "URI(\"", uri.uri, "\")")
Base.show(io::IO, client::Client) = print(io, "Client(URI(\"", client.uri, "\"))")
Base.getindex(client::Client, database::String) = Database(client, database)
"""
Client(host, port)
Client(uri)
Client()
Client(pool; [try_pop=false])
Creates a `Client`, which represents a connection to a MongoDB database.
See also [`Mongoc.ClientPool`](@ref).
# Examples:
These lines are equivalent.
```julia
c = Mongoc.Client()
c = Mongoc.Client("localhost", 27017)
c = Mongoc.Client("mongodb://localhost:27017")
```
"""
Client(host::String, port::Int) = Client(URI("mongodb://$host:$port"))
Client(uri::String) = Client(URI(uri))
Client() = Client("localhost", 27017)
"""
set_appname!(client::Client, appname::String)
Sets the application name for this client.
This string, along with other internal driver details,
is sent to the server as part of the initial connection handshake.
# C API
* [`mongoc_client_set_appname`](http://mongoc.org/libmongoc/current/mongoc_client_set_appname.html).
"""
function set_appname!(client::Client, appname::String)
ok = mongoc_client_set_appname(client.handle, appname)
if !ok
error("Couldn't set appname=$appname for client $client.")
end
nothing
end
"""
ping(client::Client) :: BSON
Pings the server, testing wether it is reachable.
One thing to keep in mind is that operations on MongoDB are *lazy*,
which means that a client reaches a server only when it needs to
transfer documents.
# Example
```julia
julia> client = Mongoc.Client() # nothing happens here between client and server
Client(URI("mongodb://localhost:27017"))
julia> Mongoc.ping(client) # connection to server happens here
BSON("{ "ok" : 1.0 }")
```
"""
function ping(client::Client) :: BSON
return command_simple(client["admin"], BSON("""{ "ping" : 1 }"""))
end
"""
get_server_mongodb_version(client::Client) :: VersionNumber
Queries the version for the MongoDB server instance.
"""
function get_server_mongodb_version(client::Client) :: VersionNumber
bson_server_status = command_simple(client["admin"], BSON("""{ "serverStatus" : 1 }"""))
return VersionNumber(bson_server_status["version"])
end
"""
find_databases(client::Client; options::Union{Nothing, BSON}=nothing) :: Cursor
Queries for databases.
"""
function find_databases(client::Client; options::Union{Nothing, BSON}=nothing) :: Cursor
options_handle = options == nothing ? C_NULL : options.handle
cursor_handle = mongoc_client_find_databases_with_opts(client.handle, options_handle)
if cursor_handle == C_NULL
error("Couldn't execute query.")
end
return Cursor(client, cursor_handle)
end
"""
get_database_names(client::Client; options::Union{Nothing, BSON}=nothing) :: Vector{String}
Helper method to get a list of names for all databases.
See also [`Mongoc.find_databases`](@ref).
"""
function get_database_names(client::Client; options::Union{Nothing, BSON}=nothing) :: Vector{String}
result = Vector{String}()
for bson_database in find_databases(client, options=options)
push!(result, bson_database["name"])
end
return result
end
"""
has_database(client::Client, database_name::String;
options::Union{Nothing, BSON}=nothing) :: Bool
Helper method to check if there is a database named `database_name`.
See also [`Mongoc.find_databases`](@ref).
"""
function has_database(client::Client, database_name::String;
options::Union{Nothing, BSON}=nothing) :: Bool
for bson_database in find_databases(client, options=options)
if bson_database["name"] == database_name
return true
end
end
return false
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 1242 |
"""
ClientPool(uri; [max_size])
Creates a pool of connections to a MongoDB instance.
# Example
```julia
const REPLICA_SET_URL = "mongodb://127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023/?replicaSet=rs0"
pool = Mongoc.ClientPool(REPLICA_SET_URL, max_size=2)
# create Clients from a pool
client1 = Mongoc.Client(pool)
client2 = Mongoc.Client(pool)
```
When you reach the maximum number of clients,
the next call to `Mongoc.Client(pool)` will block
until a `Client` is released.
Use `try_pop=true` option to throw an error instead
of blocking the current thread:
```julia
# will throw `AssertionError`
client3 = Mongoc.Client(pool, try_pop=true)
```
"""
function ClientPool(uri::String; max_size::Union{Nothing, Integer}=nothing)
return ClientPool(URI(uri), max_size=max_size)
end
"""
set_max_size(pool, max_size)
Set the maximum number of clients on the client pool.
# Example
```julia
const REPLICA_SET_URL = "mongodb://127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023/?replicaSet=rs0"
pool = Mongoc.ClientPool(REPLICA_SET_URL)
Mongoc.set_max_size(pool, 4)
```
"""
function set_max_size(client_pool::ClientPool, max_size::Integer)
mongoc_client_pool_max_size(client_pool.handle, UInt32(max_size))
nothing
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 23143 |
Base.show(io::IO, coll::Collection) = print(io, "Collection($(coll.database), \"", coll.name, "\")")
# docstring for this function is at database.jl
function command_simple(collection::Collection, command::BSON) :: BSON
reply = BSON()
err_ref = Ref{BSONError}()
ok = mongoc_collection_command_simple(collection.handle, command.handle, C_NULL, reply.handle,
err_ref)
if !ok
throw(err_ref[])
end
return reply
end
function read_command(collection::Collection, command::BSON;
options::Union{Nothing, BSON}=nothing) :: BSON
reply = BSON()
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_collection_read_command_with_opts(collection.handle,
command.handle, C_NULL, options_handle, reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
# Aux function to add _id field to document if it does not exist.
# If `_id_` is not present, creates a copy of `document`.
# This function returns `document, inserted_oid`.
function _new_id(document::BSON)
if haskey(document, "_id")
return document, nothing
else
inserted_oid = BSONObjectId()
# copies it so this function doesn't have side effects
document = deepcopy(document)
document["_id"] = inserted_oid
return document, inserted_oid
end
end
function insert_one(collection::Collection, document::BSON;
options::Union{Nothing, BSON}=nothing) :: InsertOneResult
document, inserted_oid = _new_id(document)
reply = BSON()
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_collection_insert_one(collection.handle, document.handle, options_handle,
reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return InsertOneResult(reply, inserted_oid)
end
function delete_one(collection::Collection, selector::BSON; options::Union{Nothing, BSON}=nothing)
reply = BSON()
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_collection_delete_one(collection.handle, selector.handle, options_handle,
reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
function delete_many(collection::Collection, selector::BSON; options::Union{Nothing, BSON}=nothing)
reply = BSON()
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_collection_delete_many(collection.handle, selector.handle, options_handle,
reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
function update_one(collection::Collection, selector::BSON, update::BSON;
options::Union{Nothing, BSON}=nothing)
reply = BSON()
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_collection_update_one(collection.handle, selector.handle, update.handle,
options_handle, reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
function update_many(collection::Collection, selector::BSON, update::BSON;
options::Union{Nothing, BSON}=nothing)
reply = BSON()
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_collection_update_many(collection.handle, selector.handle, update.handle,
options_handle, reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
"""
replace_one(
collection::Collection,
selector::BSON,
replacement::BSON;
options::Union{Nothing, BSON}=nothing
)
Replace the result of querying by `selector` with `replacement`.
"""
function replace_one(
collection::Collection,
selector::BSON,
replacement::BSON;
options::Union{Nothing, BSON}=nothing
)
reply = BSON()
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_collection_replace_one(collection.handle, selector.handle, replacement.handle,
options_handle, reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
function BulkOperationResult(reply::BSON, server_id::UInt32)
BulkOperationResult(reply, server_id, Vector{Union{Nothing, BSONObjectId}}())
end
function execute!(bulk_operation::BulkOperation) :: BulkOperationResult
if bulk_operation.executed
error("Bulk operation was already executed.")
end
try
reply = BSON()
err_ref = Ref{BSONError}()
bulk_operation_result = mongoc_bulk_operation_execute(bulk_operation.handle,
reply.handle, err_ref)
if bulk_operation_result == 0
throw(err_ref[])
end
return BulkOperationResult(reply, bulk_operation_result)
finally
destroy!(bulk_operation)
end
end
function bulk_insert!(bulk_operation::BulkOperation, document::BSON;
options::Union{Nothing, BSON}=nothing)
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_bulk_operation_insert_with_opts(bulk_operation.handle, document.handle,
options_handle, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
function bulk_replace_one!(bulk_operation::BulkOperation, selector::BSON, replacement::BSON;
options::Union{Nothing, BSON}=nothing)
err_ref = Ref{BSONError}()
options_handle = options === nothing ? C_NULL : options.handle
ok = mongoc_bulk_operation_replace_one_with_opts(
bulk_operation.handle,
selector.handle,
replacement.handle,
options_handle,
err_ref
)
if !ok
throw(err_ref[])
end
nothing
end
function bulk_update_one!(
bulk_operation::BulkOperation, selector::BSON, document::BSON;
options::Union{Nothing, BSON} = nothing
)
err_ref = Ref{BSONError}()
options_handle = options === nothing ? C_NULL : options.handle
ok = mongoc_bulk_operation_update_one_with_opts(
bulk_operation.handle,
selector.handle,
document.handle,
options_handle,
err_ref
)
if !ok
throw(err_ref[])
end
nothing
end
function insert_many(collection::Collection, documents::Vector{BSON};
bulk_options::Union{Nothing, BSON}=nothing, insert_options::Union{Nothing, BSON}=nothing)
inserted_oids = Vector{Union{Nothing, BSONObjectId}}()
bulk_operation = BulkOperation(collection, options=bulk_options)
for doc in documents
doc, inserted_oid = _new_id(doc)
bulk_insert!(bulk_operation, doc, options=insert_options)
push!(inserted_oids, inserted_oid)
end
result = execute!(bulk_operation)
append!(result.inserted_oids, inserted_oids)
return result
end
"""
find(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Cursor
Executes a query on `collection` and returns an iterable `Cursor`.
# Example
```julia
function find_contract_codes(collection, criteria::Dict=Dict()) :: Vector{String}
result = Vector{String}()
let
bson_filter = Mongoc.BSON(criteria)
bson_options = Mongoc.BSON(\"\"\"{ "projection" : { "_id" : true }, "sort" : { "_id" : 1 } }\"\"\")
for bson_document in Mongoc.find(collection, bson_filter, options=bson_options)
push!(result, bson_document["_id"])
end
end
return result
end
```
Check the [libmongoc documentation](http://mongoc.org/libmongoc/current/mongoc_collection_find_with_opts.html)
for more information.
"""
function find(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Cursor
options_handle = options == nothing ? C_NULL : options.handle
cursor_handle = mongoc_collection_find_with_opts(collection.handle, bson_filter.handle,
options_handle, C_NULL)
if cursor_handle == C_NULL
error("Couldn't execute query.")
end
return Cursor(collection, cursor_handle)
end
"""
count_documents(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Int
Returns the number of documents on a `collection`,
with an optional filter given by `bson_filter`.
`length(collection)` and `Mongoc.count_documents(collection)`
produces the same output.
# Example
```julia
result = length(collection, Mongoc.BSON("_id" => oid))
```
"""
function count_documents(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Int
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
len = mongoc_collection_count_documents(collection.handle, bson_filter.handle,
options_handle, C_NULL, C_NULL, err_ref)
if len == -1
throw(err_ref[])
end
return Int(len)
end
function set_limit!(cursor::Cursor, limit::Int)
ok = mongoc_cursor_set_limit(cursor.handle, limit)
if !ok
error("Couldn't set cursor limit to $limit.")
end
nothing
end
"""
find_one(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
Execute a query to a collection and returns the first element of the result set.
Returns `nothing` if the result set is empty.
"""
function find_one(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
cursor = find(collection, bson_filter, options=options)
set_limit!(cursor, 1)
next = _iterate(cursor)
if next == nothing
return nothing
else
bson_document, _state = next
return bson_document
end
end
"""
aggregate(collection::Collection, bson_pipeline::BSON;
flags::QueryFlags=QUERY_FLAG_NONE,
options::Union{Nothing, BSON}=nothing) :: Cursor
Use `Mongoc.aggregate` to execute an aggregation command.
# Example
The following reproduces the example from the
[MongoDB Tutorial](https://docs.mongodb.com/manual/aggregation/).
```julia
docs = [
Mongoc.BSON(\"\"\"{ "cust_id" : "A123", "amount" : 500, "status" : "A" }\"\"\"),
Mongoc.BSON(\"\"\"{ "cust_id" : "A123", "amount" : 250, "status" : "A" }\"\"\"),
Mongoc.BSON(\"\"\"{ "cust_id" : "B212", "amount" : 200, "status" : "A" }\"\"\"),
Mongoc.BSON(\"\"\"{ "cust_id" : "A123", "amount" : 300, "status" : "D" }\"\"\")
]
collection = client["my-database"]["aggregation-collection"]
append!(collection, docs)
# Sets the pipeline command
bson_pipeline = Mongoc.BSON(\"\"\"
[
{ "\$match" : { "status" : "A" } },
{ "\$group" : { "_id" : "\$cust_id", "total" : { "\$sum" : "\$amount" } } }
]
\"\"\")
for doc in Mongoc.aggregate(collection, bson_pipeline)
println(doc)
end
```
The result of the script above is:
```julia
BSON("{ "_id" : "B212", "total" : 200 }")
BSON("{ "_id" : "A123", "total" : 750 }")
```
"""
function aggregate(collection::Collection, bson_pipeline::BSON;
flags::QueryFlags=QUERY_FLAG_NONE,
options::Union{Nothing, BSON}=nothing) :: Cursor
options_handle = options == nothing ? C_NULL : options.handle
cursor_handle = mongoc_collection_aggregate(collection.handle, flags,
bson_pipeline.handle, options_handle, C_NULL)
if cursor_handle == C_NULL
error("Couldn't execute aggregate command.")
end
return Cursor(collection, cursor_handle)
end
"""
drop(database::Database, opts::Union{Nothing, BSON}=nothing)
drop(collection::Collection, opts::Union{Nothing, BSON}=nothing)
Drops `database` or `collection`.
For information about `opts` argument, check the libmongoc documentation for
[database drop](http://mongoc.org/libmongoc/current/mongoc_database_drop_with_opts.html)
or
[collection drop](http://mongoc.org/libmongoc/current/mongoc_collection_drop_with_opts.html).
"""
function drop(collection::Collection, opts::Union{Nothing, BSON}=nothing)
opts_handle = opts == nothing ? C_NULL : opts.handle
err_ref = Ref{BSONError}()
ok = mongoc_collection_drop_with_opts(collection.handle, opts_handle, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
# findAndModify
function Base.setproperty!(builder::FindAndModifyOptsBuilder, opt::Symbol, val::BSON)
if opt == :update
set_opt_update!(builder, val)
elseif opt == :sort
set_opt_sort!(builder, val)
elseif opt == :fields
set_opt_fields!(builder, val)
else
error("Unknown option for FindAndModifyOptsBuilder: $opt")
end
end
function Base.setproperty!(builder::FindAndModifyOptsBuilder, opt::Symbol, val::FindAndModifyFlags)
@assert opt == :flags "Can't set $val to field $opt."
set_opt_flags!(builder, val)
end
function set_opt_update!(builder::FindAndModifyOptsBuilder, val::BSON)
ok = mongoc_find_and_modify_opts_set_update(builder.handle, val.handle)
if !ok
error("Couldn't set option update $val for FindAndModifyOptsBuilder.")
end
nothing
end
function set_opt_sort!(builder::FindAndModifyOptsBuilder, val::BSON)
ok = mongoc_find_and_modify_opts_set_sort(builder.handle, val.handle)
if !ok
error("Couldn't set option sort $val for FindAndModifyOptsBuilder.")
end
nothing
end
function set_opt_fields!(builder::FindAndModifyOptsBuilder, val::BSON)
ok = mongoc_find_and_modify_opts_set_fields(builder.handle, val.handle)
if !ok
error("Couldn't set option fields $val for FindAndModifyOptsBuilder.")
end
nothing
end
function set_opt_flags!(builder::FindAndModifyOptsBuilder, val::FindAndModifyFlags)
ok = mongoc_find_and_modify_opts_set_flags(builder.handle, val)
if !ok
error("Couldn't set option flags $val for FindAndModifyOptsBuilder.")
end
nothing
end
function Base.setproperty!(builder::FindAndModifyOptsBuilder, opt::Symbol, val::Bool)
@assert opt == :bypass_document_validation "Can't set $val to field $opt."
set_opt_bypass_document_validation!(builder, val)
end
function set_opt_bypass_document_validation!(builder::FindAndModifyOptsBuilder, bypass::Bool)
ok = mongoc_find_and_modify_opts_set_bypass_document_validation(builder.handle, bypass)
if !ok
error("Couldn't set option `bypass document validation` for FindAndModifyOptsBuilder.")
end
nothing
end
"""
find_and_modify(collection::Collection, query::BSON;
update::Union{Nothing, BSON}=nothing,
sort::Union{Nothing, BSON}=nothing,
fields::Union{Nothing, BSON}=nothing,
flags::Union{Nothing, FindAndModifyFlags}=nothing,
bypass_document_validation::Bool=false,
) :: BSON
Find documents and updates them in one go.
See [`Mongoc.FindAndModifyFlags`](@ref) for a list of accepted values
for `flags` argument.
# C API
* [mongoc_collection_find_and_modify](http://mongoc.org/libmongoc/current/mongoc_collection_find_and_modify.html).
"""
function find_and_modify(collection::Collection, query::BSON;
update::Union{Nothing, BSON}=nothing,
sort::Union{Nothing, BSON}=nothing,
fields::Union{Nothing, BSON}=nothing,
flags::Union{Nothing, FindAndModifyFlags}=nothing,
bypass_document_validation::Bool=false,
) :: BSON
opts = FindAndModifyOptsBuilder(
update=update,
sort=sort,
fields=fields,
flags=flags,
bypass_document_validation=bypass_document_validation,
)
reply = BSON()
err_ref = Ref{BSONError}()
ok = mongoc_collection_find_and_modify_with_opts(
collection.handle,
query.handle, opts.handle,
reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
const FIND_ONE_AND_DELETE_FIELDS = Dict(
"collation" => "collation",
"maxTimeMS" => "maxTimeMS",
"projection" => "fields",
"sort" => "sort",
"writeConcern" => "writeConcern",
)
"""
find_one_and_delete(collection::Collection, bson_filter::BSON;
options::Union{Nothing, BSON}=nothing
) :: Union{Nothing, BSON}
Delete a document and return it.
See [db.collection.findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/)
for a list of accepted options.
"""
function find_one_and_delete(collection::Collection, bson_filter::BSON;
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
command_bson = BSON(
"findAndModify" => collection.name,
"query" => bson_filter,
"remove" => true,
)
options_bson = BSON()
if !isnothing(options)
for (opt_key, comm_key) in FIND_ONE_AND_DELETE_FIELDS
if haskey(options, opt_key)
command_bson[comm_key] = options[opt_key]
end
end
if haskey(options, "sessionId")
options_bson["sessionId"] = options["sessionId"]
end
end
reply = write_command(
collection.database,
command_bson,
options=options_bson,
)
return reply["value"]
end
const FIND_ONE_AND_MODIFY_FIELDS = Dict(
"arrayFilters" => "arrayFilters",
"bypassDocumentValidation" .=> "bypassDocumentValidation",
"collation" => "collation",
"maxTimeMS" => "maxTimeMS",
"projection" => "fields",
"returnNewDocument" => "new",
"sort" => "sort",
"upsert" => "upsert",
"writeConcern" => "writeConcern",
)
function _find_one_and_modify(collection::Collection, bson_filter::BSON, bson_modify::BSON;
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
command_bson = BSON(
"findAndModify" => collection.name,
"query" => bson_filter,
"update" => bson_modify,
)
options_bson = BSON()
if !isnothing(options)
for (opt_key, comm_key) in FIND_ONE_AND_MODIFY_FIELDS
if haskey(options, opt_key)
command_bson[comm_key] = options[opt_key]
end
end
if haskey(options, "sessionId")
options_bson["sessionId"] = options["sessionId"]
end
end
reply = write_command(
collection.database,
command_bson,
options=options_bson,
)
return reply["value"]
end
"""
find_one_and_replace(collection::Collection, bson_filter::BSON, bson_replacement::BSON;
options::Union{Nothing, BSON}=nothing
) :: Union{Nothing, BSON}
Replace a document and return the original.
See [db.collection.findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/)
for a list of accepted options.
"""
function find_one_and_replace(collection::Collection, bson_filter::BSON, bson_replacement::BSON;
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
# Ensure the document has no operators
for key in keys(bson_replacement)
if startswith(key, '$')
throw(ArgumentError("replacement must not contain update operators"))
end
end
return _find_one_and_modify(collection, bson_filter, bson_replacement, options=options)
end
"""
find_one_and_update(collection::Collection, bson_filter::BSON, bson_update::BSON;
options::Union{Nothing, BSON}=nothing
) :: Union{Nothing, BSON}
Update a document and return the original.
See [db.collection.findOneAndUpdate](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/)
for a list of accepted options.
"""
function find_one_and_update(collection::Collection, bson_filter::BSON, bson_update::BSON;
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
# Ensure the document only contains operators
for key in keys(bson_update)
if !startswith(key, '$')
throw(ArgumentError("update must only contain update operators"))
end
end
return _find_one_and_modify(collection, bson_filter, bson_update, options=options)
end
#
# High-level API
#
function _iterate(cursor::Cursor, state::Nothing=nothing)
bson_handle_ref = Ref{Ptr{Cvoid}}()
has_next = mongoc_cursor_next(cursor.handle, bson_handle_ref)
if has_next
# The bson document is valid only until the next call to mongoc_cursor_next.
# So we should return a deepcopy.
return deepcopy(BSON(bson_handle_ref[], enable_finalizer=false)), nothing
else
err_ref = Ref{BSONError}()
if mongoc_cursor_error(cursor.handle, err_ref)
throw(err_ref[])
end
return nothing
end
end
# Cursor implementation of the iteration interface
Base.iterate(cursor::Cursor, state::Nothing=nothing) = _iterate(cursor, state)
Base.IteratorSize(::Type{Cursor{T}}) where T = Base.SizeUnknown()
Base.IteratorEltype(::Type{Cursor{T}}) where T = Base.HasEltype()
Base.eltype(::Type{Cursor{T}}) where T = BSON
# Collection implementation of the iteration interface
Base.IteratorSize(::Type{<:AbstractCollection}) = Base.HasLength()
Base.IteratorEltype(::Type{<:AbstractCollection}) = Base.HasEltype()
Base.eltype(::Type{<:AbstractCollection}) = BSON
function Base.iterate(coll::Collection)
cursor = find(coll)
return iterate(coll, cursor)
end
function Base.iterate(coll::Collection, state::Cursor)
next = _iterate(state)
if next === nothing
return nothing
else
doc, _ = next
return doc, state
end
end
function Base.push!(collection::AbstractCollection, document::BSON;
options::Union{Nothing, BSON}=nothing)
insert_one(collection, document; options=options)
end
function Base.append!(collection::AbstractCollection, documents::Vector{BSON};
bulk_options::Union{Nothing, BSON}=nothing,
insert_options::Union{Nothing, BSON}=nothing)
insert_many(collection, documents; bulk_options=bulk_options, insert_options=insert_options)
end
function Base.length(collection::AbstractCollection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing)
count_documents(collection, bson_filter; options=options)
end
function Base.isempty(collection::AbstractCollection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing)
count_documents(collection, bson_filter; options=options) == 0
end
Base.empty!(collection::C) where {C<:AbstractCollection} = delete_many(collection, BSON())
function Base.collect(cursor::Cursor) :: Vector{BSON}
result = Vector{BSON}()
for doc in cursor
push!(result, doc)
end
return result
end
function Base.collect(collection::AbstractCollection, bson_filter::BSON=BSON())
return collect(find(collection, bson_filter))
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 5293 |
Base.show(io::IO, db::Database) = print(io, "Database($(db.client), \"", db.name, "\")")
Base.getindex(database::Database, collection_name::String) = Collection(database, collection_name)
"""
command_simple(database::Database, command::BSON) :: BSON
command_simple(collection::Collection, command::BSON) :: BSON
Executes a `command` given by a JSON string or a BSON instance.
It returns the first document from the result cursor.
# Example
```julia
julia> client = Mongoc.Client() # connects to localhost at port 27017
Client(URI("mongodb://localhost:27017"))
julia> bson_result = Mongoc.command_simple(client[\"admin\"], "{ \"ping\" : 1 }")
BSON("{ "ok" : 1.0 }")
```
# C API
* [`mongoc_database_command_simple`](http://mongoc.org/libmongoc/current/mongoc_database_command_simple.html)
"""
function command_simple(database::Database, command::BSON) :: BSON
reply = BSON()
err_ref = Ref{BSONError}()
ok = mongoc_database_command_simple(database.handle, command.handle, C_NULL, reply.handle,
err_ref)
if !ok
throw(err_ref[])
end
return reply
end
"""
write_command(database::Database, command::BSON;
options::Union{Nothing, BSON}=nothing) :: BSON
Issue a command with write semantics.
See http://mongoc.org/libmongoc/current/mongoc_database_read_write_command_with_opts.html.
"""
function write_command(database::Database, command::BSON;
options::Union{Nothing, BSON}=nothing) :: BSON
options_handle = options == nothing ? C_NULL : options.handle
reply = BSON()
err_ref = Ref{BSONError}()
ok = mongoc_database_write_command_with_opts(database.handle, command.handle,
options_handle, reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
"""
read_command(database::Database, command::BSON;
options::Union{Nothing, BSON}=nothing) :: BSON
Issue a command with read semantics.
See http://mongoc.org/libmongoc/current/mongoc_database_read_command_with_opts.html.
"""
function read_command(database::Database, command::BSON;
options::Union{Nothing, BSON}=nothing) :: BSON
options_handle = options == nothing ? C_NULL : options.handle
reply = BSON()
err_ref = Ref{BSONError}()
ok = mongoc_database_read_command_with_opts(database.handle, command.handle,
C_NULL, options_handle, reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
"""
add_user(database::Database, username::String, password::String, roles::Union{Nothing, BSON},
custom_data::Union{Nothing, BSON}=nothing)
This function shall create a new user with access to database.
**Warning:** Do not call this function without TLS.
"""
function add_user(database::Database, username::String, password::String,
roles::Union{Nothing, BSON}, custom_data::Union{Nothing, BSON}=nothing)
err_ref = Ref{BSONError}()
roles_handle = roles == nothing ? C_NULL : roles.handle
custom_data_handle = custom_data == nothing ? C_NULL : custom_data.handle
ok = mongoc_database_add_user(database.handle, username, password, roles_handle,
custom_data_handle, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
"""
remove_user(database::Database, username::String)
Removes a user from database.
"""
function remove_user(database::Database, username::String)
err_ref = Ref{BSONError}()
ok = mongoc_database_remove_user(database.handle, username, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
"""
has_user(database::Database, user_name::String) :: Bool
Checks if `database` has a user named `user_name`.
"""
function has_user(database::Database, user_name::String) :: Bool
cmd_result = command_simple(database, BSON("""{ "usersInfo": "$user_name" }"""))
return !isempty(cmd_result["users"])
end
"""
find_collections(database::Database; options::Union{Nothing, BSON}=nothing) :: Cursor
Queries for collections in a `database`.
"""
function find_collections(database::Database; options::Union{Nothing, BSON}=nothing) :: Cursor
options_handle = options == nothing ? C_NULL : options.handle
cursor_handle = mongoc_database_find_collections_with_opts(database.handle, options_handle)
if cursor_handle == C_NULL
error("Couldn't execute query.")
end
return Cursor(database, cursor_handle)
end
"""
get_collection_names(database::Database;
options::Union{Nothing, BSON}=nothing) :: Vector{String}
Helper method to get collection names.
See also [`Mongoc.find_collections`](@ref).
"""
function get_collection_names(database::Database;
options::Union{Nothing, BSON}=nothing) :: Vector{String}
result = Vector{String}()
for bson_collection in find_collections(database, options=options)
push!(result, bson_collection["name"])
end
return result
end
# docstring for drop is at collection.jl
function drop(database::Database;
options::Union{Nothing, BSON}=nothing)
err_ref = Ref{BSONError}()
opts_handle = options == nothing ? C_NULL : options.handle
ok = mongoc_database_drop_with_opts(database.handle, opts_handle, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 11597 |
"""
upload(bucket::Bucket, filename::AbstractString, source::AbstractMongoStream;
options::Union{Nothing, BSON}=nothing,
file_id=BSONObjectId())
Uploads data from `source` to a GridFS file `filename`.
`bson_file_id` is a BSON document with a `_id` field.
If `_id` field is not present, a `BSONObjectId` will be generated.
"""
function upload(bucket::Bucket, filename::AbstractString, source::AbstractMongoStream;
file_id=BSONObjectId(),
chunk_size::Union{Nothing, Integer}=nothing,
metadata::Union{Nothing, BSON}=nothing)
# Julia does not support C unions.
# libmongoc represents bson_value_t as a C union.
# To make things work, here we construct a BSON document
# and set the id. Later, we retrieve a bson_value_t
# using get_as_bson_value, which uses bson_iter_value.
# new_bson_with_id returns a tuple with the BSON doc
# along with the id to ensure that the lifetime of the BSON
# doc exceeds the lifetime of the bson_value_t
# that we'll pass to mongoc_gridfs_bucket_upload_from_stream_with_id.
function new_bson_with_id(id)
doc = BSON("_id" => id)
return doc, get_as_bson_value(doc, "_id")
end
doc, file_id_as_bson_value = new_bson_with_id(file_id)
function new_bson_upload_opts(chunk_size::Union{Nothing, Integer}, metadata::Union{Nothing, BSON}) :: Union{Nothing, BSON}
if chunk_size == nothing && metadata == nothing
return nothing
else
result = BSON()
if chunk_size != nothing
result["chunkSizeBytes"] = Int32(chunk_size)
end
if metadata != nothing
result["metadata"] = metadata
end
return result
end
end
options = new_bson_upload_opts(chunk_size, metadata)
options_handle = options == nothing ? C_NULL : options.handle
err_ref = Ref{BSONError}()
ok = mongoc_gridfs_bucket_upload_from_stream_with_id(
bucket.handle,
file_id_as_bson_value.handle,
filename,
source.handle,
options_handle,
err_ref
)
if !ok
throw(err_ref[])
end
nothing
end
"""
upload(bucket::Bucket, remote_filename::AbstractString, local_source_filepath::AbstractString;
options::Union{Nothing, BSON}=nothing,
file_id=BSONObjectId())
High-level interface to upload a local file to a GridFS bucket.
"""
function upload(bucket::Bucket, remote_filename::AbstractString, local_source_filepath::AbstractString;
file_id=BSONObjectId(),
chunk_size::Union{Nothing, Integer}=nothing,
metadata::Union{Nothing, BSON}=nothing)
@assert isfile(local_source_filepath) "Couldn't find $local_source_filepath."
source_stream = MongoStreamFile(local_source_filepath)
try
upload(bucket, remote_filename, source_stream,
file_id=file_id, chunk_size=chunk_size, metadata=metadata)
finally
close(source_stream)
end
end
"""
download(bucket::Bucket, file_id, target::AbstractMongoStream)
Download a GridFS file identified by `file_id` to `target` stream.
`file_id` may be either a `BSONValue` or a `BSON` document with an `_id` field.
"""
function download(bucket::Bucket, file_id::BSONValue, target::AbstractMongoStream)
err_ref = Ref{BSONError}()
ok = mongoc_gridfs_bucket_download_to_stream(
bucket.handle, file_id.handle, target.handle, err_ref
)
if !ok
throw(err_ref[])
end
nothing
end
function download(bucket::Bucket, file_info::BSON, target::AbstractMongoStream)
@assert haskey(file_info, "_id")
download(bucket, get_as_bson_value(file_info, "_id"), target)
end
function find_file_info(bucket::Bucket, filename::AbstractString) :: BSON
bson_filter = BSON()
bson_filter["filename"] = String(filename)
local found::Bool=false
local result::BSON
for doc in find(bucket, bson_filter)
@assert !found "More than 1 file was found with name $filename."
found = true
result = doc
end
@assert found "Coudln't find file with name $filename."
return result
end
function download(bucket::Bucket, remote_file_id_or_info::Union{BSONValue, BSON}, local_filepath::AbstractString;
flags::Integer=(Base.Filesystem.JL_O_CREAT | Base.Filesystem.JL_O_RDWR), mode::Integer=0o600)
download_file_stream = Mongoc.MongoStreamFile(local_filepath, flags=(Base.Filesystem.JL_O_CREAT | Base.Filesystem.JL_O_RDWR), mode=0o600)
try
Mongoc.download(bucket, remote_file_id_or_info, download_file_stream)
finally
Mongoc.close(download_file_stream)
end
end
"""
download(bucket::Bucket, remote_file, local_filepath::AbstractString;
flags::Integer=(Base.Filesystem.JL_O_CREAT | Base.Filesystem.JL_O_RDWR), mode::Integer=0o600
Downloads a GridFS file `remote_file` to `local_filepath`.
`remote_file` can be either a unique filename, or a `file_id::BSONValue`, or `file_info::BSON`.
"""
function download(bucket::Bucket, remote_filename::AbstractString, local_filepath::AbstractString;
flags::Integer=(Base.Filesystem.JL_O_CREAT | Base.Filesystem.JL_O_RDWR), mode::Integer=0o600)
file_info = find_file_info(bucket, remote_filename)
download(bucket, file_info, local_filepath, flags=flags, mode=mode)
end
"""
find(bucket::Bucket, bson_filter::BSON=BSON();
options::BSON=BSON()) :: Cursor
Looks for files in GridFS bucket.
"""
function find(bucket::Bucket, bson_filter::BSON=BSON();
options::BSON=BSON()) :: Cursor
cursor_handle = mongoc_gridfs_bucket_find(bucket.handle, bson_filter.handle, options.handle)
if cursor_handle == C_NULL
error("Couldn't execute query.")
end
return Cursor(bucket, cursor_handle)
end
"""
delete(bucket::Bucket, file_id)
delete(bucket::Bucket, file_metadata::BSON)
Deletes a file from a GridFS Bucket.
"""
function delete(bucket::Bucket, file_id::BSONValue)
err_ref = Ref{BSONError}()
ok = mongoc_gridfs_bucket_delete_by_id(bucket.handle, file_id.handle, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
function delete(bucket::Bucket, file_metadata::BSON)
oid_as_bson_value = get_as_bson_value(file_metadata, "_id")
delete(bucket, oid_as_bson_value)
end
function delete(bucket::Bucket, file_id)
file_metadata = BSON("_id" => file_id)
delete(bucket, file_metadata)
end
function Base.empty!(bucket::Bucket)
for doc in find(bucket)
delete(bucket, doc)
end
end
function Base.isempty(bucket::Bucket)
for _ in find(bucket)
return false
end
return true
end
function open_download_stream(bucket::Bucket, file_id::BSONValue;
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE) :: MongoIOStream
err_ref = Ref{BSONError}()
stream_handle = mongoc_gridfs_bucket_open_download_stream(bucket.handle, file_id.handle, err_ref)
if stream_handle == C_NULL
throw(err_ref[])
end
return MongoIOStream(bucket, stream_handle; timeout_msec=timeout_msec, chunk_size=chunk_size)
end
function open_download_stream(bucket::Bucket, filename::AbstractString) :: MongoIOStream
local result::MongoIOStream
file_info = find_file_info(bucket, filename)
return open_download_stream(bucket, file_info)
end
function open_download_stream(bucket::Bucket, file_info::BSON;
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE) :: MongoIOStream
@assert haskey(file_info, "_id")
return open_download_stream(bucket, get_as_bson_value(file_info, "_id"),
timeout_msec=timeout_msec,
chunk_size=chunk_size)
end
"""
open_download_stream(f, bucket, filename)
open_download_stream(bucket, filename) :: MongoIOStream
Opens a stream for reading a remote file identified by `filename`.
# Example
Open a stream, do some work, then close it.
```julia
io = Mongoc.open_download_stream(bucket, file)
try
tmp_str = read(io, String)
finally
close(io)
end
```
Use *do-syntax* to ensure that the `io` stream will
be closed in case something goes wrong.
```julia
Mongoc.open_download_stream(bucket, remote_filename) do io
tmp_str = read(io, String)
end
```
"""
function open_download_stream(f::Function, bucket::Bucket, file::Union{BSONValue, AbstractString})
stream = open_download_stream(bucket, file)
try
f(stream)
finally
close(stream)
end
end
function open_upload_stream(bucket::Bucket, file_id::BSONValue, filename::AbstractString;
options::Union{Nothing, BSON}=nothing,
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE) :: MongoIOStream
err_ref = Ref{BSONError}()
options_handle = options == nothing ? C_NULL : options.handle
stream_handle = mongoc_gridfs_bucket_open_upload_stream_with_id(
bucket.handle, file_id.handle, filename, options_handle,
err_ref)
if stream_handle == C_NULL
throw(err_ref[])
end
return MongoIOStream(
bucket,
stream_handle,
timeout_msec=timeout_msec,
chunk_size=chunk_size
)
end
function open_upload_stream(bucket::Bucket, file_info::BSON;
options::Union{Nothing, BSON}=nothing,
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE) :: MongoIOStream
@assert haskey(file_info, "filename") "`file_info` must have a `filename` field."
# generates a new _id if not present in `file_info`
if !haskey(file_info, "_id")
file_info["_id"] = BSONObjectId()
end
return open_upload_stream(
bucket, get_as_bson_value(file_info, "_id"), file_info["filename"],
options=options, timeout_msec=timeout_msec, chunk_size=chunk_size
)
end
"""
open_upload_stream(bucket, file_id, filename; [options], [timeout_msec], [chunk_size]) :: MongoIOStream
open_upload_stream(bucket, filename; [options], [timeout_msec], [chunk_size]) :: MongoIOStream
open_upload_stream(bucket, file_info; [options], [timeout_msec], [chunk_size]) :: MongoIOStream
Opens a stream to upload a file to a GridFS Bucket.
`file_info` is a BSON document with the following fields:
* `_id` as an optional identifier.
* `filename` as the name of the file in the remote bucket.
If `_id` is not provided, a `BSONObjectId` will be generated.
# Example
```julia
data = rand(UInt8, 3_000_000)
remote_filename = "uploaded.data"
io = Mongoc.open_upload_stream(bucket, remote_filename)
write(io, data)
close(io)
```
"""
function open_upload_stream(bucket::Bucket, file_id, filename::AbstractString;
options::Union{Nothing, BSON}=nothing,
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE) :: MongoIOStream
file_info = BSON("_id" => file_id, "filename" => filename)
return open_upload_stream(bucket, file_info,
options=options, timeout_msec=timeout_msec, chunk_size=chunk_size)
end
function open_upload_stream(bucket::Bucket, filename::AbstractString;
options::Union{Nothing, BSON}=nothing,
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE) :: MongoIOStream
file_info = BSON("filename" => filename)
return open_upload_stream(bucket, file_info,
options=options, timeout_msec=timeout_msec, chunk_size=chunk_size)
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 8302 |
# Append session to options.
# Given that options may be nothing, always use the return value as the new value for options.
function _join(options::Union{Nothing, BSON}, session::Session) :: BSON
result = options == nothing ? Mongoc.BSON() : options
err_ref = Ref{BSONError}()
ok = mongoc_client_session_append(session.handle, result.handle, err_ref)
if !ok
throw(err_ref[])
end
return result
end
function set_casual_consistency!(session_options::SessionOptions, casual_consistency::Bool)
mongoc_session_opts_set_causal_consistency(session_options.handle, casual_consistency)
nothing
end
function get_casual_consistency(session_options::SessionOptions) :: Bool
mongoc_session_opts_get_causal_consistency(session_options.handle)
end
get_session(database_session::DatabaseSession) = database_session.session
get_session(collection_session::CollectionSession) = get_session(collection_session.database_session)
function DatabaseSession(session::Session, db_name::String)
DatabaseSession(Database(session.client, db_name), session)
end
function CollectionSession(database_session::DatabaseSession, collection_name::String)
CollectionSession(database_session, Collection(database_session.database, collection_name))
end
Base.getindex(session::Session, db_name::String) = DatabaseSession(session, db_name)
function Base.getindex(database_session::DatabaseSession, collection_name::String)
CollectionSession(database_session, collection_name)
end
#
# Overload
#
function find_collections(database::DatabaseSession; options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(database))
find_collections(database.database; options=options_with_session)
end
function get_collection_names(database::DatabaseSession; options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(database))
get_collection_names(database.database, options=options_with_session)
end
function insert_one(collection::CollectionSession, document::BSON;
options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(collection))
insert_one(collection.collection, document, options=options_with_session)
end
function delete_one(collection::CollectionSession, selector::BSON;
options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(collection))
delete_one(collection.collection, selector, options=options_with_session)
end
function delete_many(collection::CollectionSession, selector::BSON;
options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(collection))
delete_many(collection.collection, selector, options=options_with_session)
end
function update_one(collection::CollectionSession, selector::BSON, update::BSON;
options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(collection))
update_one(collection.collection, selector, update, options=options_with_session)
end
function update_many(collection::CollectionSession, selector::BSON, update::BSON;
options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(collection))
update_many(collection.collection, selector, update, options=options_with_session)
end
function insert_many(collection::CollectionSession, documents::Vector{BSON};
bulk_options::Union{Nothing, BSON}=nothing,
insert_options::Union{Nothing, BSON}=nothing)
bulk_options_with_session = _join(bulk_options, get_session(collection))
insert_many(collection.collection, documents,
bulk_options=bulk_options_with_session, insert_options=insert_options)
end
function find(collection::CollectionSession, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Cursor
options_with_session = _join(options, get_session(collection))
find(collection.collection, bson_filter, options=options_with_session)
end
function count_documents(collection::CollectionSession, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing)
options_with_session = _join(options, get_session(collection))
count_documents(collection.collection, bson_filter, options=options_with_session)
end
function find_one(collection::CollectionSession, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
options_with_session = _join(options, get_session(collection))
find_one(collection.collection, bson_filter, options=options_with_session)
end
function aggregate(collection::CollectionSession, bson_pipeline::BSON;
flags::QueryFlags=QUERY_FLAG_NONE,
options::Union{Nothing, BSON}=nothing) :: Cursor
options_with_session = _join(options, get_session(collection))
aggregate(collection.collection, bson_pipeline, flags=flags, options=options_with_session)
end
function find_one_and_delete(collection::CollectionSession, bson_filter::BSON;
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
options_with_session = _join(options, get_session(collection))
find_one_and_delete(collection.collection, bson_filter, options=options_with_session)
end
function find_one_and_replace(collection::CollectionSession, bson_filter::BSON, bson_replacement::BSON;
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
options_with_session = _join(options, get_session(collection))
find_one_and_replace(collection.collection, bson_filter, bson_replacement, options=options_with_session)
end
function find_one_and_update(collection::CollectionSession, bson_filter::BSON, bson_update::BSON;
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
options_with_session = _join(options, get_session(collection))
find_one_and_update(collection.collection, bson_filter, bson_update, options=options_with_session)
end
function drop(collection::CollectionSession, opts::Union{Nothing, BSON}=nothing)
drop(collection.collection, opts)
end
#
# Transaction
#
function start_transaction!(session::Session)
err_ref = Ref{BSONError}()
ok = mongoc_client_session_start_transaction(session.handle, C_NULL, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
function abort_transaction!(session::Session)
err_ref = Ref{BSONError}()
ok = mongoc_client_session_abort_transaction(session.handle, err_ref)
if !ok
throw(err_ref[])
end
nothing
end
function commit_transaction!(session::Session) :: BSON
reply = BSON()
err_ref = Ref{BSONError}()
ok = mongoc_client_session_commit_transaction(session.handle, reply.handle, err_ref)
if !ok
throw(err_ref[])
end
return reply
end
in_transaction(session::Session) :: Bool = mongoc_client_session_in_transaction(session.handle)
#
# High-level API
#
"""
transaction(f::Function, client::Client; session_options::SessionOptions=SessionOptions())
Use *do-syntax* to execute a transaction.
Transaction will be commited automatically. If an error occurs, the transaction is aborted.
The `session` parameter should be treated the same way as a `Client`:
from a `session` you get a `database`,
and a `collection` that are bound to the session.
```julia
Mongoc.transaction(client) do session
database = session["my_database"]
collection = database["my_collection"]
new_item = Mongoc.BSON()
new_item["inserted"] = true
push!(collection, new_item)
end
```
"""
function transaction(f::Function, client::Client; session_options::SessionOptions=SessionOptions())
local result::Union{Nothing, BSON} = nothing
local aborted::Bool = false
session = Session(client, options=session_options)
start_transaction!(session)
try
f(session)
catch
abort_transaction!(session)
aborted = true
rethrow()
finally
if !aborted
result = commit_transaction!(session)
end
Mongoc.destroy!(session)
end
return result
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 4595 |
"""
MongoStreamFile(filepath;
[flags=JL_O_RDONLY], [mode=0],
[timeout_msec=DEFAULT_TIMEOUT_MSEC],
[chunk_size=DEFAULT_CHUNK_SIZE])
Creates a stream from file located at `filepath`.
`flags` is the input to pass to `open`. Must be one of the constants
defined at `Base.Filesystem`: `Base.Filesystem.JL_O_RDONLY`,
`Base.Filesystem.JL_O_CREAT`, etc.
`mode` is an optional mode to pass to `open`.
"""
function MongoStreamFile(filepath::AbstractString;
flags::Integer=Base.Filesystem.JL_O_RDONLY,
mode::Integer=0,
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE)
handle = mongoc_stream_file_new_for_path(filepath, flags, mode)
if handle == C_NULL
error("Couldn't create stream for $filepath.")
end
return MongoStreamFile(nothing, handle, timeout_msec=timeout_msec, chunk_size=chunk_size)
end
function check_stream_error(stream::MongoIOStream)
err_ref = Ref{BSONError}()
if mongoc_gridfs_bucket_stream_error(stream.handle, err_ref)
throw(err_ref[])
end
nothing
end
function check_stream_error(stream::AbstractMongoStream)
nothing
end
"""
abort_upload(io::MongoIOStream)
Aborts the upload of a GridFS upload stream.
"""
function abort_upload(io::MongoIOStream)
ok = mongoc_gridfs_bucket_abort_upload(io.handle)
if !ok
check_stream_error(io)
error("Error aborting upload.")
end
nothing
end
function Base.flush(stream::AbstractMongoStream)
ok = mongoc_stream_flush(stream.handle)
if ok == -1
check_stream_error(stream)
error("Error flushing stream.")
end
@assert ok == 0 "Unexpected result from mongoc_stream_flush: $(Int(ok))"
nothing
end
function Base.close(stream::AbstractMongoStream)
if stream.isopen
ok = mongoc_stream_close(stream.handle)
if ok == -1
check_stream_error(stream)
error("Error closing stream.")
end
@assert ok == 0 "Unexpected result from mongoc_stream_close: $(Int(ok))"
stream.isopen = false
end
nothing
end
Base.isopen(stream::AbstractMongoStream) = stream.isopen
function Base.readbytes!(s::AbstractMongoStream, buffer::AbstractArray{UInt8}, nb=length(b))
chunk = Vector{UInt8}(undef, s.chunk_size)
total_nr = 0
while true
next_nb = min(s.chunk_size, nb - total_nr)
nr = fillbuffer!(s, chunk, next_nb)
if nr == 0
# reached end of stream
break
end
transfer_to_buffer!( buffer, total_nr, chunk, nr )
total_nr += nr
# should never happen
@assert total_nr <= nb
if total_nr == nb
# read the number of bytes requested
break
end
end
return total_nr
end
# returns the number of available bytes in the buffer
function nb_free(buffer, buffer_pos::Integer)
@assert length(buffer) >= buffer_pos
return length(buffer) - buffer_pos
end
# returns the number of bytes that will be copied to the buffer
function nb_to_fill(buffer, buffer_pos::Integer, nr::Integer)
fr = nb_free(buffer, buffer_pos)
return min(nr, fr)
end
# returns the number of bytes that will be appended to the buffer
function nb_to_append(buffer, buffer_pos::Integer, nr::Integer)
result = nr - nb_to_fill(buffer, buffer_pos, nr)
@assert result >= 0
return result
end
# transfers nr bytes from data to target.buffer
# writes data after target.pos, increasing buffer size if needed
function transfer_to_buffer!(buffer::T, buffer_pos::Integer, data::T, nr::Integer) where {T}
# sanity checks
@assert nr > 0
@assert length(data) >= nr
@assert buffer_pos <= length(buffer)
resize!(buffer, length(buffer) + nb_to_append(buffer, buffer_pos, nr))
for i in 1:nr
buffer[buffer_pos + i] = data[i]
end
end
# reads at most nb byter to buffer without resizing it
# returns the number of bytes read
function fillbuffer!(s::AbstractMongoStream, buffer::AbstractArray{UInt8}, nb::Integer)
@assert nb <= length(buffer)
nr = mongoc_stream_read(s.handle, pointer(buffer), nb, 0, s.timeout_msec)
if nr == -1
check_stream_error(stream)
error("Error closing stream.")
end
return nr
end
function Base.unsafe_write(io::AbstractMongoStream, p::Ptr{UInt8}, n::UInt)
written = mongoc_stream_write(io.handle, p, n, io.timeout_msec)
if written == -1
check_stream_error(io)
error("Error writing to stream.")
end
@assert written >= 0
return Int(written)
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 15825 |
"""
`QueryFlags` correspond to the MongoDB wire protocol.
They may be bitwise or’d together.
They may modify how a query is performed in the MongoDB server.
These flags are passed as optional argument
for the aggregation function `Mongoc.aggregate`.
This data type mirrors C struct `mongoc_query_flags_t`.
See [libmongoc docs](http://mongoc.org/libmongoc/current/mongoc_query_flags_t.html)
for more information.
# Constants
`Mongoc.QUERY_FLAG_NONE`:
Specify no query flags.
`Mongoc.QUERY_FLAG_TAILABLE_CURSOR`:
Cursor will not be closed when the last data is retrieved. You can resume this cursor later.
`Mongoc.QUERY_FLAG_SLAVE_OK`:
Allow query of replica set secondaries.
`Mongoc.QUERY_FLAG_OPLOG_REPLAY`:
Used internally by MongoDB.
`Mongoc.QUERY_FLAG_NO_CURSOR_TIMEOUT`:
The server normally times out an idle cursor after an inactivity period (10 minutes).
This prevents that.
`Mongoc.QUERY_FLAG_AWAIT_DATA`:
Use with `Mongoc.MONGOC_QUERY_TAILABLE_CURSOR`. Block rather than returning no data.
After a period, time out.
`Mongoc.QUERY_FLAG_EXHAUST`:
Stream the data down full blast in multiple "reply" packets.
Faster when you are pulling down a lot of data and you know you want to retrieve it all.
`Mongoc.QUERY_FLAG_PARTIAL`:
Get partial results from mongos if some shards are down (instead of throwing an error).
"""
primitive type QueryFlags sizeof(Cint) * 8 end
"""
Adds one or more flags to the `FindAndModifyOptsBuilder`.
These flags can be *ORed* together,
as in `flags = Mongoc.FIND_AND_MODIFY_FLAG_UPSERT | Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW`.
* `FIND_AND_MODIFY_FLAG_NONE`: Default. Doesn’t add anything to the builder.
* `FIND_AND_MODIFY_FLAG_REMOVE`: Will instruct find_and_modify to remove the matching document.
* `FIND_AND_MODIFY_FLAG_UPSERT`: Update the matching document or, if no document matches, insert the document.
* `FIND_AND_MODIFY_FLAG_RETURN_NEW`: Return the resulting document.
"""
primitive type FindAndModifyFlags sizeof(Cint) * 8 end
const QueryOrFindAndModifyFlags = Union{QueryFlags, FindAndModifyFlags}
Base.convert(::Type{T}, t::QueryOrFindAndModifyFlags) where {T<:Number} = reinterpret(Cint, t)
Base.convert(::Type{Q}, n::T) where {Q<:QueryOrFindAndModifyFlags, T<:Number} = reinterpret(Q, n)
Cint(flags::QueryOrFindAndModifyFlags) = convert(Cint, flags)
Base.:(|)(flag1::T, flag2::T) where {T<:QueryOrFindAndModifyFlags} = T( Cint(flag1) | Cint(flag2) )
Base.:(&)(flag1::T, flag2::T) where {T<:QueryOrFindAndModifyFlags} = T( Cint(flag1) & Cint(flag2) )
QueryFlags(u::Cint) = convert(QueryFlags, u)
QueryFlags(i::Number) = QueryFlags(Cint(i))
Base.show(io::IO, flags::QueryFlags) = print(io, "QueryFlags($(Cint(flags)))")
FindAndModifyFlags(u::Cint) = convert(FindAndModifyFlags, u)
FindAndModifyFlags(i::Number) = FindAndModifyFlags(Cint(i))
Base.show(io::IO, flags::FindAndModifyFlags) = print(io, "FindAndModifyFlags($(Cint(flags)))")
const QUERY_FLAG_NONE = QueryFlags(0)
const QUERY_FLAG_TAILABLE_CURSOR = QueryFlags(1 << 1)
const QUERY_FLAG_SLAVE_OK = QueryFlags(1 << 2)
const QUERY_FLAG_OPLOG_REPLAY = QueryFlags(1 << 3)
const QUERY_FLAG_NO_CURSOR_TIMEOUT = QueryFlags(1 << 4)
const QUERY_FLAG_AWAIT_DATA = QueryFlags(1 << 5)
const QUERY_FLAG_EXHAUST = QueryFlags(1 << 6)
const QUERY_FLAG_PARTIAL = QueryFlags(1 << 7)
const FIND_AND_MODIFY_FLAG_NONE = FindAndModifyFlags(0)
const FIND_AND_MODIFY_FLAG_REMOVE = FindAndModifyFlags(1 << 0)
const FIND_AND_MODIFY_FLAG_UPSERT = FindAndModifyFlags(1 << 1)
const FIND_AND_MODIFY_FLAG_RETURN_NEW = FindAndModifyFlags(1 << 2)
# `URI` is a wrapper for C struct `mongoc_uri_t`."
mutable struct URI
uri::String
handle::Ptr{Cvoid}
function URI(uri_string::String)
err_ref = Ref{BSONError}()
handle = mongoc_uri_new_with_error(uri_string, err_ref)
if handle == C_NULL
throw(err_ref[])
end
new_uri = new(uri_string, handle)
finalizer(destroy!, new_uri)
return new_uri
end
end
mutable struct ClientPool
uri::String
handle::Ptr{Cvoid}
function ClientPool(uri::URI; max_size::Union{Nothing, Integer}=nothing)
client_pool_handle = mongoc_client_pool_new(uri.handle)
@assert client_pool_handle != C_NULL "Failed to create client pool from URI $(uri.uri)."
client_pool = new(uri.uri, client_pool_handle)
finalizer(destroy!, client_pool)
if max_size != nothing
set_max_size(client_pool, max_size)
end
return client_pool
end
end
# `Client` is a wrapper for C struct `mongoc_client_t`.
mutable struct Client{T<:Union{Nothing, ClientPool}}
uri::String
handle::Ptr{Cvoid}
pool::T
end
function Client(uri::URI)
client_handle = mongoc_client_new_from_uri(uri.handle)
@assert client_handle != C_NULL "Failed to create client handle from URI $(uri.uri)."
client = Client(uri.uri, client_handle, nothing)
finalizer(destroy!, client)
return client
end
function Client(pool::ClientPool; try_pop::Bool=false, pop_timeout_secs::Real=10.0)
local client_handle::Ptr{Cvoid}
if try_pop
client_handle = mongoc_client_pool_try_pop(pool.handle)
else
# NOTE: The blocking mongoc_client_pop() can deadlock the process
# during GC, see https://github.com/felipenoris/Mongoc.jl/issues/84.
# Would prefer to use @threadcall to avoid this issue, but
# that appears to generate exceptions
# (see https://github.com/felipenoris/Mongoc.jl/issues/84#issuecomment-926433352).
# Periodically polling as a temporary workaround.
waiting_time = 0.0
sleep_period = 0.01
while true
client_handle = mongoc_client_pool_try_pop(pool.handle)
client_handle != C_NULL && break
sleep(sleep_period)
waiting_time += sleep_period
if waiting_time > pop_timeout_secs
error("Failed to create client handle from Pool.")
end
end
end
@assert client_handle != C_NULL "Failed to create client handle from Pool."
client = Client(pool.uri, client_handle, pool)
finalizer(destroy!, client)
return client
end
abstract type AbstractDatabase end
abstract type AbstractCollection end
# `Database` is a wrapper for C struct `mongoc_database_t`.
mutable struct Database <: AbstractDatabase
client::Client
name::String
handle::Ptr{Cvoid}
function Database(client::Client, db_name::String)
db = new(client, db_name, mongoc_client_get_database(client.handle, db_name))
finalizer(destroy!, db)
return db
end
end
mutable struct Bucket
database::Database
handle::Ptr{Cvoid}
function Bucket(database::Database; options::Union{Nothing, BSON}=nothing)
options_handle = options == nothing ? C_NULL : options.handle
err_ref = Ref{BSONError}()
gridfs_handle = mongoc_gridfs_bucket_new(database.handle,
options_handle,
C_NULL, err_ref)
if gridfs_handle == C_NULL
throw(err_ref[])
end
gridfs = new(database, gridfs_handle)
finalizer(destroy!, gridfs)
return gridfs
end
end
# `Collection` is a wrapper for C struct `mongoc_collection_t`.
mutable struct Collection <: AbstractCollection
database::Database
name::String
handle::Ptr{Cvoid}
function Collection(database::Database, collection_name::String)
collection_handle = mongoc_database_get_collection(database.handle, collection_name)
@assert collection_handle != C_NULL "Failed to create a collection handle to $collection_name on db $(database.name)."
collection = new(database, collection_name, collection_handle)
finalizer(destroy!, collection)
return collection
end
end
const CursorSource = Union{Client, AbstractDatabase, AbstractCollection, Bucket}
# `Cursor` is a wrapper for C struct `mongoc_cursor_t`.
mutable struct Cursor{T<:CursorSource}
source::T
handle::Ptr{Cvoid}
function Cursor(source::T, handle::Ptr{Cvoid}) where {T<:CursorSource}
cursor = new{T}(source, handle)
finalizer(destroy!, cursor)
return cursor
end
end
function batch_size(cursor::Cursor)
cursor.handle != C_NULL || error("Cursor destroyed")
GC.@preserve cursor mongoc_cursor_get_batch_size(cursor.handle)
end
function batch_size!(cursor::Cursor, batch_size::Integer)
cursor.handle != C_NULL || error("Cursor destroyed")
GC.@preserve cursor mongoc_cursor_set_batch_size(cursor.handle, batch_size)
end
mutable struct BulkOperation
collection::Collection
handle::Ptr{Cvoid}
executed::Bool
function BulkOperation(collection::Collection; options::Union{Nothing, BSON}=nothing)
options_handle = options == nothing ? C_NULL : options.handle
handle = mongoc_collection_create_bulk_operation_with_opts(collection.handle, options_handle)
@assert handle != C_NULL "Failed to create a bulk operation handle."
bulk_operation = new(collection, handle, false)
finalizer(destroy!, bulk_operation)
return bulk_operation
end
end
struct InsertOneResult{T}
reply::BSON
inserted_oid::T
end
struct BulkOperationResult{T}
reply::BSON
server_id::UInt32
inserted_oids::Vector{T}
end
#
# Basic functions for types
#
function destroy!(uri::URI)
if uri.handle != C_NULL
mongoc_uri_destroy(uri.handle)
uri.handle = C_NULL
end
nothing
end
function destroy!(client::Client{Nothing})
if client.handle != C_NULL
mongoc_client_destroy(client.handle)
client.handle = C_NULL
end
nothing
end
function destroy!(client::Client{ClientPool})
if client.handle != C_NULL
mongoc_client_pool_push(client.pool.handle, client.handle)
client.handle = C_NULL
end
nothing
end
function destroy!(client_pool::ClientPool)
if client_pool.handle != C_NULL
mongoc_client_pool_destroy(client_pool.handle)
client_pool.handle = C_NULL
end
nothing
end
function destroy!(database::Database)
if database.handle != C_NULL
mongoc_database_destroy(database.handle)
database.handle = C_NULL
end
nothing
end
function destroy!(gridfs::Bucket)
if gridfs.handle != C_NULL
mongoc_gridfs_bucket_destroy(gridfs.handle)
gridfs.handle = C_NULL
end
end
function destroy!(collection::Collection)
if collection.handle != C_NULL
mongoc_collection_destroy(collection.handle)
collection.handle = C_NULL
end
nothing
end
function destroy!(cursor::Cursor)
if cursor.handle != C_NULL
mongoc_cursor_destroy(cursor.handle)
cursor.handle = C_NULL
end
nothing
end
function destroy!(bulk_operation::BulkOperation)
if bulk_operation.handle != C_NULL
mongoc_bulk_operation_destroy(bulk_operation.handle)
bulk_operation.handle = C_NULL
bulk_operation.executed = true
end
nothing
end
#
# Session Types
#
mutable struct SessionOptions
handle::Ptr{Cvoid}
function SessionOptions(; casual_consistency::Bool=true)
session_options_handle = mongoc_session_opts_new()
@assert session_options_handle != C_NULL "Failed to create session options handle."
session_options = new(session_options_handle)
finalizer(destroy!, session_options)
set_casual_consistency!(session_options, casual_consistency)
return session_options
end
end
mutable struct Session
client::Client
options::SessionOptions
handle::Ptr{Cvoid}
function Session(client::Client; options::SessionOptions=SessionOptions())
err_ref = Ref{BSONError}()
session_handle = mongoc_client_start_session(client.handle, options.handle, err_ref)
if session_handle == C_NULL
throw(err_ref[])
end
session = new(client, options, session_handle)
finalizer(destroy!, session)
return session
end
end
struct DatabaseSession <: AbstractDatabase
database::Database
session::Session
end
struct CollectionSession <: AbstractCollection
database_session::DatabaseSession
collection::Collection
end
#=
struct BulkOperationSession
collection_session::CollectionSession
bulk_operation::BulkOperation
function BulkOperationSession(collection_session::CollectionSession, options::Union{Nothing, BSON})
options_with_session = _join(options, get_session(collection_session))
bulk_operation = BulkOperation(collection_session.collection, options=options_with_session)
return BulkOperationSession(collection_session, bulk_operation)
end
end
=#
function destroy!(session_options::SessionOptions)
if session_options.handle != C_NULL
mongoc_session_opts_destroy(session_options.handle)
session_options.handle = C_NULL
end
nothing
end
function destroy!(session::Session)
if session.handle != C_NULL
mongoc_client_session_destroy(session.handle)
session.handle = C_NULL
end
nothing
end
mutable struct FindAndModifyOptsBuilder
handle::Ptr{Cvoid}
function FindAndModifyOptsBuilder(;
update::Union{Nothing, BSON}=nothing,
sort::Union{Nothing, BSON}=nothing,
fields::Union{Nothing, BSON}=nothing,
flags::Union{Nothing, FindAndModifyFlags}=nothing,
bypass_document_validation::Bool=false,
)
opts = new(mongoc_find_and_modify_opts_new())
finalizer(destroy!, opts)
if update != nothing
opts.update = update
end
if sort != nothing
opts.sort = sort
end
if fields != nothing
opts.fields = fields
end
if flags != nothing
opts.flags = flags
end
opts.bypass_document_validation = bypass_document_validation
return opts
end
end
function destroy!(opts::FindAndModifyOptsBuilder)
if opts.handle != C_NULL
mongoc_find_and_modify_opts_destroy(opts.handle)
opts.handle = C_NULL
end
nothing
end
#
# Streams
#
"""
# Interface
## Mutable fields
* `handle::Ptr{Cvoid}`
* `isopen::Bool`
* `timeout_msec::Int`
* `chunk_size::UInt`
"""
abstract type AbstractMongoStream <: IO end
function destroy!(stream::AbstractMongoStream)
if stream.handle != C_NULL
mongoc_stream_destroy(stream.handle)
stream.handle = C_NULL
end
end
# 30sec
const DEFAULT_TIMEOUT_MSEC = 30000
# 56kb of chunk size when reading from streams
const DEFAULT_CHUNK_SIZE = 56 * 1024
mutable struct MongoStreamFile{T} <: AbstractMongoStream
owner::T
handle::Ptr{Cvoid}
isopen::Bool
timeout_msec::Int
chunk_size::UInt
function MongoStreamFile(owner::T, handle::Ptr{Cvoid};
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE
) where {T}
@assert handle != C_NULL
stream = new{T}(owner, handle, true, Int(timeout_msec), UInt(chunk_size))
finalizer(destroy!, stream)
return stream
end
end
mutable struct MongoIOStream{T} <: AbstractMongoStream
owner::T
handle::Ptr{Cvoid}
isopen::Bool
timeout_msec::Int
chunk_size::UInt
function MongoIOStream(owner::T, handle::Ptr{Cvoid};
timeout_msec::Integer=DEFAULT_TIMEOUT_MSEC,
chunk_size::Integer=DEFAULT_CHUNK_SIZE
) where {T}
@assert handle != C_NULL
stream = new{T}(owner, handle, true, Int(timeout_msec), UInt(chunk_size))
finalizer(destroy!, stream)
return stream
end
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 19213 |
import Mongoc
import Base.UUID
using Test
using Dates
using DecFP
using Distributed
@testset "BSON" begin
@testset "as_json" begin
@test_throws ErrorException Mongoc.BSON(""" { ajskdla sdjsafd } """)
bson = Mongoc.BSON("""{"hey" : 1}""")
@test bson["hey"] == 1
@test Mongoc.as_json(bson) == """{ "hey" : 1 }"""
@test Mongoc.as_json(bson, canonical=true) == """{ "hey" : { "\$numberInt" : "1" } }"""
end
@testset "oid conversion" begin
str = "5b9fb22b3192e3fa155693a1"
local oid::Mongoc.BSONObjectId = str
@test String(oid) == str
end
@testset "oid compare" begin
x = Mongoc.BSONObjectId()
y = Mongoc.BSONObjectId()
@test x != y
@test x == x
@test y == y
@test hash(x) == hash(x)
@test hash(y) == hash(y)
@test hash(x) != hash(y)
@test Mongoc.bson_oid_compare(x, y) < 0
@test Mongoc.bson_oid_compare(y, x) > 0
@test Mongoc.bson_oid_compare(x, x) == 0
@test Mongoc.bson_oid_compare(y, y) == 0
end
@testset "oid copy" begin
x = Mongoc.BSONObjectId()
y = copy(x)
@test x == y
@test hash(x) == hash(y)
@test Mongoc.bson_oid_compare(x, y) == 0
end
@testset "oid string" begin
x = Mongoc.BSONObjectId()
y = Mongoc.BSONObjectId(String(x))
@test x == y
@test_throws ErrorException Mongoc.BSONObjectId("invalid_objectid")
end
@testset "oid time" begin
Mongoc.get_time( Mongoc.BSONObjectId("5b9eaa2711c3dd0d6a46a5c4") ) == DateTime(2018, 9, 16, 19, 8, 23) # 2018-09-16T19:08:23
end
@testset "BSONObjectId segfault issue (#2)" begin
io = IOBuffer()
v = Vector{Mongoc.BSONObjectId}()
for i in 1:5
push!(v, Mongoc.BSONObjectId())
end
show(io, v)
end
@testset "oid sort" begin
v = Vector{Mongoc.BSONObjectId}()
for i in 1:10_000
push!(v, Mongoc.BSONObjectId())
end
@test length(v) == length(unique(v))
v_sorted = sort(v, lt = (a,b) -> Mongoc.bson_oid_compare(a,b) < 0)
@test v_sorted == v
end
@testset "AbstractString support" begin
keys_with_prefix = ["aKey1", "aKey2", "aKey3"]
substring_keys = [ SubString(k, 2, length(k)) for k in keys_with_prefix ]
vals = [ 1, "hey", nothing ]
bson = Mongoc.BSON()
for (i, k) in enumerate(substring_keys)
bson[k] = vals[i]
end
for k in substring_keys
@test haskey(bson, k)
end
for i in 1:3
@test haskey(bson, "Key$i")
end
bson["ah"] = substring_keys[1]
@test isa(bson["ah"], String)
@test bson["ah"] == "Key1"
end
@testset "UUID support" begin
uuid = UUID("a1f18b06-2210-499b-8313-28e69090511f")
bson = Mongoc.BSON("uuid" => uuid)
@test isa(bson["uuid"], UUID)
@test bson["uuid"] == uuid
end
@testset "BSON key/values itr support" begin
bson = Mongoc.BSON()
bson["hey"] = 10
bson["you"] = "aaa"
bson["out"] = nothing
@test ["hey" => 10, "you" => "aaa", "out" => nothing] == [k => v for (k, v) in bson]
@test ["hey" => 10, "you" => "aaa", "out" => nothing] == collect(pairs(bson))
@test ["hey", "you", "out"] == collect(keys(bson))
@test [10, "aaa", nothing] == collect(values(bson))
end
@testset "BSON Iterator" begin
doc = Mongoc.BSON("""{ "a" : 1, "b" : 2.2, "str" : "my string", "bool_t" : true, "bool_f" : false, "array" : [1, 2, false, "inner_string"], "float_array" : [0.1, 0.2, 0.3, 0.4], "document" : { "a" : 1, "b" : "b_string"}, "null" : null }""")
new_id = Mongoc.BSONObjectId()
doc["_id"] = new_id
@test haskey(doc, "a")
@test haskey(doc, "b")
@test !haskey(doc, "c")
@test haskey(doc, "str")
@test haskey(doc, "_id")
@test haskey(doc, "array")
@test haskey(doc, "float_array")
@test haskey(doc, "document")
@test haskey(doc, "null")
@test doc["a"] == 1
@test doc["b"] == 2.2
@test doc["str"] == "my string"
@test doc["bool_t"]
@test !doc["bool_f"]
@test doc["_id"] == new_id
@test doc["array"] == [1, 2, false, "inner_string"]
@test doc["document"] == Dict("a"=>1, "b"=>"b_string")
@test doc["null"] == nothing
@test_throws KeyError doc["invalid key"]
@test isequal(get(doc, "invalid key", missing), missing)
@test get(doc, "_id", missing) == new_id
doc_dict = Mongoc.as_dict(doc)
@test keytype(doc_dict) === String
@test doc_dict["a"] == 1
@test doc_dict["b"] == 2.2
@test doc_dict["str"] == "my string"
@test doc_dict["bool_t"]
@test !doc_dict["bool_f"]
@test doc_dict["_id"] == new_id
@test doc_dict["array"] == [1, 2, false, "inner_string"]
@test doc_dict["document"] == Dict("a"=>1, "b"=>"b_string")
@test doc_dict["null"] == nothing
@testset "convert(Dict, BSON)" begin
doc_dict2 = @inferred(convert(Dict, doc))
@test doc_dict2 == doc_dict
doc_dict3 = @inferred(convert(Dict{String, Any}, doc))
@test doc_dict3 == doc_dict
end
# Type-stable API
@test @inferred(Mongoc.get_array(doc, "float_array", Float64)) == [0.1, 0.2, 0.3, 0.4]
@test @inferred(Mongoc.get_array(doc, "float_array", Float32)) == Float32[0.1, 0.2, 0.3, 0.4]
@test_throws MethodError Mongoc.get_array(doc, "float_array", String)
@test_throws ErrorException Mongoc.get_array(doc, "document", Any)
end
@testset "BSON write" begin
bson = Mongoc.BSON()
new_oid = Mongoc.BSONObjectId()
bson["_id"] = new_oid
bson["int32"] = Int32(10)
bson["int64"] = Int64(20)
bson["string"] = "hey you"
bson["bool_true"] = true
bson["bool_false"] = false
bson["double"] = 2.3
bson["decimal128"] = d128"1.2"
bson["datetime"] = DateTime(2018, 2, 1, 10, 20, 35, 10)
bson["vector"] = collect(1:10)
bson["source"] = Mongoc.BSONCode("function() = 1")
bson["null"] = nothing
@test_throws ErrorException bson["key"] = Date(2018, 9, 18)
str = "the real string"
sub = SubString(str, 4, 7)
bson["substring"] = sub
let
sub_bson = Mongoc.BSON()
sub_bson["hey"] = "you"
sub_bson["num"] = 10
bson["sub_document"] = sub_bson
end
@test bson["_id"] == new_oid
@test bson["int32"] == Int32(10)
@test bson["int64"] == Int64(20)
@test bson["string"] == "hey you"
@test bson["bool_true"]
@test !bson["bool_false"]
@test bson["double"] == 2.3
@test bson["decimal128"] == d128"1.2"
@test bson["datetime"] == DateTime(2018, 2, 1, 10, 20, 35, 10)
@test bson["sub_document"]["hey"] == "you"
@test bson["sub_document"]["num"] == 10
@test bson["vector"] == collect(1:10)
@test bson["source"] == Mongoc.BSONCode("function() = 1")
@test bson["null"] == nothing
@test bson["substring"] == sub
let
sub_bson = bson["sub_document"]
@test sub_bson["hey"] == "you"
@test sub_bson["num"] == 10
end
end
@testset "BSON to Dict conversion" begin
dict = Dict("a" => 1, "b" => false, "c" => "string", "d" => nothing)
doc = Mongoc.BSON(dict)
@test doc["a"] == 1
@test doc["b"] == false
@test doc["c"] == "string"
@test doc["d"] == nothing
@test dict == Mongoc.as_dict(doc)
@test dict == Dict(doc)
@test dict == Dict{String, Any}(doc)
@test dict == convert(Dict, doc)
@test dict == convert(Dict{String, Any}, doc)
end
@testset "BSON Dict API" begin
doc = Mongoc.BSON("a" => 1, "b" => false, "c" => "string", "d" => nothing)
@test doc["a"] == 1
@test doc["b"] == false
@test doc["c"] == "string"
@test doc["d"] == nothing
for (key, value) in doc
if key == "a"
@test value == 1
elseif key == "b"
@test value == false
elseif key == "c"
@test value == "string"
elseif key == "d"
@test value == nothing
else
# test fails
@test false
end
end
end
@testset "BSON copy" begin
@testset "exclude one key" begin
src = Mongoc.BSON("hey" => "you", "out" => 1)
dst = Mongoc.BSON()
Mongoc.bson_copy_to_excluding_noinit(src.handle, dst.handle, "out")
@test !haskey(dst, "out")
@test dst["hey"] == "you"
end
@testset "no exclude keys" begin
src = Mongoc.BSON("hey" => "you", "out" => 1)
dst = Mongoc.BSON()
Mongoc.bson_copy_to_noinit(src.handle, dst.handle)
@test Mongoc.as_dict(src) == Mongoc.as_dict(dst)
end
end
@testset "BSON Write to IO" begin
@testset "write_bson closure" begin
io = IOBuffer()
Mongoc.bson_writer(io, initial_buffer_capacity=1) do writer
Mongoc.write_bson(writer) do bson
bson["id"] = 10
bson["str"] = "aa"
end
end
@test io.data == [0x1d,0x00,0x00,0x00,0x12,0x69,0x64,0x00,0x0a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x73,0x74,0x72,0x00,0x03,0x00,0x00,0x00,0x61,0x61,0x00,0x00,0x00,0x00,0x00]
end
@testset "BSON copy single doc" begin
src = Mongoc.BSON("id" => 10, "str" => "aa")
io = IOBuffer()
Mongoc.write_bson(io, src)
@test io.data == [0x1d,0x00,0x00,0x00,0x12,0x69,0x64,0x00,0x0a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x73,0x74,0x72,0x00,0x03,0x00,0x00,0x00,0x61,0x61,0x00,0x00,0x00,0x00,0x00]
end
@testset "BSON copy doc list" begin
list = Vector{Mongoc.BSON}()
let
src = Mongoc.BSON("id" => 1, "name" => "1st")
push!(list, src)
end
let
src = Mongoc.BSON("id" => 2, "name" => "2nd")
push!(list, src)
end
io = IOBuffer()
Mongoc.write_bson(io, list)
seekstart(io)
vec_bson = Mongoc.read_bson(io)
@test length(vec_bson) == 2
let
fst_bson = vec_bson[1]
@test fst_bson["id"] == 1
@test fst_bson["name"] == "1st"
end
let
sec_bson = vec_bson[2]
@test sec_bson["id"] == 2
@test sec_bson["name"] == "2nd"
end
seekstart(io)
reader = Mongoc.BSONReader(read(io))
vec_bson_from_reader = collect(reader)
let
fst_bson = vec_bson_from_reader[1]
@test fst_bson["id"] == 1
@test fst_bson["name"] == "1st"
end
let
sec_bson = vec_bson_from_reader[2]
@test sec_bson["id"] == 2
@test sec_bson["name"] == "2nd"
end
end
@testset "read BSON from data" begin
vec_bson = Mongoc.read_bson([0x1d,0x00,0x00,0x00,0x12,0x69,0x64,0x00,0x0a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x73,0x74,0x72,0x00,0x03,0x00,0x00,0x00,0x61,0x61,0x00,0x00,0x00,0x00,0x00])
@test length(vec_bson) == 1
bson = vec_bson[1]
@test bson["id"] == 10
@test bson["str"] == "aa"
end
@testset "read/write BSON to/from File" begin
filepath = joinpath(@__DIR__, "data.bson")
isfile(filepath) && rm(filepath)
list = Vector{Mongoc.BSON}()
let
src = Mongoc.BSON("id" => 1, "name" => "1st")
push!(list, src)
end
let
src = Mongoc.BSON("id" => 2, "name" => "2nd")
push!(list, src)
end
try
open(filepath, "w") do io
Mongoc.write_bson(io, list)
end
@test isfile(filepath)
reader = Mongoc.BSONReader(filepath)
for (i, bson) in enumerate(reader)
if i == 1
@test bson["id"] == 1
@test bson["name"] == "1st"
elseif i == 2
@test bson["id"] == 2
@test bson["name"] == "2nd"
else
error("Got document $i.")
end
end
Mongoc.destroy!(reader)
finally
if isfile(filepath)
try
rm(filepath)
catch err
@warn("Failed to remove test file $filepath: $(err.msg)")
stacktrace(catch_backtrace())
end
end
end
end
end
@testset "BSONJSONReader" begin
@testset "Iterate Reader" begin
fp = joinpath(@__DIR__, "docs.json")
@assert isfile(fp)
reader = Mongoc.BSONJSONReader(fp)
for (i, bson) in enumerate(reader)
if i == 1
@test bson["num"] == 1
@test bson["str"] == "two"
elseif i == 2
@test bson["num"] == 2
@test bson["str"] == "three"
else
error("Got bson $i.")
end
end
Mongoc.destroy!(reader)
end
@testset "read_bson_from_json" begin
fp = joinpath(@__DIR__, "docs.json")
@assert isfile(fp)
for (i, bson) in enumerate(Mongoc.read_bson_from_json(fp))
if i == 1
@test bson["num"] == 1
@test bson["str"] == "two"
elseif i == 2
@test bson["num"] == 2
@test bson["str"] == "three"
else
error("Got bson $i.")
end
end
end
end
@testset "BSONError" begin
err = Mongoc.BSONError(0x00000005, 0x00000101, (0x54, 0x6f, 0x74, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x7a, 0x65, 0x20, 0x6f,
0x66, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x20, 0x62, 0x65, 0x20, 0x6c, 0x65, 0x73, 0x73, 0x20, 0x74, 0x68, 0x61, 0x6e, 0x20, 0x31,
0x36, 0x37, 0x39, 0x33, 0x36, 0x30, 0x30, 0x2e, 0x20, 0x41, 0x63, 0x74, 0x75, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x7a, 0x65, 0x20, 0x69, 0x73, 0x20,
0x31, 0x36, 0x37, 0x39, 0x34, 0x31, 0x37, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00))
str = sprint(show, err)
@test str == "BSONError: domain=5, code=257, message=Total size of all transaction operations must be less than 16793600. Actual size is 16794174"
@test sprint(showerror, err) == str
end
@testset "serialize" begin
@testset "BufferedBSON" begin
bson = Mongoc.BSON("a" => 1)
x = Mongoc.BufferedBSON(bson)
bson_copy = Mongoc.BSON(x)
@test bson_copy["a"] == 1
end
addprocs(1)
@everywhere using Mongoc
@testset "serialize BufferedBSON" begin
f = @spawn Mongoc.BufferedBSON(Mongoc.BSON("a" => 1))
bson = Mongoc.BSON(fetch(f))
@test bson["a"] == 1
end
@testset "read/write single BSON" begin
doc = Mongoc.BSON("a" => 1)
io = IOBuffer()
write(io, doc)
seekstart(io)
doc2 = read(io, Mongoc.BSON)
@test doc2["a"] == 1
end
@testset "Serialize BSON" begin
f = @spawn Mongoc.BSON("a" => 1)
bson = fetch(f)
@test bson["a"] == 1
end
end
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 39394 |
#
# Tests depend on a running server at localhost:27017,
# and will create a database named "mongoc".
#
# Start a fresh MongoDB instance with:
#
# ```
# $ mkdir db
# $ mongod --dbpath ./db
# ```
#
import Mongoc
using Test
using Dates
const DB_NAME = "mongoc"
@testset "MongoDB" begin
client = Mongoc.Client()
@testset "Destroy" begin
cli = Mongoc.Client()
db = cli["database"]
coll = db["collection"]
Mongoc.destroy!(coll)
Mongoc.destroy!(db)
Mongoc.destroy!(cli)
end
@testset "Types" begin
bson = Mongoc.BSON()
@test_throws Mongoc.BSONError Mongoc.Client("////invalid-url")
try
Mongoc.Client("////invalid-url")
catch err
@test isa(err, Mongoc.BSONError)
io = IOBuffer()
showerror(io, err)
end
@test client.uri == "mongodb://localhost:27017"
Mongoc.set_appname!(client, "Runtests")
db = client[DB_NAME]
coll = db["new_collection"]
io = IOBuffer()
show(io, bson)
show(io, client)
show(io, db)
show(io, coll)
show(io, Mongoc.BSONCode("function() = 1"))
show(io, Mongoc.QUERY_FLAG_TAILABLE_CURSOR)
end
@testset "Connection" begin
@testset "ping" begin
bson_ping_result = Mongoc.ping(client)
@test haskey(bson_ping_result, "ok")
@test Mongoc.as_json(Mongoc.ping(client)) == """{ "ok" : 1.0 }"""
end
@testset "Server Status" begin
bson_server_status = Mongoc.command_simple(client["admin"], Mongoc.BSON("""{ "serverStatus" : 1 }"""))
println("Server Mongo Version: ", bson_server_status["version"])
end
@testset "error print" begin
error_happened = false
try
Mongoc.command_simple(client["hey"], Mongoc.BSON("""{ "you" : 1 }"""))
catch e
println(IOBuffer(), e)
error_happened = true
end
@test error_happened
end
@testset "new_collection" begin
coll = client[DB_NAME]["new_collection"]
@testset "Insert One with generated OID" begin
io = IOBuffer()
result = push!(coll, Mongoc.BSON("""{ "hello" : "world" }"""))
@test isa(result, Mongoc.InsertOneResult)
show(io, result)
@test result.inserted_oid != nothing
first_inserted_oid = result.inserted_oid
@test Mongoc.as_json(result.reply) == """{ "insertedCount" : 1 }"""
result = push!(coll, Mongoc.BSON("""{ "hey" : "you" }"""))
show(io, result)
@test result.inserted_oid != nothing
@test result.inserted_oid != first_inserted_oid
@test Mongoc.as_json(result.reply) == """{ "insertedCount" : 1 }"""
end
@testset "Insert One with custom OID" begin
io = IOBuffer()
bson = Mongoc.BSON("_id" => 123, "out" => "there")
result = push!(coll, bson)
show(io, result)
@test result.inserted_oid == nothing
@test Mongoc.as_json(result.reply) == """{ "insertedCount" : 1 }"""
end
bson = Mongoc.BSON()
bson["hey"] = "you"
bson["zero_date"] = DateTime(0)
bson["date_2018"] = DateTime(2018)
result = push!(coll, bson)
@test Mongoc.as_json(result.reply) == """{ "insertedCount" : 1 }"""
i = 0
for bson in coll
@test haskey(bson, "hello") || haskey(bson, "hey") || haskey(bson, "out")
@test haskey(bson, "_id")
i += 1
end
@test i == length(coll)
i = 0
for bson in Mongoc.find(coll, Mongoc.BSON("""{ "hello" : "world" }"""))
i += 1
end
@test i == 1
@testset "cursor in comprehension" begin
bsons = [bson for bson in Mongoc.find(coll, Mongoc.BSON("""{ "hello" : "world" }"""))]
@test length(bsons) == 1
@test eltype(bsons) == Mongoc.BSON
end
@testset "collection in comprehension" begin
bsons = [bson for bson in coll]
@test length(bsons) == 4
@test eltype(bsons) == Mongoc.BSON
end
@testset "collection command_simple" begin
result = Mongoc.command_simple(coll, Mongoc.BSON("""{ "collStats" : "new_collection" }"""))
@test result["ok"] == 1
end
empty!(coll)
end
@testset "find_databases" begin
found = false
for obj in Mongoc.find_databases(client)
if obj["name"] == DB_NAME
found = true
end
end
@test found
@test DB_NAME ∈ Mongoc.get_database_names(client)
end
@testset "catch cursor error" begin
# issue #15
invalid_client = Mongoc.Client("mongodb://invalid_url")
collection = invalid_client["db_name"]["collection_name"]
@test_throws Mongoc.BSONError Mongoc.find_one(collection, Mongoc.BSON(""" { "a" : 1 } """))
end
@testset "cursor batch size" begin
collection = client[DB_NAME]["batch_size_test"]
cursor = Mongoc.find(collection)
@test Mongoc.batch_size(cursor) == 0
Mongoc.batch_size!(cursor, 10)
@test Mongoc.batch_size(cursor) == 10
end
@static if !Sys.iswindows() # skipping binary tests for windows
@testset "Binary data" begin
coll = client[DB_NAME]["new_collection"]
bsonDoc = Mongoc.BSON()
testdata = rand(UInt8, 100)
bsonDoc["someId"] = "1234"
bsonDoc["bindata"] = testdata
result = push!(coll, bsonDoc)
@test Mongoc.as_json(result.reply) == """{ "insertedCount" : 1 }"""
# read data out and confirm
selector = Mongoc.BSON("""{ "someId": "1234" }""")
results = Mongoc.find_one(coll, selector)
@test results["bindata"] == testdata
end
end
@testset "find_collections" begin
for obj in Mongoc.find_collections(client["local"])
@test obj["name"] == "startup_log"
end
@test Mongoc.get_collection_names(client["local"]) == [ "startup_log" ]
end
@testset "BulkOperation" begin
coll = client[DB_NAME]["new_collection"]
bulk_operation = Mongoc.BulkOperation(coll)
Mongoc.destroy!(bulk_operation)
bulk_2 = Mongoc.BulkOperation(coll) # will be freed by GC
end
@testset "Cleanup" begin
coll = client[DB_NAME]["new_collection"]
Mongoc.drop(coll)
end
@testset "insert_many" begin
collection = client[DB_NAME]["insert_many"]
vector = Vector{Mongoc.BSON}()
push!(vector, Mongoc.BSON("""{ "hey" : "you" }"""))
push!(vector, Mongoc.BSON("""{ "out" : "there" }"""))
push!(vector, Mongoc.BSON("""{ "count" : 3 }"""))
result = append!(collection, vector)
@test isa(result, Mongoc.BulkOperationResult)
@test result.reply["nInserted"] == 3
for oid in result.inserted_oids
@test oid != nothing
end
io = IOBuffer()
show(io, result)
@test length(collection) == 3
@test length(collect(collection)) == 3
Mongoc.drop(collection)
end
@testset "bulk_replace_one" begin
collection = client[DB_NAME]["replace_many"]
push!(collection, Mongoc.BSON("""{ "x": 1, "y": 100 }"""))
push!(collection, Mongoc.BSON("""{ "x": 2, "y": 200 }"""))
push!(collection, Mongoc.BSON("""{ "x": 3, "y": 300 }"""))
bulk = Mongoc.BulkOperation(collection)
Mongoc.bulk_replace_one!(
bulk,
Mongoc.BSON("""{ "x": 1 }"""),
Mongoc.BSON("""{ "x": 1, "y": -100 }"""),
)
Mongoc.bulk_replace_one!(
bulk,
Mongoc.BSON("""{ "x": 2 }"""),
Mongoc.BSON("""{ "x": 2, "y": -200 }"""),
)
Mongoc.bulk_replace_one!(
bulk,
Mongoc.BSON("""{ "x": 4 }"""),
Mongoc.BSON("""{ "x": 4, "y": 400 }""");
options = Mongoc.BSON("""{ "upsert": true }""")
)
result = Mongoc.execute!(bulk)
@test result.reply["nInserted"] == 0
@test result.reply["nMatched"] == 2
@test result.reply["nModified"] == 2
@test result.reply["nUpserted"] == 1
@test length(collection) == 4
@test length(collect(collection)) == 4
Mongoc.drop(collection)
end
@testset "bulk_update_one" begin
collection = client[DB_NAME]["bulk_update_one"]
push!(collection, Mongoc.BSON("""{ "x": 1, "y": 100 }"""))
push!(collection, Mongoc.BSON("""{ "x": 2, "y": 200 }"""))
bulk = Mongoc.BulkOperation(collection)
Mongoc.bulk_update_one!(
bulk,
Mongoc.BSON("""{ "x": 1 }"""),
Mongoc.BSON("""{ "\$set": { "y": 150 } }"""),
)
Mongoc.bulk_update_one!(
bulk,
Mongoc.BSON("""{ "x": 2 }"""),
Mongoc.BSON("""{ "\$inc": { "y": 13 } }"""),
)
result = Mongoc.execute!(bulk)
@test result.reply["nInserted"] == 0
@test result.reply["nMatched"] == 2
@test result.reply["nModified"] == 2
@test result.reply["nUpserted"] == 0
@test length(collection) == 2
@test length(collect(collection)) == 2
x1 = Mongoc.find_one(collection, Mongoc.BSON("x" => 1))
@test x1["x"] == 1
@test x1["y"] == 150
x2 = Mongoc.find_one(collection, Mongoc.BSON("x" => 2))
@test x2["x"] == 2
@test x2["y"] == 213
Mongoc.drop(collection)
end
@testset "delete_one" begin
collection = client[DB_NAME]["delete_one"]
doc = Mongoc.BSON("""{ "to" : "delete", "hey" : "you" }""")
doc2 = Mongoc.BSON("""{ "to" : "keep", "out" : "there" }""")
insert_result = push!(collection, doc)
oid = insert_result.inserted_oid
push!(collection, doc2)
selector = Mongoc.BSON()
selector["_id"] = oid
@test length(collection, selector) == 1
result = Mongoc.delete_one(collection, selector)
@test result["deletedCount"] == 1
@test length(collection, selector) == 0
Mongoc.drop(collection)
end
@testset "delete_many" begin
collection = client[DB_NAME]["delete_many"]
result = append!(collection, [ Mongoc.BSON("""{ "first" : 1, "delete" : true }"""), Mongoc.BSON("""{ "second" : 2, "delete" : true }"""), Mongoc.BSON("""{ "third" : 3, "delete" : false }""") ])
@test length(collection) == 3
result = Mongoc.delete_many(collection, Mongoc.BSON("""{ "delete" : true }"""))
@test result["deletedCount"] == 2
@test length(collection) == 1
result = Mongoc.delete_many(collection, Mongoc.BSON())
@test result["deletedCount"] == 1
@test isempty(collection)
Mongoc.drop(collection)
end
@testset "update_one, update_many" begin
collection = client[DB_NAME]["update_one"]
append!(collection, [ Mongoc.BSON("""{ "first" : 1, "delete" : true }"""), Mongoc.BSON("""{ "second" : 2, "delete" : true }"""), Mongoc.BSON("""{ "third" : 3, "delete" : false }""") ])
@test length(collection) == 3
selector = Mongoc.BSON("""{ "delete" : false }""")
update = Mongoc.BSON("""{ "\$set" : { "delete" : true, "new_field" : 1 } }""")
result = Mongoc.update_one(collection, selector, update)
@test result["modifiedCount"] == 1
@test result["matchedCount"] == 1
@test result["upsertedCount"] == 0
updated_bson = Mongoc.find_one(collection, Mongoc.BSON("""{ "third" : 3 }"""))
@test updated_bson != nothing
@test updated_bson["delete"] == true
@test updated_bson["new_field"] == 1
selector = Mongoc.BSON("""{ "delete" : true }""")
update = Mongoc.BSON("""{ "\$set" : { "delete" : false } }""")
result = Mongoc.update_many(collection, selector, update)
@test result["modifiedCount"] == 3
@test result["matchedCount"] == 3
@test result["upsertedCount"] == 0
for doc in Mongoc.find(collection)
@test doc["delete"] == false
end
@test Mongoc.find_one(collection, Mongoc.BSON("""{ "delete" : true }""")) == nothing
Mongoc.drop(collection)
end
@testset "replace_one" begin
collection = client[DB_NAME]["replace_one"]
append!(collection, [ Mongoc.BSON("""{ "first" : 1, "delete" : true }"""), Mongoc.BSON("""{ "second" : 2, "delete" : true }"""), Mongoc.BSON("""{ "third" : 3, "delete" : false }""") ])
@test length(collection) == 3
selector = Mongoc.BSON("""{ "delete" : false }""")
replacement = Mongoc.BSON("""{ "third" : 3, "new_field" : 1 }""")
result = Mongoc.replace_one(collection, selector, replacement)
@test result["modifiedCount"] == 1
@test result["matchedCount"] == 1
@test result["upsertedCount"] == 0
replaced_bson = Mongoc.find_one(collection, Mongoc.BSON("""{ "third" : 3 }"""))
@test replaced_bson !== nothing
@test !haskey(replaced_bson, "delete")
@test replaced_bson["new_field"] == 1
Mongoc.drop(collection)
end
@testset "aggregation, map_reduce" begin
@testset "QueryFlags" begin
qf_composite = Mongoc.QUERY_FLAG_PARTIAL | Mongoc.QUERY_FLAG_NO_CURSOR_TIMEOUT
@test qf_composite & Mongoc.QUERY_FLAG_PARTIAL == Mongoc.QUERY_FLAG_PARTIAL
@test qf_composite & Mongoc.QUERY_FLAG_NO_CURSOR_TIMEOUT == Mongoc.QUERY_FLAG_NO_CURSOR_TIMEOUT
end
# reproducing the examples at https://docs.mongodb.com/manual/aggregation/
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
database = client[DB_NAME]
collection = database["aggregation_example"]
append!(collection, docs)
@test length(collection) == 4
# Aggregation
let
bson_pipeline = Mongoc.BSON("""
[
{ "\$match" : { "status" : "A" } },
{ "\$group" : { "_id" : "\$cust_id", "total" : { "\$sum" : "\$amount" } } }
]""")
# Response should be
# BSON("{ "_id" : "B212", "total" : 200 }")
# BSON("{ "_id" : "A123", "total" : 750 }")
for doc in Mongoc.aggregate(collection, bson_pipeline)
if doc["_id"] == "A123"
@test doc["total"] == 750
elseif doc["_id"] == "B212"
@test doc["total"] == 200
else
# shouldn't get in here
@test false
end
end
end
# map_reduce
let
input_collection_name = "aggregation_example"
mapper = Mongoc.BSONCode(""" function() { emit( this.cust_id, this.amount ); } """)
reducer = Mongoc.BSONCode(""" function(key, values) { return Array.sum( values ) } """)
output_collection_name = "order_totals"
query = Mongoc.BSON("""{ "status" : "A" }""")
map_reduce_command = Mongoc.BSON()
map_reduce_command["mapReduce"] = input_collection_name
map_reduce_command["map"] = mapper
map_reduce_command["reduce"] = reducer
map_reduce_command["out"] = output_collection_name
map_reduce_command["query"] = query
result = Mongoc.read_command(database, map_reduce_command)
@test result["result"] == "order_totals"
@test result["ok"] == 1.0
for doc in Mongoc.find(database["order_totals"])
if doc["_id"] == "A123"
@test doc["value"] == 750
elseif doc["_id"] == "B212"
@test doc["value"] == 200
else
# shouldn't get in here
@test false
end
end
# Response should be
# BSON("{ "_id" : "A123", "value" : 750.0 }")
# BSON("{ "_id" : "B212", "value" : 200.0 }")
end
Mongoc.drop(collection)
end
end
@testset "find and modify" begin
@testset "create/destroy opts" begin
opts = Mongoc.FindAndModifyOptsBuilder()
Mongoc.destroy!(opts)
end
@testset "set opts" begin
opts = Mongoc.FindAndModifyOptsBuilder()
opts.update = Mongoc.BSON("""{ "\$set" : { "position" : "striker" }}""")
opts.sort = Mongoc.BSON("""{ "age" : -1 }""")
opts.fields = Mongoc.BSON("""{ "goals" : 1 }""")
opts.flags = Mongoc.FIND_AND_MODIFY_FLAG_UPSERT | Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW
end
@testset "main function" begin
collection = client[DB_NAME]["find_and_modify"]
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
append!(collection, docs)
@testset "update simple" begin
query = Mongoc.BSON("amount" => 500)
reply = Mongoc.find_and_modify(
collection,
query,
update = Mongoc.BSON("""{ "\$set" : { "status" : "N" } }"""),
flags = Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW # will return the new version of the document
)
let
modified_doc = reply["value"]
@test modified_doc["status"] == "N"
end
let
modified_doc = Mongoc.find_one(collection, Mongoc.BSON("amount" => 500))
@test modified_doc["status"] == "N"
end
end
@testset "upsert and return new" begin
query = Mongoc.BSON("""{ "cust_id" : "C555", "amount" : 10, "status" : "X" }""")
reply = Mongoc.find_and_modify(
collection,
query,
update = Mongoc.BSON("""{ "\$set" : { "status" : "S" } }"""),
flags = Mongoc.FIND_AND_MODIFY_FLAG_UPSERT | Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW
)
let
new_document = reply["value"]
@test new_document["cust_id"] == "C555"
@test new_document["amount"] == 10
@test new_document["status"] == "S"
end
end
@testset "update sorted with selected fields" begin
query = Mongoc.BSON("""{ "amount" : { "\$lt" : 300 } }""")
update = Mongoc.BSON("""{ "\$set" : { "status" : "Z" } }""")
fields = Mongoc.BSON("""{ "amount" : 1, "status" : 1 }""")
sort = Mongoc.BSON("""{ "amount" : 1 }""")
reply = Mongoc.find_and_modify(
collection,
query,
update=update,
sort=sort,
fields=fields,
flags=Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW)
let
new_document = reply["value"]
@test new_document["amount"] == 10
@test new_document["status"] == "Z"
@test !haskey(new_document, "cust_id")
end
end
Mongoc.drop(collection)
end
end
@testset "find one and delete" begin
collection = client[DB_NAME]["find_one_and_delete"]
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
append!(collection, docs)
@testset "delete by filter" begin
query = Mongoc.BSON("""{ "cust_id" : "B212" }""")
doc = Mongoc.find_one_and_delete(collection, query)
@test !isnothing(doc)
@test doc["cust_id"] == "B212"
@test doc["amount"] == 200
end
@testset "nothing result when not found" begin
query = Mongoc.BSON("""{ "cust_id" : "B212" }""")
doc = Mongoc.find_one_and_delete(collection, query)
@test isnothing(doc)
end
@testset "delete with sort" begin
query = Mongoc.BSON("""{ "cust_id" : "A123" }""")
options = Mongoc.BSON("""{ "sort" : {"amount" : 1 } }""")
doc = Mongoc.find_one_and_delete(collection, query, options=options)
@test !isnothing(doc)
@test doc["cust_id"] == "A123"
@test doc["amount"] == 250
end
@testset "delete with projection" begin
query = Mongoc.BSON("""{ "cust_id" : "A123" }""")
options = Mongoc.BSON("""{ "projection": { "amount" : 0 } }""")
doc = Mongoc.find_one_and_delete(collection, query, options=options)
@test !isnothing(doc)
@test doc["cust_id"] == "A123"
@test !haskey(doc, "amount")
end
Mongoc.drop(collection)
end
@testset "find one and replace" begin
collection = client[DB_NAME]["find_one_and_replace"]
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
append!(collection, docs)
@testset "replace by filter" begin
query = Mongoc.BSON("""{ "cust_id" : "B212" }""")
replacement = Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "B" }""")
doc = Mongoc.find_one_and_replace(collection, query, replacement)
@test doc["cust_id"] == "B212"
@test doc["amount"] == 200
# Returns original document
@test doc["status"] == "A"
end
@testset "replace with sort" begin
query = Mongoc.BSON("""{ "cust_id" : "A123" }""")
replacement = Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 275, "status" : "B" }""")
options = Mongoc.BSON("""{ "sort" : {"amount": 1 } }""")
doc = Mongoc.find_one_and_replace(collection, query, replacement, options=options)
@test doc["cust_id"] == "A123"
@test doc["amount"] == 250
# Returns original document
@test doc["status"] == "A"
end
@testset "return new document" begin
query = Mongoc.BSON("""{ "cust_id" : "B212" }""")
replacement = Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "C" }""")
options = Mongoc.BSON("""{ "returnNewDocument" : true }""")
doc = Mongoc.find_one_and_replace(collection, query, replacement, options=options)
@test doc["cust_id"] == "B212"
@test doc["amount"] == 200
# Returns new document
@test doc["status"] == "C"
end
@testset "returns nothing if it does not exist" begin
query = Mongoc.BSON("""{ "cust_id" : "C313" }""")
replacement = Mongoc.BSON("""{ "cust_id" : "C313", "amount" : 400, "status" : "A" }""")
doc = Mongoc.find_one_and_replace(collection, query, replacement)
@test isnothing(doc)
end
@testset "returns nothing if it does not exist and returning new document" begin
query = Mongoc.BSON("""{ "cust_id" : "C313" }""")
replacement = Mongoc.BSON("""{ "cust_id" : "C313", "amount" : 400, "status" : "A" }""")
options = Mongoc.BSON("""{ "returnNewDocument" : true }""")
doc = Mongoc.find_one_and_replace(collection, query, replacement, options=options)
@test isnothing(doc)
end
@testset "upsert" begin
query = Mongoc.BSON("""{ "cust_id" : "C313" }""")
replacement = Mongoc.BSON("""{ "cust_id" : "C313", "amount" : 400, "status" : "A" }""")
options = Mongoc.BSON("""{ "upsert" : true }""")
doc = Mongoc.find_one_and_replace(collection, query, replacement, options=options)
@test isnothing(doc)
replacement = Mongoc.BSON("""{ "cust_id" : "C313", "amount" : 400, "status" : "B" }""")
doc = Mongoc.find_one_and_replace(collection, query, replacement, options=options)
@test !isnothing(doc)
end
@testset "throws if operator in replacement" begin
query = Mongoc.BSON("""{"cust_id" : "B212"}""")
replacement = Mongoc.BSON("""{ "\$set" : {"cust_id" : "B212", "amount" : 200, "status" : "C" } }""")
@test_throws ArgumentError Mongoc.find_one_and_replace(collection, query, replacement)
end
Mongoc.drop(collection)
end
@testset "find one and update" begin
collection = client[DB_NAME]["find_one_and_update"]
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
append!(collection, docs)
@testset "update by filter" begin
query = Mongoc.BSON("""{ "cust_id" : "B212" }""")
update = Mongoc.BSON("""{"\$set" : { "status" : "B" } }""")
doc = Mongoc.find_one_and_update(collection, query, update)
@test doc["cust_id"] == "B212"
@test doc["amount"] == 200
# Returns original document
@test doc["status"] == "A"
end
@testset "update with sort" begin
query = Mongoc.BSON("""{ "cust_id" : "A123" }""")
update = Mongoc.BSON("""{ "\$set" : { "status" : "B", "amount" : 275 } }""")
options = Mongoc.BSON("""{ "sort": {"amount": 1 } }""")
doc = Mongoc.find_one_and_update(collection, query, update, options=options)
@test doc["cust_id"] == "A123"
@test doc["amount"] == 250
# Returns original document
@test doc["status"] == "A"
end
@testset "return new document" begin
query = Mongoc.BSON("""{ "cust_id" : "B212" }""")
update = Mongoc.BSON("""{ "\$set" : { "status" : "C" } }""")
options = Mongoc.BSON("""{ "returnNewDocument" : true}""")
doc = Mongoc.find_one_and_update(collection, query, update, options=options)
@test doc["cust_id"] == "B212"
@test doc["amount"] == 200
# Returns new document
@test doc["status"] == "C"
end
@testset "returns nothing if it does not exist" begin
query = Mongoc.BSON("""{ "cust_id" : "C313" }""")
update = Mongoc.BSON("""{ "\$set" : { "cust_id" : "C313", "amount" : 400, "status" : "A" } }""")
doc = Mongoc.find_one_and_update(collection, query, update)
@test isnothing(doc)
end
@testset "returns nothing if it does not exist and returning new document" begin
query = Mongoc.BSON("""{ "cust_id" : "C313" }""")
update = Mongoc.BSON("""{ "\$set" : { "cust_id" : "C313", "amount" : 400, "status" : "A" } }""")
options = Mongoc.BSON("""{ "returnNewDocument" : true }""")
doc = Mongoc.find_one_and_update(collection, query, update, options=options)
@test isnothing(doc)
end
@testset "upsert" begin
query = Mongoc.BSON("""{ "cust_id" : "C313" }""")
update = Mongoc.BSON("""{ "\$setOnInsert" : { "cust_id" : "C313", "amount" : 400 }, "\$set" : { "status" : "A" } }""")
options = Mongoc.BSON("""{ "upsert" : true }""")
doc = Mongoc.find_one_and_update(collection, query, update, options=options)
@test isnothing(doc)
update = Mongoc.BSON("""{ "\$setOnInsert" : { "cust_id" : "C313", "amount" : 400 }, "\$set" : { "status" : "B" } }""")
doc = Mongoc.find_one_and_update(collection, query, update, options=options)
@test !isnothing(doc)
end
@testset "throws if no operator in update" begin
query = Mongoc.BSON("""{ "cust_id" : "B212" }""")
update = Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "C" }""")
@test_throws ArgumentError Mongoc.find_one_and_update(collection, query, update)
end
Mongoc.drop(collection)
end
@testset "command" begin
database = client[DB_NAME]
collection_name = "index_collection"
collection = database[collection_name]
let
items = [
Mongoc.BSON("_id" => 1, "group" => "g1"),
Mongoc.BSON("_id" => 2, "group" => "g1"),
Mongoc.BSON("_id" => 3, "group" => "g2")
]
append!(collection, items)
@test length(collection) == 3
end
@testset "database write_command" begin
create_indexes_cmd = Mongoc.BSON(
"createIndexes" => collection_name,
"indexes" => [ Mongoc.BSON("key" => Mongoc.BSON("group" => 1), "name" => "group_index") ]
)
reply = Mongoc.write_command(database, create_indexes_cmd)
@test reply["ok"] == 1
end
@testset "database read_command" begin
reply = Mongoc.read_command(client["admin"], Mongoc.BSON("""{ "serverStatus" : 1 }"""))
@test reply["ok"] == 1
end
Mongoc.drop(collection)
end
@testset "Users" begin
# creates admin user - https://docs.mongodb.com/manual/tutorial/enable-authentication/
@test Mongoc.has_database(client, DB_NAME) # at this point, DB_NAME should exist
database = client[DB_NAME]
user_name = "myUser"
pass = "abc123"
roles = Mongoc.BSON()
if Mongoc.has_user(database, user_name)
Mongoc.remove_user(database, user_name)
end
Mongoc.add_user(database, user_name, pass, roles)
Mongoc.remove_user(database, user_name)
@test !Mongoc.has_user(database, user_name)
end
@testset "Session Options" begin
opt = Mongoc.SessionOptions()
@test Mongoc.get_casual_consistency(opt)
Mongoc.set_casual_consistency!(opt, false)
@test !Mongoc.get_casual_consistency(opt)
end
server_version = Mongoc.get_server_mongodb_version(client)
if server_version < v"3.6"
@warn("MongoDB server version $server_version does not support Sessions. Skipping tests.")
else
@testset "Session" begin
session = Mongoc.Session(client)
db = session[DB_NAME]
collection = db["session_collection"]
push!(collection, Mongoc.BSON("""{ "try-insert" : 1 }"""))
Mongoc.drop(collection)
end
end
@testset "Drop Database" begin
Mongoc.drop(client[DB_NAME])
end
@testset "GridFS" begin
@testset "Create/Destroy" begin
db = client[DB_NAME]
bucket = Mongoc.Bucket(db)
Mongoc.destroy!(bucket)
end
@testset "Stream from filepath" begin
fp = joinpath(@__DIR__, "replica_set_initiate.js")
@assert isfile(fp)
io = Mongoc.MongoStreamFile(fp)
@test isopen(io)
Mongoc.close(io)
@test !isopen(io)
Mongoc.destroy!(io)
end
@testset "Upload/Download/Find/Delete file" begin
db = client[DB_NAME]
bucket = Mongoc.Bucket(db)
local_fp = joinpath(@__DIR__, "replica_set_initiate.js")
@assert isfile(local_fp)
original_str = read(local_fp, String)
remote_filename = "remote_replica_set_initiate.js"
@testset "Upload" begin
Mongoc.upload(bucket, remote_filename, local_fp)
end
@test !isempty(bucket)
download_filepath = joinpath(@__DIR__, "tmp_replica_set_initiate.js")
@testset "Download to file" begin
try
Mongoc.download(bucket, remote_filename, download_filepath)
let
tmp_str = read(download_filepath, String)
@test original_str == tmp_str
end
finally
isfile(download_filepath) && rm(download_filepath)
end
end
@testset "transfer_to_buffer!" begin
@testset "empty buffer" begin
buff = UInt8[]
pos = 0
data = UInt8[1,2,0,0]
nr = 2
@test Mongoc.nb_free(buff, pos) == 0
@test Mongoc.nb_to_fill(buff, pos, nr) == 0
@test Mongoc.nb_to_append(buff, pos, nr) == 2
Mongoc.transfer_to_buffer!(buff, pos, data, nr)
@test buff == UInt8[1,2]
end
@testset "increase buffer" begin
buff = UInt8[1,2,0,0]
pos = 2
data = UInt8[3,4,5,6]
nr = 3
@test Mongoc.nb_free(buff, pos) == 2
@test Mongoc.nb_to_fill(buff, pos, nr) == 2
@test Mongoc.nb_to_append(buff, pos, nr) == 1
Mongoc.transfer_to_buffer!(buff, pos, data, nr)
@test buff == UInt8[1,2,3,4,5]
end
@testset "big buffer" begin
buff = UInt8[1,0,0,0]
pos = 1
data = UInt8[2,3,4,5]
nr = 1
Mongoc.transfer_to_buffer!(buff, pos, data, nr)
@test buff == UInt8[1,2,0,0]
end
end
@testset "Download to stream" begin
Mongoc.open_download_stream(bucket, remote_filename) do io
@test isopen(io)
tmp_str = read(io, String)
@test original_str == tmp_str
end
end
@testset "Find and Delete" begin
cursor = Mongoc.find(bucket)
found = false
for doc in cursor
@test !found
found = true
@test doc["filename"] == remote_filename
Mongoc.delete(bucket, doc)
end
@test isempty(bucket)
end
@testset "Upload and Delete with id" begin
Mongoc.upload(bucket, remote_filename, local_fp, file_id="my_id")
found = false
for doc in Mongoc.find(bucket, Mongoc.BSON("_id" => "my_id"))
found = true
end
@test found
@test !isempty(bucket)
empty!(bucket)
@test isempty(bucket)
end
@testset "open upload stream - text" begin
remote_filename = "uploaded_file.txt"
io = Mongoc.open_upload_stream(bucket, remote_filename)
msg = "hey you out there"
write(io, msg)
close(io)
Mongoc.open_download_stream(bucket, remote_filename) do io
@test isopen(io)
tmp_str = read(io, String)
@test msg == tmp_str
end
empty!(bucket)
end
@testset "open upload stream - bytes" begin
data = rand(UInt8, 3_000_000)
remote_filename = "uploaded.data"
io = Mongoc.open_upload_stream(bucket, remote_filename)
write(io, data)
close(io)
Mongoc.open_download_stream(bucket, remote_filename) do io
@test isopen(io)
downloaded_data = read(io)
@test downloaded_data == data
end
empty!(bucket)
end
@testset "upload abort" begin
remote_filename = "uploaded_file.txt"
io = Mongoc.open_upload_stream(bucket, remote_filename)
msg = "hey you out there"
write(io, msg)
Mongoc.abort_upload(io)
close(io)
@test isempty(bucket)
end
end
end
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 8359 |
#=
https://docs.mongodb.com/manual/tutorial/deploy-replica-set/
```shell
mkdir tmp
cd tmp
mkdir db1
mkdir db2
mkdir db3
mongod --dbpath ./db1 --port 27021 --replSet "rst" --bind_ip 127.0.0.1 &
mongod --dbpath ./db2 --port 27022 --replSet "rst" --bind_ip 127.0.0.1 &
mongod --dbpath ./db3 --port 27023 --replSet "rst" --bind_ip 127.0.0.1 &
mongo --port 27021 replica_set_initiate.js
```
=#
let
fp_replicaset_script = joinpath(@__DIR__, "replica_set_initiate.js")
@assert isfile(fp_replicaset_script)
run(`mongo --port 27021 $fp_replicaset_script`)
sleep(20)
end
import Mongoc
using Test
using Dates
const DB_REPLICA_NAME = "mongoc_replica"
const REPLICA_SET_URL = "mongodb://127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023/?replicaSet=rst"
@testset "Connect to ReplicaSet" begin
client = Mongoc.Client(REPLICA_SET_URL)
database = client[DB_REPLICA_NAME]
collection = database["my_collection"]
@test isempty(collection)
push!(collection, Mongoc.BSON("""{ "hey" : 1 }"""))
@test length(collection) == 1
doc = collect(collection)[1]
@test doc["hey"] == 1
empty!(collection)
end
@testset "Transaction API" begin
client = Mongoc.Client(REPLICA_SET_URL)
database = client[DB_REPLICA_NAME]
collection = database["transaction"]
@test isempty(collection)
push!(collection, Mongoc.BSON("""{ "outside_transaction" : 1 }"""))
@test length(collection) == 1
session = Mongoc.Session(client)
Mongoc.start_transaction!(session)
@test Mongoc.in_transaction(session)
collection_session = session[DB_REPLICA_NAME]["transaction"]
push!(collection_session, Mongoc.BSON("""{ "inside_transaction" : 1 }"""))
@test length(collection_session) == 2
@test length(collection) == 1
Mongoc.abort_transaction!(session)
@test !Mongoc.in_transaction(session)
@test length(collection_session) == 1
Mongoc.start_transaction!(session)
@test Mongoc.in_transaction(session)
push!(collection_session, Mongoc.BSON("""{ "inside_transaction" : 2 }"""))
@test length(collection_session) == 2
@test length(collection) == 1
Mongoc.commit_transaction!(session)
@test length(collection_session) == 2
@test length(collection) == 2
empty!(collection)
end
@testset "Transaction High-Level API" begin
client = Mongoc.Client(REPLICA_SET_URL)
collection_unbounded = client[DB_REPLICA_NAME]["transaction"]
@assert isempty(collection_unbounded) # test precondition
Mongoc.transaction(client) do session # session = Mongoc.Session(client); Mongoc.start_transaction!(session)
@test Mongoc.in_transaction(session)
database = session[DB_REPLICA_NAME]
collection = database["transaction"]
@test isempty(collection)
let # insert_many
items = Vector{Mongoc.BSON}()
push!(items, Mongoc.BSON("""{ "item" : 1 }"""))
push!(items, Mongoc.BSON("""{ "item" : 2 }"""))
push!(items, Mongoc.BSON("""{ "item" : 3 }"""))
append!(collection, items)
@test length(collection) == 3
@test isempty(collection_unbounded)
empty!(collection)
end
@test isempty(collection)
@test Mongoc.in_transaction(session)
let # insert_one
new_item = Mongoc.BSON()
new_item["inserted"] = true
push!(collection, new_item)
@test isempty(collection_unbounded)
@test !isempty(collection)
end
@test Mongoc.in_transaction(session)
let # delete_one
item_to_delete = Mongoc.BSON()
item_to_delete["inserted"] = true
item_to_delete["to_delete"] = true
push!(collection, item_to_delete)
@test length(collection) == 2
@test isempty(collection_unbounded)
Mongoc.delete_one(collection, Mongoc.BSON("""{ "to_delete" : true }"""))
@test length(collection) == 1
@test isempty(collection_unbounded)
end
@test Mongoc.in_transaction(session)
let # delete_many
item_to_delete = Mongoc.BSON()
item_to_delete["inserted"] = true
item_to_delete["to_delete"] = true
push!(collection, item_to_delete)
@test length(collection) == 2
@test isempty(collection_unbounded)
Mongoc.delete_many(collection, Mongoc.BSON("""{ "to_delete" : true }"""))
@test length(collection) == 1
@test isempty(collection_unbounded)
end
@test Mongoc.in_transaction(session)
let # update_one
selector = Mongoc.BSON()
update = Mongoc.BSON("""{ "\$set" : { "update_one" : true } }""")
Mongoc.update_one(collection, selector, update)
end
@test Mongoc.in_transaction(session)
let # update_many
selector = Mongoc.BSON()
update = Mongoc.BSON("""{ "\$set" : { "update_many" : true } }""")
Mongoc.update_many(collection, selector, update)
end
@test Mongoc.in_transaction(session)
let # check updates
doc = Mongoc.find_one(collection, Mongoc.BSON())
@test doc["update_one"]
@test doc["update_many"]
@test isempty(collection_unbounded)
end
@test Mongoc.in_transaction(session)
let # find_one_and_delete
item_to_delete = Mongoc.BSON()
item_to_delete["inserted"] = true
item_to_delete["to_delete"] = true
push!(collection, item_to_delete)
@test length(collection) == 2
@test isempty(collection_unbounded)
doc = Mongoc.find_one_and_delete(collection, Mongoc.BSON("""{ "to_delete" : true }"""))
@test !isnothing(doc)
@test length(collection) == 1
@test isempty(collection_unbounded)
end
@test Mongoc.in_transaction(session)
let # find_one_and_replace
selector = Mongoc.BSON()
replacement = Mongoc.BSON("""{ "find_one_and_replace": true }""")
doc = Mongoc.find_one_and_replace(collection, selector, replacement)
@test !isnothing(doc)
end
@test Mongoc.in_transaction(session)
let # find_one_and_update
selector = Mongoc.BSON()
update = Mongoc.BSON("""{ "\$set": { "find_one_and_update": true } }""")
doc = Mongoc.find_one_and_update(collection, selector, update)
@test !isnothing(doc)
end
@test Mongoc.in_transaction(session)
let # check updates
doc = Mongoc.find_one(collection, Mongoc.BSON())
@test doc["find_one_and_replace"]
@test doc["find_one_and_update"]
@test isempty(collection_unbounded)
end
@test Mongoc.in_transaction(session)
end
@test !isempty(collection_unbounded)
empty!(collection_unbounded)
try
Mongoc.transaction(client) do session
database = session[DB_REPLICA_NAME]
collection = database["transaction"]
new_item = Mongoc.BSON()
new_item["inserted"] = true
push!(collection, new_item)
@test isempty(collection_unbounded)
@test !isempty(collection)
error("abort transaction")
end
catch e
println("got an error: $e")
end
@test isempty(collection_unbounded)
end
@testset "ClientPool" begin
@testset "Create/Destroy" begin
pool = Mongoc.ClientPool(REPLICA_SET_URL)
Mongoc.destroy!(pool)
end
@testset "Client from ClientPool" begin
pool = Mongoc.ClientPool(REPLICA_SET_URL, max_size=4)
client1 = Mongoc.Client(pool)
client2 = Mongoc.Client(pool)
client3 = Mongoc.Client(pool)
client = Mongoc.Client(pool)
database = client[DB_REPLICA_NAME]
collection = database["my_collection"]
@test isempty(collection)
push!(collection, Mongoc.BSON("""{ "hey" : 1 }"""))
@test length(collection) == 1
doc = collect(collection)[1]
@test doc["hey"] == 1
empty!(collection)
@test_throws AssertionError Mongoc.Client(pool, try_pop=true)
end
end
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | code | 143 |
include("bson_tests.jl")
include("mongodb_tests.jl")
#=
if !Sys.iswindows()
include("replica_set_tests.jl")
end
=#
Mongoc.mongoc_cleanup()
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 2334 |
# Mongoc.jl
[![License][license-img]](LICENSE)
[![CI][ci-img]][ci-url]
[![appveyor][appveyor-img]][appveyor-url]
[![codecov][codecov-img]][codecov-url]
[![dev][docs-dev-img]][docs-dev-url]
[![stable][docs-stable-img]][docs-stable-url]
[license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ci-img]: https://github.com/felipenoris/Mongoc.jl/workflows/CI/badge.svg
[ci-url]: https://github.com/felipenoris/Mongoc.jl/actions?query=workflow%3ACI
[appveyor-img]: https://img.shields.io/appveyor/ci/felipenoris/mongoc-jl/master.svg?logo=appveyor&label=Windows&style=flat-square
[appveyor-url]: https://ci.appveyor.com/project/felipenoris/mongoc-jl/branch/master
[codecov-img]: https://img.shields.io/codecov/c/github/felipenoris/Mongoc.jl/master.svg?label=codecov&style=flat-square
[codecov-url]: http://codecov.io/github/felipenoris/Mongoc.jl?branch=master
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg?style=flat-square
[docs-dev-url]: https://felipenoris.github.io/Mongoc.jl/dev
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg?style=flat-square
[docs-stable-url]: https://felipenoris.github.io/Mongoc.jl/stable
**Mongoc.jl** is a [MongoDB](https://www.mongodb.com/) driver for the Julia Language.
It is implemented as a thin wrapper around [libmongoc](http://mongoc.org/), the official client library for C applications.
Given that [BSON](http://bsonspec.org/) is the document format for MongoDB,
this package also implements a wrapper around [libbson](http://mongoc.org/libbson/current/index.html),
which provides a way to create and manipulate BSON documents.
## Requirements
* MongoDB 3.0 or newer.
* Julia v1.6 or newer.
* Linux, macOS, or Windows.
## Installation
From a Julia session, run:
```julia
julia> using Pkg
julia> Pkg.add("Mongoc")
```
## Documentation
The documentation for this package is hosted at https://felipenoris.github.io/Mongoc.jl/stable.
## License
The source code for the package `Mongoc.jl` is licensed under the [MIT License](https://github.com/felipenoris/Mongoc.jl/blob/master/LICENSE).
This repository distributes binary assets built from [mongo-c-driver](https://github.com/mongodb/mongo-c-driver) source code,
which is licensed under [Apache-2.0](https://github.com/mongodb/mongo-c-driver/blob/master/COPYING).
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 1229 |
# API Reference
## BSON
```@docs
Mongoc.BSON
Mongoc.BSONObjectId
Mongoc.BSONCode
Mongoc.as_json
Mongoc.as_dict
Mongoc.get_array
Mongoc.read_bson
Mongoc.write_bson
Mongoc.read_next_bson
Mongoc.BSONError
Mongoc.BSONValue
Mongoc.get_as_bson_value
Mongoc.read_bson_from_json
```
## Client
```@docs
Mongoc.Client
Mongoc.set_appname!
Mongoc.ping
Mongoc.get_server_mongodb_version
Mongoc.find_databases
Mongoc.get_database_names
Mongoc.has_database
```
## ClientPool
```@docs
Mongoc.ClientPool
Mongoc.set_max_size
```
## Database
```@docs
Mongoc.command_simple
Mongoc.add_user
Mongoc.remove_user
Mongoc.has_user
Mongoc.find_collections
Mongoc.get_collection_names
Mongoc.read_command
Mongoc.write_command
```
## Collection
```@docs
Mongoc.find
Mongoc.find_one
Mongoc.count_documents
Mongoc.drop
Mongoc.find_and_modify
Mongoc.FindAndModifyFlags
Mongoc.find_one_and_delete
Mongoc.find_one_and_replace
Mongoc.find_one_and_update
Mongoc.replace_one
```
## Aggregation
```@docs
Mongoc.aggregate
Mongoc.QueryFlags
```
## Session
```@docs
Mongoc.transaction
```
## GridFS
```@docs
Mongoc.MongoStreamFile
Mongoc.upload
Mongoc.download
Mongoc.delete
Mongoc.open_download_stream
Mongoc.open_upload_stream
Mongoc.abort_upload
```
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 2013 |
# Authentication
Refer to the [Security section of the MongoDB Manual](https://docs.mongodb.com/manual/security/)
for an overview on how authentication works in MongoDB.
## Basic Authentication (SCRAM)
In this authentication mechanism, user and passwords are passed in the URI string for the `Mongoc.Client`.
### Enable Auth
To use basic authentication mechanism, first enable authentication in the database,
as described in the [MongoDB manual](http://mongoc.org/libmongoc/current/authentication.html).
#### 1. Start MongoDB without access control
```shell
$ mongod --dbpath ./db
```
#### 2. Connect to the database and create an admin user.
From a Julia session, you can use `Mongoc.add_user` to add users to a MongoDB database.
```julia
import Mongoc
roles = Mongoc.BSON("""[ { "role" : "userAdminAnyDatabase", "db" : "admin" }, "readWriteAnyDatabase" ]""")
client = Mongoc.Client()
Mongoc.add_user(client["admin"], "myUserAdmin", "abc123", roles)
Mongoc.destroy!(client) # or exit julia session
```
#### 3. Re-start the MongoDB instance with access control
Kill the previous process running `mongod` and then start server with auth option.
```shell
$ mongod --auth --dbpath ./db
```
### Connect and authenticate
Pass the user and password in the URI, as described in [http://mongoc.org/libmongoc/current/authentication.html](http://mongoc.org/libmongoc/current/authentication.html).
```julia
client = Mongoc.Client("mongodb://myUserAdmin:abc123@localhost/?authSource=admin")
```
From MongoDB 4.0, there's a new authentication mechanism SCRAM-SHA-256, which replaces the previous SCRAM-SHA-1 mechanism.
The correct authentication mechanism is negotiated between the driver and the server.
Alternatively, SCRAM-SHA-256 can be explicitly specified:
```julia
client = Mongoc.Client("mongodb://myUserAdmin:abc123@localhost/?authMechanism=SCRAM-SHA-256&authSource=admin")
```
Refer to the [MongoDB manual](https://docs.mongodb.com/manual/security/) for adding new users and roles per database.
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 849 |
# Connection Pool
A `ClientPool` is a *thread-safe* pool of connections to a MongoDB instance.
From a `ClientPool` you can create regular `Client` connections to MongoDB.
```julia
const REPLICA_SET_URL = "mongodb://127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023/?replicaSet=rs0"
# creates a ClientPool with a maximum of 4 connections.
pool = Mongoc.ClientPool(REPLICA_SET_URL, max_size=4)
# create Clients from a pool
client1 = Mongoc.Client(pool)
client2 = Mongoc.Client(pool)
client3 = Mongoc.Client(pool)
client4 = Mongoc.Client(pool)
```
When you reach the maximum number of clients,
the next call to `Mongoc.Client(pool)` will block
until a `Client` is released.
Use `try_pop=true` option to throw an error instead
of blocking the current thread:
```julia
# will throw `AssertionError`
client5 = Mongoc.Client(pool, try_pop=true)
```
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 2226 |
# CRUD Operations
## Insert
### API
```julia
Mongoc.insert_one(collection::Collection, document::BSON; options::Union{Nothing, BSON}=nothing)
Mongoc.insert_many(collection::Collection, documents::Vector{BSON}; bulk_options::Union{Nothing, BSON}=nothing, insert_options::Union{Nothing, BSON}=nothing)
```
`Mongoc.insert_one` is equivalent to `Base.push!` for a collection.
The same applies to `Mongoc.insert_many` in relation to `Base.append!`.
### Examples
```julia
push!(collection, Mongoc.BSON("""{ "hello" : "world" }"""))
append!(collection, [ Mongoc.BSON("""{ "first" : 1, "delete" : true }"""), Mongoc.BSON("""{ "second" : 2, "delete" : true }"""), Mongoc.BSON("""{ "third" : 3, "delete" : false }""") ])
```
## Select
### API
```julia
find_one(collection::Collection, bson_filter::BSON=BSON(); options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}
find(collection::Collection, bson_filter::BSON=BSON(); options::Union{Nothing, BSON}=nothing) :: Cursor
```
### Examples
```julia
bson = Mongoc.find_one(collection, Mongoc.BSON("""{ "third" : 3 }"""))
for doc in Mongoc.find(collection)
println(doc)
end
```
## Update
### API
```julia
Mongoc.update_one(collection::Collection, selector::BSON, update::BSON; options::Union{Nothing, BSON}=nothing)
Mongoc.update_many(collection::Collection, selector::BSON, update::BSON; options::Union{Nothing, BSON}=nothing)
```
### Examples
```julia
selector = Mongoc.BSON("""{ "delete" : false }""")
update = Mongoc.BSON("""{ "\$set" : { "delete" : true, "new_field" : 1 } }""")
Mongoc.update_one(collection, selector, update)
selector = Mongoc.BSON("""{ "delete" : true }""")
update = Mongoc.BSON("""{ "\$set" : { "delete" : false } }""")
Mongoc.update_many(collection, selector, update)
```
## Delete
### API
```julia
Mongoc.delete_one(collection::Collection, selector::BSON; options::Union{Nothing, BSON}=nothing)
Mongoc.delete_many(collection::Collection, selector::BSON; options::Union{Nothing, BSON}=nothing)
```
### Examples
```julia
selector = Mongoc.BSON("_id" => oid)
Mongoc.delete_one(collection, selector)
# deletes all elements in a collection
Mongoc.delete_many(collection, Mongoc.BSON()) # equivalent to `empty!(collection)`
```
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 1799 |
# GridFS
GridFS is a MongoDB feature to store large files.
A BSON document can be use to store arbitrary data,
but the size limit is 16MB.
With GridFS, you can store files that exceed this limit.
Refer to [GridFS docs website](https://docs.mongodb.com/manual/core/gridfs/)
for more information.
## Buckets
Files in GridFS are organized inside Buckets.
First, create a Bucket associated with a database.
Then, add files to that bucket.
```julia
db = client[DB_NAME]
bucket = Mongoc.Bucket(db)
```
## Upload and Download a file
The following example shows how to upload
and download a file to/from a `Bucket`
represented by the variable `bucket`.
```julia
local_fp = "/path/to/a/local/file.txt"
@assert isfile(local_fp)
remote_filename = "remote_file.txt"
# will upload `local_fp` to `bucket`.
# On the remote bucket, the file will be named `remote_file.txt`.
Mongoc.upload(bucket, remote_filename, local_fp)
# downloads `remote_file.txt` to `download_filepath`.
download_filepath = "/path/to/a/local/download_file.txt"
Mongoc.download(bucket, remote_filename, download_filepath)
```
## Upload and Download using streams
Use [`Mongoc.open_upload_stream`](@ref)
and [`Mongoc.open_download_stream`](@ref)
to execute stream based upload and download
operations.
```julia
remote_filename = "uploaded_file.txt"
io = Mongoc.open_upload_stream(bucket, remote_filename)
msg = "hey you out there"
write(io, msg)
close(io)
Mongoc.open_download_stream(bucket, remote_filename) do io
tmp_str = read(io, String)
println( msg == tmp_str )
end
```
## Find and Delete files in Bucket
Use `Mongoc.find` on a bucket to search for files,
and `Mongoc.delete` to delete.
```julia
for doc in Mongoc.find(bucket)
println("Deleting $(doc["filename"])")
Mongoc.delete(bucket, doc)
end
```
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 1748 |
# Mongoc.jl
## Introduction
**Mongoc.jl** is a [MongoDB](https://www.mongodb.com/) driver for the Julia Language.
It is implemented as a thin wrapper around [libmongoc](http://mongoc.org/),
the official client library for C applications.
Given that [BSON](http://bsonspec.org/) is the document format for MongoDB,
this package also implements a wrapper around [libbson](http://mongoc.org/libbson/current/index.html),
which provides a way to create and manipulate BSON documents.
## Requirements
* MongoDB 3.0 or newer.
* Julia versions v1.6 or newer.
* Linux, macOS, or Windows.
## Installation
From a Julia session, run:
```julia
julia> using Pkg
julia> Pkg.add("Mongoc")
```
## Source Code
The source code for this package is hosted at
[https://github.com/felipenoris/Mongoc.jl](https://github.com/felipenoris/Mongoc.jl).
## License
The source code for the package **Mongoc.jl** is licensed under
the [MIT License](https://github.com/felipenoris/Mongoc.jl/blob/master/LICENSE).
This repository distributes binary assets built from
[mongo-c-driver](https://github.com/mongodb/mongo-c-driver) source code,
which is licensed under [Apache-2.0](https://github.com/mongodb/mongo-c-driver/blob/master/COPYING).
## Getting Help
If you're having any trouble, have any questions about this package
or want to ask for a new feature,
just open a new [issue](https://github.com/felipenoris/Mongoc.jl/issues).
## Contributing
Contributions are always welcome!
To contribute, fork the project on [GitHub](https://github.com/felipenoris/Mongoc.jl)
and send a Pull Request.
## References
* [libbson documentation](http://mongoc.org/libbson/current/index.html)
* [libmongoc documentation](http://mongoc.org/libmongoc/current/index.html)
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 2282 |
# Logging
The following example uses `Mongoc.mongoc_set_log_handler`
to set a customized log handler. In this example, the setup is done by calling `init_log_handler_if_safe()`.
```julia
using Logging
const MONGOC_LOG_LEVEL_ERROR = 0
const MONGOC_LOG_LEVEL_CRITICAL = 1
const MONGOC_LOG_LEVEL_WARNING = 2
const MONGOC_LOG_LEVEL_MESSAGE = 3
const MONGOC_LOG_LEVEL_INFO = 4
const MONGOC_LOG_LEVEL_DEBUG = 5
const MONGOC_LOG_LEVEL_TRACE = 6
if VERSION >= v"v1.7"
@inline _isjuliathread() = @ccall(jl_get_pgcstack()::Ptr{Cvoid}) != C_NULL
else
@inline _isjuliathread() = false
end
@noinline function _log_handler_do(level::Cint, domain::Ptr{UInt8}, message::Ptr{UInt8})
jlevel = if level == MONGOC_LOG_LEVEL_ERROR
Logging.Error
elseif level == MONGOC_LOG_LEVEL_CRITICAL
Logging.Error
elseif level == MONGOC_LOG_LEVEL_WARNING
Logging.Warn
elseif level == MONGOC_LOG_LEVEL_MESSAGE
Logging.Info
elseif level == MONGOC_LOG_LEVEL_INFO
Logging.Info
elseif level == MONGOC_LOG_LEVEL_DEBUG
Logging.Debug
elseif level == MONGOC_LOG_LEVEL_TRACE
Logging.Debug
else
error("Unexpected mongoc log level $level")
end
domain = unsafe_string(domain)
message = unsafe_string(message)
@logmsg jlevel "$domain $message"
nothing
end
function _log_handler(level::Cint, domain::Ptr{UInt8}, message::Ptr{UInt8}, fallback::Ptr{Cvoid})
# If called on a non-julia thread, e.g., from server monitor, fall back to default log handler.
# TODO: change this when Julia safely supports foreign thread calls.
if _isjuliathread()
_log_handler_do(level, domain, message)
else
ccall(
fallback,
Cvoid,
(Cint, Ptr{UInt8}, Ptr{UInt8}, Ptr{Cvoid}),
level, domain, message, C_NULL
)
end
end
function init_log_handler()
_isjuliathread() || error("Intercepting mongo logging unsupported on $(VERSION)")
Mongoc.mongoc_set_log_handler(
@cfunction(_log_handler, Cvoid, (Cint, Ptr{UInt8}, Ptr{UInt8}, Ptr{Cvoid})),
cglobal((:mongoc_log_default_handler, Mongoc.libmongoc))
)
end
function init_log_handler_if_safe()
if _isjuliathread()
init_log_handler()
end
end
```
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 2590 |
# Transactions
Support for transactions is available from MongoDB v4.0.
## Setting up a Replica Set
As described in the [MongoDB Manual](https://docs.mongodb.com/manual/core/transactions/),
"*multi-document transactions are available for replica sets only. Transactions for sharded clusters are scheduled for MongoDB 4.2*".
Follow [these steps](https://docs.mongodb.com/manual/tutorial/deploy-replica-set/)
to start a replica set. The following script will create a replica set with 3 nodes:
```shell
mkdir db1
mkdir db2
mkdir db3
mongod --dbpath ./db1 --port 27021 --replSet "rs0" --bind_ip 127.0.0.1
mongod --dbpath ./db2 --port 27022 --replSet "rs0" --bind_ip 127.0.0.1
mongod --dbpath ./db3 --port 27023 --replSet "rs0" --bind_ip 127.0.0.1
mongo --port 27021 replica_set_initiate.js
```
The contents of `replica_set_initiate.js` are:
```javascript
rs.initiate( {
_id : "rs0",
members: [
{ _id: 0, host: "127.0.0.1:27021" },
{ _id: 1, host: "127.0.0.1:27022" },
{ _id: 2, host: "127.0.0.1:27023" }
]
})
```
## Executing Transactions
In MongoDB, **transactions** are bound to **Sessions**.
In **Mongoc.jl**, use the function `Mongoc.transaction` with *do-syntax* to execute a transaction,
and use the argument `session` to get database and collection references bound to the session
that will execute the transaction.
Just use the `session` object the same way you would use a `Client`.
!!! note
Database and Collection references that are not created
from a `session` object are not bound to the transaction.
## Example
```julia
import Mongoc
# connect to a Replica Set
client = Mongoc.Client("mongodb://127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023/?replicaSet=rs0")
# this collection reference is not bounded to the transaction
collection_unbounded = client["my_database"]["my_collection"]
# insert a dummy document, just to make sure the collection exists
push!(collection_unbounded, Mongoc.BSON("""{ "test" : 1 }"""))
empty!(collection_unbounded)
Mongoc.transaction(client) do session
database = session["my_database"]
collection = database["my_collection"]
new_item = Mongoc.BSON()
new_item["inserted"] = true
push!(collection, new_item)
println("collection_bounded is empty? ", isempty(collection_unbounded))
println("collection is empty? ", isempty(collection))
end
println(collect(collection_unbounded))
```
The script output is:
```
collection_bounded is empty? true
collection is empty? false
Mongoc.BSON[BSON("{ "_id" : { "$oid" : "5ba4251f3192e3298b62c5a3" }, "inserted" : true }")]
```
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.9.1 | 1f0d7579d1bacc1446751990d7e0c4c0bf0f3277 | docs | 16438 |
# Tutorial
This tutorial illustrates common use cases for accessing a MongoDB database with **Mongoc.jl** package.
## Setup
First, make sure you have **Mongoc.jl** package installed.
```julia
julia> using Pkg
julia> Pkg.add("Mongoc")
```
The following tutorial assumes that a MongoDB instance is running on the
default host and port: `localhost:27017`.
To start a new server instance on the default location use the following command on your shell.
```shell
$ mkdir db
$ mongod --dbpath ./db
```
## Connecting to MongoDB
Connect to a MongoDB instance using a `Mongoc.Client`.
Use the [MongoDB URI format](https://docs.mongodb.com/manual/reference/connection-string/) to set the server location.
```julia
julia> import Mongoc
julia> client = Mongoc.Client("mongodb://localhost:27017")
Client(URI("mongodb://localhost:27017"))
```
As a shorthand, you can also use:
```julia
julia> client = Mongoc.Client("localhost", 27017)
```
To connect to the server at the default location `localhost:27017`
you can use the `Mongoc.Client` constructor with no arguments.
```julia
julia> client = Mongoc.Client()
```
One thing to keep in mind about MongoDB is that operations are usually lazy.
So you don't actually connect to the database until you need to issue a command or query.
If you need to check the connection status before sending commands,
use Mongoc.ping(client) to ping the server.
```julia
julia> Mongoc.ping(client)
BSON("{ "ok" : 1.0 }")
```
## Getting a Database
A MongoDB instance consists on a set of independent databases.
You get a Database reference using the following command.
```julia
julia> database = client["my-database"]
Database(Client(URI("mongodb://localhost:27017")), "my-database")
```
If `"my-database"` does not exist on your MongoDB instance, it will be created
in the first time you insert a document in it.
## Getting a Collection
A Collection is a set of documents in a MongoDB database.
You get a collection reference using the following command.
```julia
julia> collection = database["my-collection"]
Collection(Database(Client(URI("mongodb://localhost:27017")), "my-database"), "my-collection")
```
If it does not exist inside your database, the Collection
is created in the first time you insert a document in it.
## BSON Documents
[BSON](http://bsonspec.org/) is the document format for MongoDB.
To create a BSON document instance in **Mongoc.jl** just use Dictionary syntax,
using `String`s as keys.
```julia
julia> document = Mongoc.BSON()
julia> document["name"] = "Felipe"
julia> document["age"] = 35
julia> document["preferences"] = [ "Music", "Computer", "Photography" ]
julia> document["null_value"] = nothing # maps to BSON null value
julia> using Dates; document["details"] = Dict("birth date" => DateTime(1983, 4, 16), "location" => "Rio de Janeiro")
julia> using UUIDs; document["id"] = uuid4()
```
As another example:
```julia
julia> document = Mongoc.BSON("a" => 1, "b" => "field_b", "c" => [1, 2, 3])
BSON("{ "a" : 1, "b" : "field_b", "c" : [ 1, 2, 3 ] }")
```
You can also create a BSON document from a JSON string.
```julia
julia> document = Mongoc.BSON("""{ "hey" : "you" }""")
```
And also from a Dictionary.
```julia
julia> dict = Dict("hey" => "you")
Dict{String,String} with 1 entry:
"hey" => "you"
julia> document = Mongoc.BSON(dict)
BSON("{ "hey" : "you" }")
```
Reading data from a BSON is like reading from a `Dict`.
```julia
julia> document = Mongoc.BSON("a" => 1, "b" => "field_b", "c" => [1, 2, 3])
BSON("{ "a" : 1, "b" : "field_b", "c" : [ 1, 2, 3 ] }")
julia> document["a"]
1
julia> document["b"]
"field_b"
```
Like a `Dict`, you can iterate thru BSON's `(key, value)` pairs, like so:
```julia
julia> for (k, v) in document
println("[$k] = $v")
end
[a] = 1
[b] = field_b
[c] = Any[1, 2, 3]
```
To convert a BSON to a JSON string, use:
```julia
julia> Mongoc.as_json(document)
"{ \"name\" : \"Felipe\", \"age\" : 35, \"preferences\" : [ \"Music\", \"Computer\", \"Photography\" ], \"null_value\" : null, \"details\" : { \"location\" : \"Rio de Janeiro\", \"birth date\" : { \"\$date\" : \"1983-04-16T00:00:00Z\" } } }"
```
To convert a BSON document to a Dictionary, use `Mongoc.as_dict`.
```julia
julia> Mongoc.as_dict(document)
Dict{Any,Any} with 1 entry:
"hey" => "you"
```
## Read/Write BSON documents from/to IO Stream
You can read and write BSON documents in binary format to IO streams.
### High-level API
BSON documents can be serialized using Julia's `Serialization` stdlib.
This means that BSON documents can also be shared among Julia workers
using Julia's `Distributed` stdlib.
```julia
using Test, Mongoc
@testset "read/write single BSON" begin
doc = Mongoc.BSON("a" => 1)
io = IOBuffer()
write(io, doc)
seekstart(io)
doc2 = read(io, Mongoc.BSON)
@test doc2["a"] == 1
end
addprocs(1)
@everywhere using Mongoc
@testset "Serialize BSON" begin
f = @spawn Mongoc.BSON("a" => 1)
bson = fetch(f)
@test bson["a"] == 1
end
```
### Low-level API
The following example shows how to:
1. Create a vector of BSON documents.
2. Save the vector to a file.
3. Read back the vector of BSON documents from a file.
```julia
using Test, Mongoc
filepath = "data.bson"
list = Vector{Mongoc.BSON}()
let
src = Mongoc.BSON()
src["id"] = 1
src["name"] = "1st"
push!(list, src)
end
let
src = Mongoc.BSON()
src["id"] = 2
src["name"] = "2nd"
push!(list, src)
end
open(filepath, "w") do io
Mongoc.write_bson(io, list)
end
list_from_file = Mongoc.read_bson(filepath)
@test length(list_from_file) == 2
let
fst_bson = list_from_file[1]
@test fst_bson["id"] == 1
@test fst_bson["name"] == "1st"
end
let
sec_bson = list_from_file[2]
@test sec_bson["id"] == 2
@test sec_bson["name"] == "2nd"
end
```
## Read BSON Documents from a JSON File
Given a JSON file `docs.json` with the following content:
```json
{ "num" : 1, "str" : "two" }
{ "num" : 2, "str" : "three" }
```
This file can be read using a `Mongoc.BSONJSONReader`.
A high-level function `Mongoc.read_bson_from_json` is also available.
Notice how strange the json format is: it is a sequence of JSON documents without separator.
Adding a separator (`, `) between JSON documents will duplicate the BSON fields.
Also, if you enclose the whole file with a vector of JSONs, a single BSON will be returned
with a vector of elements.
### Examples
```julia
vec_of_bsons = Mongoc.read_bson_from_json("docs.json")
```
```julia
reader = Mongoc.BSONJSONReader("docs.json")
for bson in reader
println(bson)
end
```
## Inserting Documents
To insert a single document into a collection, just `Base.push!` a BSON document to it.
The result of this operation wraps the server reply and the inserted oid.
```julia
julia> document = Mongoc.BSON("""{ "hey" : "you" }""")
BSON("{ "hey" : "you" }")
julia> result = push!(collection, document)
Mongoc.InsertOneResult{Mongoc.BSONObjectId}(BSON("{ "insertedCount" : 1 }"), BSONObjectId("5c9fdb5d11c3dd04a83ba6c2"))
julia> result.inserted_oid
BSONObjectId("5c9fdb5d11c3dd04a83ba6c2")
```
Use `Base.append!` to insert a vector of documents to a collection.
The result of this operation also wraps the server reply and the inserted oids.
```julia
julia> doc1 = Mongoc.BSON("""{ "hey" : "you", "out" : "there" }""")
BSON("{ "hey" : "you", "out" : "there" }")
julia> doc2 = Mongoc.BSON("""{ "hey" : "others", "in the" : "cold" }""")
BSON("{ "hey" : "others", "in the" : "cold" }")
julia> vector = [ doc1, doc2 ]
2-element Array{Mongoc.BSON,1}:
BSON("{ "hey" : "you", "out" : "there" }")
BSON("{ "hey" : "others", "in the" : "cold" }")
julia> append!(collection, vector)
Mongoc.BulkOperationResult{Union{Nothing, BSONObjectId}}(BSON("{ "nInserted" : 2, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "nUpserted" : 0, "writeErrors" : [ ] }"), 0x00000001, Union{Nothing, BSONObjectId}[BSONObjectId("5c9fdbab11c3dd04a83ba6c3"), BSONObjectId("5c9fdbab11c3dd04a83ba6c4")])
```
## Querying Documents
To query a single document, use `Mongoc.find_one`. Pass a BSON argument as a query filter.
```julia
julia> document = Mongoc.find_one(collection, Mongoc.BSON("""{ "hey" : "you" }"""))
BSON("{ "_id" : { "$oid" : "5b9ef9cc11c3dd1da14675c3" }, "hey" : "you" }")
```
To iterate all documents from a collection, just use a for loop on a `collection`.
```julia
julia> for document in collection
println(document)
end
BSON("{ "_id" : { "$oid" : "5b9f02fb11c3dd1f4f3e26e5" }, "hey" : "you", "out" : "there" }")
BSON("{ "_id" : { "$oid" : "5b9f02fb11c3dd1f4f3e26e6" }, "hey" : "others", "in the" : "cold" }")
```
To query multiple documents, use `Mongoc.find`. Pass a BSON query argument as a query filter.
It returns a iterator of BSON documents that can be read using a `for` loop.
```julia
julia> for document in Mongoc.find(collection, Mongoc.BSON("""{ "in the" : "cold" }"""))
println(document)
end
BSON("{ "_id" : { "$oid" : "5b9f02fb11c3dd1f4f3e26e6" }, "hey" : "others", "in the" : "cold" }")
```
Use `Base.collect` to convert the result of `Mongoc.find` into a vector of BSON documents.
Also, applying `Base.collect` to a Collection gathers all documents in the collection.
```julia
julia> collect(collection)
2-element Array{Mongoc.BSON,1}:
BSON("{ "_id" : { "$oid" : "5b9f02fb11c3dd1f4f3e26e5" }, "hey" : "you", "out" : "there" }")
BSON("{ "_id" : { "$oid" : "5b9f02fb11c3dd1f4f3e26e6" }, "hey" : "others", "in the" : "cold" }")
```
## Project fields to Return from Query
To select which fields you want a query to return,
use a `projection` command in the `options` argument
of `Mongoc.find` or `Mongoc.find_one`.
As an example:
```julia
function find_contract_codes(collection, criteria::Dict=Dict()) :: Vector{String}
result = Vector{String}()
let
bson_filter = Mongoc.BSON(criteria)
bson_options = Mongoc.BSON("""{ "projection" : { "_id" : true }, "sort" : { "_id" : 1 } }""")
for bson_document in Mongoc.find(collection, bson_filter, options=bson_options)
push!(result, bson_document["_id"])
end
end
return result
end
```
Check the [libmongoc documentation for options field](http://mongoc.org/libmongoc/current/mongoc_collection_find_with_opts.html) for details.
## Counting Documents
Use `Base.length` function to count the number of documents in a collection.
Pass a BSON argument as a query filter.
```julia
julia> length(collection)
2
julia> length(collection, Mongoc.BSON("""{ "in the" : "cold" }"""))
1
```
## Aggregation and Map-Reduce
Use `Mongoc.aggregate` to execute an aggregation command.
The following reproduces the example from the [MongoDB Tutorial](https://docs.mongodb.com/manual/aggregation/).
```julia
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
collection = client["my-database"]["aggregation-collection"]
append!(collection, docs)
# Sets the pipeline command
bson_pipeline = Mongoc.BSON("""
[
{ "\$match" : { "status" : "A" } },
{ "\$group" : { "_id" : "\$cust_id", "total" : { "\$sum" : "\$amount" } } }
]
""")
for doc in Mongoc.aggregate(collection, bson_pipeline)
println(doc)
end
```
The result of the script above is:
```julia
BSON("{ "_id" : "B212", "total" : 200 }")
BSON("{ "_id" : "A123", "total" : 750 }")
```
A **Map-Reduce** operation can be executed with `Mongoc.command_simple` or `Mongoc.read_command`.
```julia
input_collection_name = "aggregation-collection"
output_collection_name = "order_totals"
query = Mongoc.BSON("""{ "status" : "A" }""")
# use `Mongoc.BSONCode` to represent JavaScript elements in BSON
mapper = Mongoc.BSONCode(""" function() { emit( this.cust_id, this.amount ); } """)
reducer = Mongoc.BSONCode(""" function(key, values) { return Array.sum( values ) } """)
map_reduce_command = Mongoc.BSON()
map_reduce_command["mapReduce"] = input_collection_name
map_reduce_command["map"] = mapper
map_reduce_command["reduce"] = reducer
map_reduce_command["out"] = output_collection_name
map_reduce_command["query"] = query
result = Mongoc.read_command(database, map_reduce_command)
println(result)
for doc in Mongoc.find(database["order_totals"])
println(doc)
end
```
The result of the script above is:
```julia
BSON("{ "result" : "order_totals", "timeMillis" : 135, "counts" : { "input" : 3, "emit" : 3, "reduce" : 1, "output" : 2 }, "ok" : 1.0 }")
BSON("{ "_id" : "A123", "value" : 750.0 }")
BSON("{ "_id" : "B212", "value" : 200.0 }")
```
## "distinct" command
This example demonstrates the `distinct` command,
based on [libmongoc docs](http://mongoc.org/libmongoc/current/distinct-mapreduce.html).
```julia
import Mongoc
client = Mongoc.Client()
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
collection = client["my-database"]["my-collection"]
append!(collection, docs)
distinct_cmd = Mongoc.BSON()
distinct_cmd["distinct"] = "my-collection"
distinct_cmd["key"] = "status"
result = Mongoc.command_simple(client["my-database"], distinct_cmd)
```
Which yields:
```julia
BSON("{ "values" : [ "A", "D" ], "ok" : 1.0 }")
```
## Find and Modify
Use `Mongoc.find_and_modify` to query and update documents in a single pass.
```julia
#
# populate a new collection
#
collection = client["database_name"]["find_and_modify"]
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
append!(collection, docs)
#
# updates the item with amount 5000 with status "N"
#
query = Mongoc.BSON("amount" => 500)
reply = Mongoc.find_and_modify(
collection,
query,
update = Mongoc.BSON("""{ "\$set" : { "status" : "N" } }"""),
flags = Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW # will return the new version of the document
)
modified_doc = reply["value"]
@test modified_doc["status"] == "N"
#
# UPSERT example: if the queried item is not found, it is created
#
query = Mongoc.BSON("""{ "cust_id" : "C555", "amount" : 10, "status" : "X" }""")
reply = Mongoc.find_and_modify(
collection,
query,
update = Mongoc.BSON("""{ "\$set" : { "status" : "S" } }"""),
flags = Mongoc.FIND_AND_MODIFY_FLAG_UPSERT | Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW
)
new_document = reply["value"]
@test new_document["cust_id"] == "C555"
@test new_document["amount"] == 10
@test new_document["status"] == "S"
#
# Update sorted with selected fields
#
query = Mongoc.BSON("""{ "amount" : { "\$lt" : 300 } }""")
update = Mongoc.BSON("""{ "\$set" : { "status" : "Z" } }""")
fields = Mongoc.BSON("""{ "amount" : 1, "status" : 1 }""")
sort = Mongoc.BSON("""{ "amount" : 1 }""")
reply = Mongoc.find_and_modify(
collection,
query,
update=update,
sort=sort,
fields=fields,
flags=Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW)
new_document = reply["value"]
@test new_document["amount"] == 10
@test new_document["status"] == "Z"
@test !haskey(new_document, "cust_id")
```
## Create Index
Use `Mongoc.write_command` to issue a `createIndexes` command to the database.
```julia
database = client[DB_NAME]
collection_name = "index_collection"
collection = database[collection_name]
let
items = [
Mongoc.BSON("_id" => 1, "group" => "g1"),
Mongoc.BSON("_id" => 2, "group" => "g1"),
Mongoc.BSON("_id" => 3, "group" => "g2")
]
append!(collection, items)
end
create_indexes_cmd = Mongoc.BSON(
"createIndexes" => collection_name,
"indexes" => [ Mongoc.BSON("key" => Mongoc.BSON("group" => 1), "name" => "group_index") ]
)
reply = Mongoc.write_command(database, create_indexes_cmd)
@assert reply["ok"] == 1
```
See also: http://mongoc.org/libmongoc/current/create-indexes.html.
| Mongoc | https://github.com/felipenoris/Mongoc.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 622 | using Pkg
Pkg.add("Documenter")
using Documenter, QuantizedArrays
# Make src directory available
push!(LOAD_PATH,"../src/")
# Make documentation
makedocs(
modules = [QuantizedArrays],
format = Documenter.HTML(),
sitename = " ",
authors = "Corneliu Cofaru, 0x0α Research",
clean = true,
debug = true,
pages = [
"Introduction" => "index.md",
"Usage examples" => "examples.md",
"API Reference" => "api.md",
]
)
# Deploy documentation
deploydocs(
repo = "github.com/zgornel/QuantizedArrays.jl.git",
target = "build",
deps = nothing,
make = nothing
)
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 2612 | ###################################################################################
# 'dko' ,, :NM. #
# 'Ol..'lO' d, od .M. #
# ,W' ,W, .. .. Xl ... .. .M. #
# K0 K0 ,OX 'kW ox,,dk cNklckX. cNOcc ;OX lxcclWK '0c,l0. .Kx:cdM. #
# Wk ON cX :W . Xc Kk Xo Xc cX .. OO .W: lN Xx ,M. #
# X0 KK cX :W cOollNl Kl 0o Xc cX .Kx ;MdcccoO..Mc .M. #
# :W. .M; cN cW 'M, Kl Kl 0o Xc cX .Nl 'M, ' Wo 'M. #
# ;0:. .:0; .Wl.;OW. Xx. ;Wd. .Xd. .Kx. 0d d,.dN. ,Wd...x' l0. .do :N;..xM:.#
# ':oNc .:c..,, ;c:.',' ,,,. ,,,' .:c, ',,, .,,,,,, .:c:. .:c, ,,.#
# .kK, #
# #
# .... ..... ... ... #
# ,::::::; ,MMMM, XMMMx :::::::. ;MMo kMM. '::;::, #
# XMMMMMMX ,MMMM, XMMMx .MMMMMMMd ;MMo kMM. 0MMWMM0 #
# XMMMMMMX kOOo'''' cOOO,'''. .MMMMMMMd '':OOO;'' 0MMWMM0 #
# XMMMMMMX WMMx xMMM .MMMMMMMd :MMM' 0MMX #
# XMMMMMMX WMMx xMMM .MMMMMMMd :MMM' 0MMX #
# OWWWMMMMMMX WMMx xMMM 'WWNMMMMMMMd :MMM' xWWWMMX #
# 0MMWMMMMMMX WMMx xMMM 'MMWMMMMMMMd :MMM' kMMWMMX #
# 0MMWMMMMMMX WMMx xMMM 'MMWMMMMMMMd :MMM' kMMWMMX #
# #
###################################################################################
# QuantizedArrays.jl - Array quantization and compression, written at 0x0α Research
# by Corneliu Cofaru, 2019
__precompile__(true)
"""
QuantizedArrays.jl - array quantization and compression.
"""
module QuantizedArrays
using LinearAlgebra,
InteractiveUtils,
StatsBase,
Distances,
Clustering
export QuantizedArray,
QuantizedVector,
QuantizedMatrix,
ArrayQuantizer,
CodeBook,
quantize,
build_quantizer,
build_codebooks
include("defaults.jl")
include("utils.jl")
include("codebook.jl")
include("codebook_algorithms.jl")
include("quantizer.jl")
include("interface.jl")
end # module
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 4835 | """
CodeBook{U<:Unsigned,T}
The codebook structure. It holds the codes corresponding
to the vector prototypes and the mapping bethween the codes
and prototypes.
# Fields
* `codes::Vector{U}` the codes
* `vectors::Matrix{T}` the prototypes
* `codemap::Dict{U,Int}` mapping from code to column in `vectors`
"""
struct CodeBook{U<:Unsigned,T}
codes::Vector{U}
vectors::Matrix{T}
codemap::Dict{U,Int}
end
# Constructors
CodeBook(codes::Vector{U}, vectors::Matrix{T}) where {U,T} = begin
length(codes) != size(vectors, 2) &&
throw(DimensionMismatch("Dimension of codes and vectors are inconsistent"))
codemap = Dict{U, Int}(c => i for (i,c) in enumerate(codes))
return CodeBook(codes, vectors, codemap)
end
CodeBook{U}(vectors::Matrix{T}) where {U,T} = begin
k = size(vectors,2)
nb = TYPE_TO_BITS[U]
nbk = TYPE_TO_BITS[quantized_eltype(k)]
nbk > nb && throw(ErrorException("$k vectors cannot be coded in $nb bits."))
codes = Vector{U}(0:k-1)
codemap = Dict{U, Int}(c => i for (i,c) in enumerate(codes))
return CodeBook(codes, vectors, codemap)
end
CodeBook{U,T}(vectors::Matrix{T2}) where {U,T<:Integer,T2} =
CodeBook{U}(round.(T, vectors))
CodeBook{U,T}(vectors::Matrix{T2}) where {U,T<:AbstractFloat,T2} =
CodeBook{U}(convert.(T, vectors))
CodeBook(vectors::Matrix{T}) where {T} =
CodeBook{quantized_eltype(size(vectors, 2)), T}(vectors)
# Show method
Base.show(io::IO, cb::CodeBook{U,T}) where {U,T} = begin
len_vecs, num_codes = size(cb.vectors)
print(io, "CodeBook{$U,$T} $(num_codes) codes, $(len_vecs)-element vectors")
end
# Basic indexing: for a key, get the vector
Base.getindex(cb::CodeBook{U,T}, key::U) where {U,T} =
cb.vectors[:, cb.codemap[key]]
"""
encode(codebook, aa [;distance=DEFAULT_DISTANCE])
Encodes the input array aa using `distance` to calculate the
closest vector prototype from the `codebook`.
"""
function encode(cb::CodeBook{U,T},
aa::AbstractMatrix{T};
distance::Distances.PreMetric=DEFAULT_DISTANCE
) where {U,T}
dists = Distances.pairwise(distance, cb.vectors, aa, dims=2) # distances between codebook vectors and data
best_idx = getindex(findmin(dists, dims=1), 2) # get positions vector of all minima
best_idx_cols = vec(getindex.(best_idx, 1)) # get row values from positions
return cb.codes[best_idx_cols] # get codes corresponding to minima
end
"""
decode(codebook, codes)
Returns a partial array reconstruction for using the `codes` and `codebook`.
"""
function decode(cb::CodeBook{U,T}, codes::Vector{U}) where {U,T}
m, n = size(cb.vectors, 1), length(codes)
aa = Matrix{T}(undef, m, n)
@inbounds @simd for i in 1:n
aa[:,i] = cb[codes[i]]
end
return aa
end
"""
build_codebooks(X, k, m, U [;method=DEFAULT_METHOD, distance=DEFAULT_DISTANCE, kwargs])
Generates `m` codebooks of `k` prototypes each for the input matrix `X`
using the algorithm specified my `method` and distance `distance`.
Specific codebook aglorithm keyword arguments can be specified as well.
# Arguments
* `X::AbstractMatrix{T}` input matrix of type `T`
* `k::Int` number of prototypes/codebook
* `m::Int` number of codebooks
* `U::Type{<:Unsigned}` type for codebook codes
# Keyword arguments
* `method::Symbol` the algorithm to be employed for codebook
generation; possible values are `:sample` (default), `:pq` for
classical k-means clustering codebooks and `:opq` for 'cartesian'
k-means clustering codebooks
* `distance::PreMetric` the distance to be used in the
codebook generation methods and data encoding
* `kwargs...` other codebook generation algorithm specific
keyword arguments such as `maxiter::Int`.
"""
function build_codebooks(X::AbstractMatrix{T},
k::Int,
m::Int,
::Type{U};
method::Symbol=DEFAULT_METHOD,
distance::Distances.PreMetric=DEFAULT_DISTANCE,
kwargs...) where {U,T}
nrows, ncols = size(X)
k = min(k, ncols) # number of codes for a quantizer
m = ifelse(method == :rvq, m, min(m, nrows)) # number of quantizers
R = diagm(0=>ones(T, nrows))
if method == :sample
vectors = sampling_codebooks(X, k, m) # does not use distances
elseif method == :pq
vectors = pq_codebooks(X, k, m, distance=distance; kwargs...)
elseif method == :opq
vectors, R = opq_codebooks(X, k, m, distance=distance; kwargs...)
elseif method == :rvq
vectors = rvq_codebooks(X, k, m, distance=distance; kwargs...)
else
@error "Unknown codebook generation method '$(method)'"
end
return map(CodeBook{U,T}, vectors), R
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 4541 | """
sampling_codebooks(X, k, m)
Build `m` codebooks for input matrix `X` by sampling `k` prototype vectors.
"""
function sampling_codebooks(X::AbstractMatrix{T}, k::Int, m::Int) where {T}
nrows, ncols = size(X)
cbooks = Vector{Matrix{T}}(undef, m)
@inbounds for i in 1:m
rr = rowrange(nrows, m, i)
vectors = Matrix{T}(X[rr, sample(1:ncols, k, replace=false)])
cbooks[i] = vectors
end
return cbooks
end
"""
pq_codebooks(X, k, m [;distance=DEFAULT_DISTANCE, maxiter=DEFAULT_PQ_MAXITER])
Build `m` codebooks for input matrix `X` using `k` sub-space centers obtained
using k-means clustering, the distance `distance` and `maxiter` iterations.
# References:
* [Jègou et al. 2011](https://lear.inrialpes.fr/pubs/2011/JDS11/jegou_searching_with_quantization.pdf)
"""
function pq_codebooks(X::AbstractMatrix{T}, k::Int, m::Int;
distance::Distances.PreMetric=DEFAULT_DISTANCE,
maxiter::Int=DEFAULT_PQ_MAXITER) where {T}
nrows = size(X, 1)
cbooks = Vector{Matrix{T}}(undef, m)
@inbounds for i in 1:m
rr = rowrange(nrows, m, i)
model = kmeans(X[rr, :], k,
maxiter=maxiter,
distance=distance,
init=:kmpp,
display=:none)
cbooks[i] = model.centers
end
return cbooks
end
"""
opq_codebooks(X, k, m [;distance=DEFAULT_DISTANCE, maxiter=DEFAULT_PQ_MAXITER])
Build `m` codebooks for input matrix `X` using `k` sub-space centers obtained
using 'cartesian' k-means clustering, the distance `distance` and `maxiter` iterations.
# References:
* [Ge et al. 2014](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/opq_tr.pdf)
"""
function opq_codebooks(X::AbstractMatrix{T}, k::Int, m::Int;
distance::Distances.PreMetric=DEFAULT_DISTANCE,
maxiter::Int=DEFAULT_OPQ_MAXITER) where {T}
# Initialize R, rotated data
nrows, ncols = size(X)
X̂ = zeros(T, size(X))
R = diagm(0 => ones(T, nrows))
Xr = R * X
# Initialize codebooks, codes
cweights = zeros(Int, k)
costs = zeros(ncols)
counts = zeros(Int, k)
unused = Int[]
to_update_z = zeros(Bool, k)
codes = fill(zeros(Int, ncols), m)
cbooks = sampling_codebooks(X, k, m)
@inbounds for i in 1:m
rr = rowrange(nrows, m, i)
dists = Distances.pairwise(distance, cbooks[i], Xr[rr, :], dims=2)
Clustering.update_assignments!(dists, true, codes[i], costs, counts, to_update_z, unused)
X̂[rr,:] .= cbooks[i][:, codes[i]]
end
# Run optimization
to_update = fill(ones(Bool, k), m)
for it = 1:maxiter
# Update R using orthogonal Procustes closed form solution
# and update rotated data matrix X̂
U, _, V = svd(X * X̂', full=false)
R = V * U'
Xr = R * X
@inbounds for i in 1:m
rr = rowrange(nrows, m, i)
# Update subspace cluster centers
Clustering.update_centers!(Xr[rr, :], nothing, codes[i], to_update[i], cbooks[i], cweights)
# Update subspace data assignments
dists = Distances.pairwise(distance, cbooks[i], Xr[rr, :], dims=2)
Clustering.update_assignments!(dists, false, codes[i], costs, counts, to_update[i], unused)
X̂[rr, :] .= cbooks[i][:, codes[i]]
end
@debug "OPQ: Iteration $it, error = $(sum((R'*X̂ .- X).^2)./ncols)"
end
return cbooks, R
end
"""
rvq_codebooks(X, k, m [;distance=DEFAULT_DISTANCE, maxiter=DEFAULT_RVQ_MAXITER])
Build `m` codebooks for input matrix `X` using `k` layers of residual vector cluster centers,
obtained using k-means clustering, the distance `distance` and `maxiter` iterations.
# References:
* [Chen et al. 2010](https://www.mdpi.com/1424-8220/10/12/11259/htm)
"""
function rvq_codebooks(X::AbstractMatrix{T}, k::Int, m::Int;
distance::Distances.PreMetric=DEFAULT_DISTANCE,
maxiter::Int=DEFAULT_RVQ_MAXITER) where {T}
nrows = size(X, 1)
cbooks = Vector{Matrix{T}}(undef, m)
Xr = copy(X)
@inbounds for i in 1:m
model = kmeans(Xr, k,
maxiter=maxiter,
distance=distance,
init=:kmpp,
display=:none)
cbooks[i] = model.centers
codes = model.assignments
Xr .-= cbooks[i][:, codes]
end
return cbooks
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 441 | # Default parameter values
const DEFAULT_K = 256
const DEFAULT_M = 1
const DEFAULT_METHOD = :sample
const DEFAULT_DISTANCE = Distances.SqEuclidean()
const MAX_BITS = 128
const BITS_TO_TYPE = Dict(round(Int, log2(typemax(typ))) => typ
for typ in subtypes(Unsigned))
const TYPE_TO_BITS = Dict(t=>b for (b,t) in BITS_TO_TYPE)
const DEFAULT_PQ_MAXITER = 25
const DEFAULT_OPQ_MAXITER = 25
const DEFAULT_RVQ_MAXITER = 25
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 5187 | """
QuantizedArray{Q<:AbstractQuantization,U<:Unsigned,D<:PreMetric,T,N} <: AbstractArray{T,N}
A quantized array. It represents a 'quantized' representation of an original
array, equivalent to a lossy compressed version.
# Fields
* `quantizer::ArrayQuantizer{Q,U,D,T,N}` the quantized of the array
* `data::Matrix{U}` the actual compressed representation of the quantized array
"""
struct QuantizedArray{Q,U<:Unsigned,D<:Distances.PreMetric,T,N} <: AbstractArray{T,N}
quantizer::ArrayQuantizer{Q,U,D,T,N}
data::Matrix{U}
end
# Aliases
const QuantizedVector{Q,U,D,T} = QuantizedArray{Q,U,D,T,1}
const QuantizedMatrix{Q,U,D,T} = QuantizedArray{Q,U,D,T,2}
const OrthogonalQuantizedArray{U,D,T,N} = QuantizedArray{OrthogonalQuantization,U,D,T,N}
const OrthogonalQuantizedMatrix{U,D,T,N} = QuantizedArray{OrthogonalQuantization,U,D,T,2}
const AdditiveQuantizedArray{U,D,T,N} = QuantizedArray{AdditiveQuantization,U,D,T,N}
const AdditiveQuantizedMatrix{U,D,T,N} = QuantizedArray{AdditiveQuantization,U,D,T,2}
# Main outer constructor
function QuantizedArray(aa::AbstractArray{T,N};
k::Int=DEFAULT_K,
m::Int=DEFAULT_M,
method::Symbol=DEFAULT_METHOD,
distance::Distances.PreMetric=DEFAULT_DISTANCE,
kwargs...) where {T,N}
@assert N <=2 "Array quantization is supported only for Vectors and Matrices"
@assert k >= 1 "`k` has to be larger or equal to 1"
@assert m >= 1 "`m` has to be larger or equal to 1"
method != :rvq && @assert rem(nvars(aa), m) == 0 "`m` has to divide exactly $(nvars(aa))"
method != :sample && @assert T<:AbstractFloat "Input array has to have AbstractFloat elements"
aq = build_quantizer(aa, k=k, m=m, method=method, distance=distance; kwargs...)
data = quantize_data(aq, aa)
return QuantizedArray(aq, data)
end
"""
quantize(aq, aa)
Quantize an array `aa` using an array quantizer `aq`.
"""
function quantize(aq::ArrayQuantizer{Q,U,D,T,N}, aa::AbstractArray{T,N}) where {Q,U,D,T,N}
new_aq = ArrayQuantizer(aq.quantization, size(aa), codebooks(aq), aq.k, aq.distance, aq.rot)
data = quantize_data(new_aq, aa)
return QuantizedArray(new_aq, data)
end
"""
quantize(aa; [;kwargs])
Quantize an array `aa`.
# Arguments
* `aa::AbstractArray` input array to be quantized
# Keyword arguments
* `k::Int` the number of vector prototypes in each codebook
* `m::Int` the number of codebooks
* `method::Symbol` the algorithm to be employed for codebook
generation; possible values are `:sample` (default), `:pq` for
classical k-means clustering codebooks and `:opq` for 'cartesian'
k-means clustering codebooks
* `distance::PreMetric` the distance to be used in the
codebook generation methods and data encoding
Other codebook generation algorithm specific keyword arguments
such as `maxiter::Int` can be specified as well.
"""
quantize(aa::AbstractArray{T,N}; kwargs...) where {T,N} = QuantizedArray(aa; kwargs...)
# eltype, size, length
Base.eltype(qa::QuantizedArray{Q,U,D,T,N}) where {Q,U,D,T,N} = T
Base.size(qa::QuantizedArray) = qa.quantizer.dims
Base.IndexStyle(::Type{<:QuantizedArray}) = IndexLinear()
"""
quantizer(qa)
Access the quantizer field of a quantized array `qa`.
"""
quantizer(qa::QuantizedArray) = qa.quantizer
"""
nvars(aa)
Returns the number of variables of an array `aa`. For vectors,
the value is always `1`, for matrices it is the number of
rows in the matrix.
"""
nvars(av::AbstractVector) = 1
nvars(am::AbstractMatrix) = size(am, 1)
# Indexing interface: getindex, setindex!
@inline function Base.getindex(qa::OrthogonalQuantizedArray, i::Int)
cbooks = codebooks(quantizer(qa))
m = length(cbooks)
col, row, cidx = _indices(nvars(qa), m, i)
qkey = getindex(qa.data, cidx, col)
return cbooks[cidx][qkey][row]
end
@inline function Base.getindex(qa::OrthogonalQuantizedMatrix, i::Int, j::Int)
cbooks = codebooks(quantizer(qa))
m = length(cbooks)
_, row, cidx = _indices(nvars(qa), m, i)
qkey = getindex(qa.data, cidx, j)
return cbooks[cidx][qkey][row]
end
@inline function Base.getindex(qa::AdditiveQuantizedArray, i::Int)
cbooks = codebooks(quantizer(qa))
m = length(cbooks)
col, row = divrem(i[1]-1, nvars(qa)) .+ 1
return sum(cbooks[cidx][getindex(qa.data, cidx, col)][row] for cidx in 1:m)
end
@inline function Base.getindex(qa::AdditiveQuantizedMatrix, i::Int, j::Int)
cbooks = codebooks(quantizer(qa))
m = length(cbooks)
return sum(cbooks[cidx][getindex(qa.data, cidx, j)][i] for cidx in 1:m)
end
function _indices(n::Int, m::Int, I::Vararg{Int,N}) where {N}
step = Int(n/m)
col, r = divrem(I[1]-1, n) .+ 1 # column, row in uncompressed data
cidx, row = divrem(r-1, step) .+ 1 # codebook index, codebook vector row
return col, row, cidx
end
# setindex! not supported
Base.setindex!(qa::QuantizedArray, i::Int) =
throw(ErrorException("setindex! not supported on QuantizedArrays"))
Base.setindex!(qa::QuantizedArray, I::Vararg{Int, N}) where {N}=
throw(ErrorException("setindex! not supported on QuantizedArrays"))
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 5001 | """
Abstract quantization type. Its subtypes are two singletons
corresponding to additive/residual and orthogonal quantization.
"""
abstract type AbstractQuantization end
struct OrthogonalQuantization <: AbstractQuantization end
struct AdditiveQuantization <: AbstractQuantization end
"""
ArrayQuantizer{Q,U,D,T,N}
The array quantizer object. It transforms an array with elements
of type `T` into a 'quantized' version with elemetns of type `U`.
# Fields
* `quantization::Q` type of quantization employed i.e. additive, orthogonal
* `dims::NTuple{N,Int}` the original array dimensionality
* `codebooks::Vector{CodeBook{U,T}}` the codebooks
* `k::Int` the number of vector prototypes in each codebooks
* `distance::D` the distance employed
* `rot::Matrix{T}` rotation matrix
"""
struct ArrayQuantizer{Q,U,D,T,N}
quantization::Q # type of quantization
dims::NTuple{N, Int} # original array size
codebooks::Vector{CodeBook{U,T}} # codebooks
k::Int # number of codes/quantizer
distance::D
rot::Matrix{T}
end
# Aliases
const OrthogonalQuantizer{U,D,T,N} = ArrayQuantizer{OrthogonalQuantization,U,D,T,N}
const AdditiveQuantizer{U,D,T,N} = ArrayQuantizer{AdditiveQuantization,U,D,T,N}
# show methods
Base.show(io::IO, aq::ArrayQuantizer{Q,U,D,T,N}) where {Q,U,D,T,N} = begin
m = length(codebooks(aq))
quantstr = ifelse(Q <: OrthogonalQuantization, "OrthogonalQuantizer",
"AdditiveQuantizer")
qstr = ifelse(m==1, "quantizer", "quantizers")
cstr = ifelse(aq.k==1, "code", "codes")
print(io, "$quantstr{$U,$D,$T,$N}, $m $qstr, $(aq.k) $cstr")
end
# Constructors
ArrayQuantizer(aa::AbstractMatrix{T};
k::Int=DEFAULT_K,
m::Int=DEFAULT_M,
method::Symbol=DEFAULT_METHOD,
distance::Distances.PreMetric=DEFAULT_DISTANCE,
kwargs...) where {T} = begin
U = quantized_eltype(k)
quant = quantization_type(method)
cbooks, rot = build_codebooks(aa, k, m, U, method=method,
distance=distance; kwargs...)
return ArrayQuantizer(quant, size(aa), cbooks, k, distance, rot)
end
ArrayQuantizer(aa::AbstractVector{T};
k::Int=DEFAULT_K,
m::Int=DEFAULT_M,
method::Symbol=DEFAULT_METHOD,
distance::Distances.PreMetric=DEFAULT_DISTANCE,
kwargs...) where {T} = begin
aq = ArrayQuantizer(aa', k=k, m=m, method=method, distance=distance; kwargs...)
return ArrayQuantizer(aq.quantization, size(aa), codebooks(aq), k, distance, aq.rot)
end
"""
build_quantizer(aa [;kwargs])
Builds an array quantizer using the input array `aa`.
# Keyword arguments
* `k::Int` the number of vector prototypes in each codebook
* `m::Int` the number of codebooks
* `method::Symbol` the algorithm to be employed for codebook
generation; possible values are `:sample` (default), `:pq` for
classical k-means clustering codebooks and `:opq` for 'cartesian'
k-means clustering codebooks
* `distance::PreMetric` the distance to be used in the
codebook generation methods and data encoding
Other codebook generation algorithm specific keyword arguments
such as `maxiter::Int` can be specified as well.
"""
build_quantizer(aa::AbstractArray; kwargs...) = ArrayQuantizer(aa; kwargs...)
"""
codebooks(aq)
Access the codebooks field of the array quantizer `aq`.
"""
codebooks(aq::ArrayQuantizer) = aq.codebooks
"""
quantize_data(aq, aa)
Returns a quantized version of the array `aa` using the array quantizer `aq`.
"""
function quantize_data(aq::OrthogonalQuantizer{U,D,T,2}, aa::AbstractMatrix{T}) where {U,D,T}
nrows, ncols = size(aa)
@assert nrows == aq.dims[1] "Quantized matrix needs to have $nrows rows"
cbooks = codebooks(aq)
m = length(cbooks)
qa = Matrix{U}(undef, m, ncols)
_aa = aq.rot * aa
@inbounds @simd for i in 1:m
rr = rowrange(nrows, m, i)
qa[i,:] = encode(cbooks[i], _aa[rr,:], distance=aq.distance)
end
return qa
end
function quantize_data(aq::AdditiveQuantizer{U,D,T,2}, aa::AbstractMatrix{T}) where {U,D,T}
nrows, ncols = size(aa)
@assert nrows == aq.dims[1] "Quantized matrix needs to have $nrows rows"
cbooks = codebooks(aq)
m = length(cbooks)
qa = Matrix{U}(undef, m, ncols)
aac = copy(aa)
@inbounds @simd for i in 1:m
qa[i,:] = encode(cbooks[i], aac, distance=aq.distance)
aac .-= decode(cbooks[i], qa[i,:])
end
return qa
end
function quantize_data(aq::ArrayQuantizer{Q,U,D,T,1}, aa::AbstractVector{T}) where {Q,U,D,T}
nrows = aq.dims[1]
@assert nrows == length(aa) "Quantized vector needs to have $nrows elements"
aat = aa' # use transpose as a single row matrix and quantize that
aqt = ArrayQuantizer(aq.quantization, size(aat), codebooks(aq), aq.k, aq.distance, aq.rot)
qat = quantize_data(aqt, aat)
return qat
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 1023 | """
rowrange(n, m, i)
Utility function that returns a range based on an iteration index `i`,
the number of elements `n` and number of ranges `m`.
"""
@inline rowrange(n::Int, m::Int, i::Int) = begin
rs = floor(Int, n/m) # row step
rr = rs*(i-1)+1 : rs*i # row range
return rr
end
"""
quantized_eltype(k)
Determinies the minimum `Unsigned` type that can hold the value `k`.
"""
quantized_eltype(k) = begin
b = clamp(log2(k), 1, MAX_BITS)
minbits = 1024
local mintype
for (nbits, utype) in BITS_TO_TYPE
if b <= nbits && nbits < minbits
minbits = nbits
mintype = utype
end
end
if minbits > MAX_BITS
@error "Number is too large to fit in $MAX_BITS bits."
end
return mintype
end
"""
quantization_type(method)
Returns a quantization type based on the quantization method to be employed.
"""
quantization_type(method::Symbol) = begin
ifelse(method == :rvq, AdditiveQuantization(), OrthogonalQuantization())
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 1745 | @testset "Codebook generation" begin
# Generate some random data
n = 100
dim = 2
U = UInt8
Xfloat = rand(dim, n)
codes = U.(collect(1:n))
# Test constructors
cb = CodeBook(codes, Xfloat)
@test cb isa CodeBook{U, eltype(Xfloat)}
@test size(cb.vectors) == size(Xfloat)
@test length(cb.codes) == length(codes)
for (code, idx) in cb.codemap # tests codemap creation, getindex
@test cb[code] == Xfloat[:, cb.codemap[code]] == Xfloat[:, idx]
end
@test_throws DimensionMismatch CodeBook(codes, rand(2,n-3))
@test_throws ErrorException CodeBook{UInt8}(rand(2,257))
for T in [UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64,
Float16, Float32, Float64]
for U in [UInt8, UInt16] # not really necessary for UInt32, UInt64
X = rand(T, dim, Int.(typemax(U)))
@test CodeBook(X) isa CodeBook{U,T}
if T<:Unsigned && QuantizedArrays.TYPE_TO_BITS[T] <= QuantizedArrays.TYPE_TO_BITS[U]
@test CodeBook{U,U}(X) isa CodeBook{U,U}
elseif T<:Unsigned && QuantizedArrays.TYPE_TO_BITS[T] >= QuantizedArrays.TYPE_TO_BITS[U]
@test_throws InexactError CodeBook{U,U}(X)
elseif T<:AbstractFloat
@test CodeBook{U, Float64}(X) isa CodeBook{U, Float64}
end
end
end
@test QuantizedArrays.encode(cb, Xfloat) == cb.codes
#TODO(Corneliu): Functional testing of codebook
# generation algorithms i.e. `build_codebooks`
T = Float32
U = UInt16
m = 2
dim = 4
npoints = 10
for method in [:pq, :opq, :rvq]
cbs, rot = QuantizedArrays.build_codebooks(rand(T, dim, npoints),
2, m, U, method=method)
@test cbs isa Vector{CodeBook{U,T}}
@test length(cbs) == m
@test rot isa Matrix{T}
@test size(rot) == (dim, dim)
end
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 3943 | @testset "Array interface" begin
# Test aliases
@test QuantizedArray(rand(10), k=2, method=:sample) isa QuantizedVector
@test QuantizedArray(rand(2, 10), k=2, method=:sample) isa QuantizedMatrix
# Test outer constructor checks
@test_throws AssertionError QuantizedArray(rand(2, 2, 2), k=2, m=1, method=:sample)
@test_throws AssertionError QuantizedArray(rand(2, 10), k=-1, m=1, method=:sample)
@test_throws AssertionError QuantizedArray(rand(2, 10), k=2, m=-1, method=:sample)
@test_throws AssertionError QuantizedArray(rand(3, 10), k=2, m=2, method=:sample)
for method in [:pq, :opq, :rvq]
@test_throws AssertionError QuantizedArray(rand([1,2,3], 3, 10), k=2, m=2, method=method)
end
# Test quantize function
T = Float32
X = rand(T, 3, 10)
qa = QuantizedArray(X, k=2, m=3, method=:sample)
@test QuantizedArrays.quantizer(qa) === qa.quantizer
@test quantize(QuantizedArrays.quantizer(qa), X) == qa
# Test other interface parts
@test size(qa) == qa.quantizer.dims
@test eltype(qa) == T
@test QuantizedArrays.nvars(rand(10)) == 1
@test QuantizedArrays.nvars(rand(2, 10)) == 2
# Test setindex!
@test_throws CanonicalIndexError qa[1] = one(T)
@test_throws CanonicalIndexError qa[1,1] = one(T)
# Test orthogonal reconstruction: getindex
# vector
truevector = [0, 1, 0, 2, 0]
codes = [0x00, 0x01, 0x02]
vectors = [0 1 2]
data = [0x00 0x01 0x00 0x02 0x00]
cb = CodeBook(codes, vectors)
q = QuantizedArrays.OrthogonalQuantization()
rot = diagm(0=>ones(eltype(truevector), length(truevector)))
aq = ArrayQuantizer(q, size(truevector), [cb], length(codes), Distances.SqEuclidean(), rot)
qa = QuantizedArray(aq, data)
@test qa[:] == truevector
@test all(qa .== truevector)
# matrix
truematrix = [0 1 0 2 0 3;
0 1 0 2 0 3]
codes = [0x00, 0x01, 0x02, 0x03]
vectors = [0 1 2 3;
0 1 2 3]
data = [0x00 0x01 0x00 0x02 0x00 0x03]
cb = CodeBook(codes, vectors)
q = QuantizedArrays.OrthogonalQuantization()
rot = diagm(0=>ones(eltype(truematrix), size(truematrix, 1)))
aq = ArrayQuantizer(q, size(truematrix), [cb], length(codes), Distances.SqEuclidean(), rot)
qa = QuantizedArray(aq, data)
@test qa[:] == truematrix[:]
@test qa[:,:] == truematrix
@test all(qa .== truematrix)
# Test aditive reconstruction: getindex
# vector
truevector = [0, 1, 0, 2, 0] .+ [-1, -1, 1, 1, 2]
codes = [0x00, 0x01, 0x02]
vectors1 = [0 1 2]
vectors2 = [-1 1 2]
data = [0x00 0x01 0x00 0x02 0x00;
0x00 0x00 0x01 0x01 0x02]
cbs = [CodeBook(codes, vectors1), CodeBook(codes, vectors2)]
q = QuantizedArrays.AdditiveQuantization()
rot = diagm(0=>ones(eltype(truevector), length(truevector)))
aq = ArrayQuantizer(q, size(truevector), cbs, length(codes), Distances.SqEuclidean(), rot)
qa = QuantizedArray(aq, data)
@test qa[:] == truevector
@test all(qa .== truevector)
# matrix
truematrix = [0 1 0 2 0 3;
0 1 0 2 0 3] .+
[ 2 3 1 4 4 1;
-2 -3 -1 -4 -4 -1]
codes = [0x00, 0x01, 0x02, 0x03]
vectors1 = [0 1 2 3;
0 1 2 3]
vectors2 = [1 2 3 4
-1 -2 -3 -4]
data = [0x00 0x01 0x00 0x02 0x00 0x03;
0x01 0x02 0x00 0x03 0x03 0x00]
cbs = [CodeBook(codes, vectors1), CodeBook(codes, vectors2)]
q = QuantizedArrays.AdditiveQuantization()
rot = diagm(0=>ones(eltype(truematrix), size(truematrix, 1)))
aq = ArrayQuantizer(q, size(truematrix), cbs, length(codes), Distances.SqEuclidean(), rot)
qa = QuantizedArray(aq, data)
@test qa[:] == truematrix[:]
@test qa[:,:] == truematrix
@test all(qa .== truematrix)
# Setindex tests
@test_throws ErrorException qa[1] = 1
@test_throws ErrorException qa[1, 1] = 1
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 1653 | @testset "Array quantizer" begin
m = 2
k = 2
Q = QuantizedArrays.OrthogonalQuantization
for T in [UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64,
Float16, Float32, Float64]
for mᵢ in 1:2
X = rand(T[0,1,2,3], m, 10) # values in 0-3 to keep distances small
aqm = build_quantizer(X, k=k, m=mᵢ, method=:sample)
@test aqm isa ArrayQuantizer{Q, UInt8, Distances.SqEuclidean, T, 2}
@test length(aqm.codebooks) == mᵢ
qm = QuantizedArrays.quantize_data(aqm, X)
@test qm isa Matrix{UInt8}
@test size(qm) == (mᵢ, size(X,2))
Xᵥ= rand(T[0,1,2,3,4], 10)
aqv = build_quantizer(Xᵥ, k=k, m=mᵢ, method=:sample)
@test aqv isa ArrayQuantizer{Q, UInt8, Distances.SqEuclidean, T, 1}
@test length(aqv.codebooks) == 1
qv = QuantizedArrays.quantize_data(aqv, Xᵥ)
@test qv isa Matrix{UInt8}
@test length(qv) == length(Xᵥ)
end
end
T = Float32
Twrong = Float16
X = rand(T, m, 100)
m = 2
k = 2
aq = build_quantizer(X, k=k, m=m, method=:sample)
@test QuantizedArrays.codebooks(aq) == aq.codebooks
@test_throws AssertionError QuantizedArrays.quantize_data(aq, rand(T, m+1, 100))
@test_throws MethodError QuantizedArrays.quantize_data(aq, rand(Twrong, m, 100))
# The ArrayQuantizer works with any `m`:
X2 = rand(T, m+1, 100)
aq2 = ArrayQuantizer(X2, k=k, m=m, method=:sample)
@test aq2 isa ArrayQuantizer{Q, UInt8, Distances.SqEuclidean, T, 2}
@test length(aq2.codebooks) == m
aq3 = ArrayQuantizer(X, k=k, m=m+100, method=:sample)
@test aq3 isa ArrayQuantizer{Q, UInt8, Distances.SqEuclidean, T, 2}
@test length(aq3.codebooks) == m
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 217 | module TestQuantizedArrays
using Test
using InteractiveUtils
using LinearAlgebra
using Distances
using QuantizedArrays
include("codebook.jl")
include("quantizer.jl")
include("interface.jl")
include("utils.jl")
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | code | 702 | @testset "Utils" begin
# rowrange
n = 23
v = rand(n)
for m in 1:9
step = floor(Int, n/m)
for i in 1:m
@test QuantizedArrays.rowrange(n, m, i) ==
step*(i-1)+1 : step*i
end
end
# quantized_eltype
for T in subtypes(Unsigned)
k = rand(typemin(T):typemax(T))
@test QuantizedArrays.quantized_eltype(k+1) == T
end
# Quantization type
for qt in [:sample, :pq, :opq, :rvq]
qt == :rvq && @test QuantizedArrays.quantization_type(qt) isa QuantizedArrays.AdditiveQuantization
qt != :rvq && @test QuantizedArrays.quantization_type(qt) isa QuantizedArrays.OrthogonalQuantization
end
end
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | docs | 258 | ## QuantizedArrays Release Notes
v0.1.7
-----
- Bugfixes, dependency updates
v0.1.3
------
- Fixes for OPQ
v0.1.2
------
- Bugfixes, test coverage improvements
v0.1.1
------
- Added RVQ (residual vector quantization)
v0.1.0
------
- Initial version
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | docs | 2884 | 
Array quantization and compression.
[](LICENSE.md)
[](https://travis-ci.org/zgornel/QuantizedArrays.jl)
[](https://coveralls.io/github/zgornel/QuantizedArrays.jl?branch=master)
[](https://zgornel.github.io/QuantizedArrays.jl/stable)
[](https://zgornel.github.io/QuantizedArrays.jl/dev)
## Installation
```julia
Pkg.add("QuantizedArrays")
```
## Examples
- Vector quantization
```julia
using QuantizedArrays
v = collect(1:10);
# Use 3 quantization levels (always 1 codebook)
qv = QuantizedArray(v, k=3)
# 10-element QuantizedArray{QuantizedArrays.OrthogonalQuantization,UInt8,Distances.SqEuclidean,Int64,1}:
# 5
# 5
# 5
# 5
# 5
# 6
# 6
# 6
# 10
# 10
```
- matrix quantization
```julia
using QuantizedArrays
m = reshape(collect(1:60), (6,10))
# 6×10 array{int64,2}:
# 1 7 13 19 25 31 37 43 49 55
# 2 8 14 20 26 32 38 44 50 56
# 3 9 15 21 27 33 39 45 51 57
# 4 10 16 22 28 34 40 46 52 58
# 5 11 17 23 29 35 41 47 53 59
# 6 12 18 24 30 36 42 48 54 60
# use 5 quantization levels (vectors) / codebook and 2 codebooks
qm = QuantizedArray(m, k = 5, m = 2)
# 6×10 QuantizedArray{QuantizedArrays.OrthogonalQuantization,UInt8,Distances.SqEuclidean,Int64,2}:
# 7 7 13 13 31 31 43 43 43 55
# 8 8 14 14 32 32 44 44 44 56
# 9 9 15 15 33 33 45 45 45 57
# 10 10 10 28 28 34 40 46 46 46
# 11 11 11 29 29 35 41 47 47 47
# 12 12 12 30 30 36 42 48 48 48
```
## Features
To keep track with the latest features, please consult [NEWS.md](https://github.com/zgornel/QuantizedArrays.jl/blob/master/NEWS.md) and the [documentation](https://zgornel.github.io/QuantizedArrays.jl/dev).
## License
The code has an MIT license and therefore it is free.
## Reporting Bugs
This is work in progress and bugs may still be present...¯\\_(ツ)_/¯ Do not worry, just [open an issue](https://github.com/zgornel/QuantizedArrays.jl/issues/new) to report a bug or request a feature.
## References
- [Rayuela.jl](https://github.com/una-dinosauria/Rayuela.jl) provides an extensive list of quantization methods implementations as well as good references pertinent to the state-of-the-art.
- [Quantization in signal processing (Wikipedia)](https://en.wikipedia.org/wiki/Quantization_(signal_processing))
- [Vector quantization (Wikipedia)](https://en.wikipedia.org/wiki/Vector_quantization)
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | docs | 60 | ```@index
```
```@autodocs
Modules = [QuantizedArrays]
```
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | docs | 1589 | # Usage examples
Arrays can be quantized through either the `quantize` function or using the `QuantizedArray` constructor directly.
If the quantization is done through sampling, the quantized arrays may differ with each run as the vector prototypes are randomly sampled.
```@repl index
using QuantizedArrays
v = collect(1:10)
qv = quantize(v, k=2) # quantize by sampling 2 prototypes i.e. values
qv = QuantizedArray(v, k=2)
m = reshape(collect(1:60), (6,10))
qm = quantize(m, k=5, m=2) # 5 prototypes, 2 codebooks
qm = QuantizedArray(m, k=5, m=2)
```
The compressed representation of the input arrays is stored in the `data` field and the quantizer in the `quantizer` field
```@repl index
qm.data
qm.quantizer
```
A new array can be quantized using the quantizers
```@repl index
quantize(qv.quantizer, rand(1:10, 5))
quantize(qm.quantizer, rand(1:60, 6, 2))
```
The `:pq` (k-means), `:opq` ('cartesian' k-means) and `:rvq` ('residual') quantization methods work for arrays with `AbstractFloat` elements only and return the same result each run.
```@repl index
quantize(Float32.(v), k=2, method=:pq)
quantize(Float32.(m), k=5, m=2, method=:pq)
```
Indexing can be performed as in regular arrays
```@repl index
qm[1,1]
qm[2,:]
qm[1:1,:]
```
however changing values is not supported
```@repl index
qm[1,1] = 0
```
The element type of the compressed array representation is dynamically calculated to reflect the number of vector prototypes employed
```@repl index
m = rand(1, 10_000);
quantize(m, k=256) # 8 bits are used (UInt8)
quantize(m, k=257) # 16 bits are used (UInt16)
```
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"MIT"
] | 0.1.7 | e772e844d101617b218983bff89fa21c280cd643 | docs | 1255 | ```@meta
CurrentModule=QuantizedArrays
```
# Introduction
`QuantizedArrays` is a package for array quantization and compression. The basic principle is that arrays can be represented through the concatenation of shorter vectors obtained by either sampling or clustering of subspaces in the original data. This effectively compresses the original array with a loss in quality.
## Implemented features
- basic `AbstractArray` interface for vectors, matrices
- quantization types implemented:
- random sampling
- k-mean clustering ([PQ](https://lear.inrialpes.fr/pubs/2011/JDS11/jegou_searching_with_quantization.pdf))
- 'cartesian' k-means clustering ([OPQ](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/opq_tr.pdf))
- residual quantization ([RVQ](https://www.mdpi.com/1424-8220/10/12/11259/htm))
## Installation
Installation can be performed from either inside or outside Julia.
### Git cloning
```
$ git clone https://github.com/zgornel/QuantizedArrays.jl
```
### Julia REPL
The package can be installed from inside Julia with:
```
using Pkg
Pkg.add("QuantizedArrays")
```
or
```
Pkg.add(PackageSpec(url="https://github.com/zgornel/QuantizedArrays.jl", rev="master"))
```
for the latest `master` branch.
| QuantizedArrays | https://github.com/zgornel/QuantizedArrays.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 747 |
using Pkg
Pkg.status()
using Documenter
using ProgressiveHedging
makedocs(modules=[ProgressiveHedging],
format=Documenter.HTML(prettyurls=haskey(ENV,"GITHUB_ACTIONS")),
sitename="ProgressiveHedging.jl",
authors="Jonathan Maack",
pages=["Overview" => "index.md",
"Examples" => map(s -> "examples/$(s)",
sort(readdir(joinpath(@__DIR__, "src", "examples")))
),
"Reference" => map(s -> "api/$(s)",
sort(readdir(joinpath(@__DIR__, "src", "api")))
),
]
)
deploydocs(repo = "github.com/NREL/ProgressiveHedging.jl.git")
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 1313 |
using Pkg
Pkg.activate(@__DIR__)
using ProgressiveHedging
import JuMP
import Ipopt
function two_stage_model(scenario_id::ScenarioID)
model = JuMP.Model(()->Ipopt.Optimizer())
JuMP.set_optimizer_attribute(model, "print_level", 0)
JuMP.set_optimizer_attribute(model, "tol", 1e-12)
JuMP.set_optimizer_attribute(model, "acceptable_tol", 1e-12)
scen = value(scenario_id)
ref = JuMP.@variable(model, x >= 0.0)
stage1 = [ref]
ref = JuMP.@variable(model, y >= 0.0)
stage2 = [ref]
b_s = scen == 0 ? 11.0 : 4.0
c_s = scen == 0 ? 0.5 : 10.0
JuMP.@constraint(model, x + y == b_s)
JuMP.@objective(model, Min, 1.0*x + c_s*y)
return JuMPSubproblem(model,
scenario_id,
Dict(stid(1) => stage1,
stid(2) => stage2)
)
end
scen_tree = two_stage_tree(2)
(niter, abs_res, rel_res, obj, soln_df, phd) = solve(scen_tree,
two_stage_model,
ScalarPenaltyParameter(1.0)
)
@show niter
@show abs_res
@show rel_res
@show obj
@show soln_df
dual_df = retrieve_w(phd)
@show dual_df
raw_values_df = retrieve_no_hats(phd)
@show raw_values_df
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 2156 |
using Pkg
Pkg.activate(@__DIR__)
using ProgressiveHedging
import JuMP
import Ipopt
function two_stage_model(scenario_id::ScenarioID)
model = JuMP.Model(()->Ipopt.Optimizer())
JuMP.set_optimizer_attribute(model, "print_level", 0)
JuMP.set_optimizer_attribute(model, "tol", 1e-12)
JuMP.set_optimizer_attribute(model, "acceptable_tol", 1e-12)
scen = value(scenario_id)
ref = JuMP.@variable(model, x >= 0.0)
stage1 = [ref]
ref = JuMP.@variable(model, y >= 0.0)
stage2 = [ref]
b_s = scen == 0 ? 11.0 : 4.0
c_s = scen == 0 ? 0.5 : 10.0
JuMP.@constraint(model, x + y == b_s)
JuMP.@objective(model, Min, 1.0*x + c_s*y)
return JuMPSubproblem(model,
scenario_id,
Dict(stid(1) => stage1,
stid(2) => stage2)
)
end
scen_tree = two_stage_tree(2)
function my_callback(ext::Dict{Symbol,Any},
phd::PHData,
winf::ProgressiveHedging.WorkerInf,
niter::Int)
# The `ext` dictionary can be used to store things between PH iterations
if niter == 2
ext[:message] = "This is from iteration 2!"
elseif niter == 5
println("Iteration 5 found the message: " * ext[:message])
elseif niter == 10
println("This is iteration 10!")
# We can access the current consensus variable values
for (xhid, xhat) in pairs(consensus_variables(phd))
println("The value of $(name(phd,xhid)) is $(value(xhat)).")
end
end
# Returning false from the callback will terminate PH.
# Here we stop after 20 iterations.
return niter < 20
end
my_cb = Callback(my_callback)
(niter, abs_res, rel_res, obj, soln_df, phd) = solve(scen_tree,
two_stage_model,
ScalarPenaltyParameter(1.0),
callbacks=[my_cb]
)
@show niter
@show abs_res
@show rel_res
@show obj
@show soln_df
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 1388 |
using Distributed
addprocs(2) # add 2 workers
@everywhere using Pkg
@everywhere Pkg.activate(joinpath(@__DIR__, "..", "examples"))
@everywhere using ProgressiveHedging
@everywhere import JuMP
@everywhere import Ipopt
@everywhere function two_stage_model(scenario_id::ScenarioID)
model = JuMP.Model(()->Ipopt.Optimizer())
JuMP.set_optimizer_attribute(model, "print_level", 0)
JuMP.set_optimizer_attribute(model, "tol", 1e-12)
JuMP.set_optimizer_attribute(model, "acceptable_tol", 1e-12)
scen = value(scenario_id)
ref = JuMP.@variable(model, x >= 0.0)
stage1 = [ref]
ref = JuMP.@variable(model, y >= 0.0)
stage2 = [ref]
b_s = scen == 0 ? 11.0 : 4.0
c_s = scen == 0 ? 0.5 : 10.0
JuMP.@constraint(model, x + y == b_s)
JuMP.@objective(model, Min, 1.0*x + c_s*y)
return JuMPSubproblem(model,
scenario_id,
Dict(stid(1) => stage1,
stid(2) => stage2)
)
end
scen_tree = two_stage_tree(2)
(niter, abs_res, rel_res, obj, soln_df, phd) = solve(scen_tree,
two_stage_model,
ScalarPenaltyParameter(1.0)
)
@show niter
@show abs_res
@show rel_res
@show obj
@show soln_df
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 3092 |
using Pkg
Pkg.activate(@__DIR__)
using ProgressiveHedging
import JuMP
import Ipopt
function create_model(scenario_id::ScenarioID)
model = JuMP.Model(()->Ipopt.Optimizer())
JuMP.set_optimizer_attribute(model, "print_level", 0)
JuMP.set_optimizer_attribute(model, "tol", 1e-12)
c = [1.0, 10.0, 0.01]
d = 7.0
a = 16.0
α = 1.0
β = 1.0
γ = 1.0
δ = 1.0
ϵ = 1.0
s1 = 8.0
s2 = 4.0
s11 = 9.0
s12 = 16.0
s21 = 5.0
s22 = 18.0
stage1 = JuMP.@variable(model, x[1:3] >= 0.0)
JuMP.@constraint(model, x[3] <= 1.0)
obj = zero(JuMP.GenericQuadExpr{Float64,JuMP.VariableRef})
JuMP.add_to_expression!(obj, sum(c.*x))
# Second stage
stage2 = Vector{JuMP.VariableRef}()
if scenario_id < scid(2)
vref = JuMP.@variable(model, y >= 0.0)
JuMP.@constraint(model, α*sum(x) + β*y >= s1)
JuMP.add_to_expression!(obj, d*y)
else
vref = JuMP.@variable(model, y >= 0.0)
JuMP.@constraint(model, α*sum(x) + β*y >= s2)
JuMP.add_to_expression!(obj, d*y)
end
push!(stage2, vref)
# Third stage
stage3 = Vector{JuMP.VariableRef}()
if scenario_id == scid(0)
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s11)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
elseif scenario_id == scid(1)
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s12)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
elseif scenario_id == scid(2)
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s21)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
else
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s22)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
end
append!(stage3, vref)
JuMP.@objective(model, Min, obj)
vdict = Dict{StageID, Vector{JuMP.VariableRef}}([stid(1) => stage1,
stid(2) => stage2,
stid(3) => stage3,
])
return JuMPSubproblem(model, scenario_id, vdict)
end
scen_tree = ScenarioTree()
branch_node_1 = add_node(scen_tree, root(scen_tree))
branch_node_2 = add_node(scen_tree, root(scen_tree))
add_leaf(scen_tree, branch_node_1, 0.375)
add_leaf(scen_tree, branch_node_1, 0.125)
add_leaf(scen_tree, branch_node_2, 0.375)
add_leaf(scen_tree, branch_node_2, 0.125)
(niter, abs_res, rel_res, obj, soln_df, phd) = solve(scen_tree,
create_model,
ScalarPenaltyParameter(25.0);
atol=1e-8, rtol=1e-12, max_iter=500)
@show niter
@show abs_res
@show rel_res
@show obj
@show soln_df
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 12636 | module ProgressiveHedging
import DataFrames
import JuMP
import MathOptInterface
const MOI = MathOptInterface
using Distributed
using Printf
using TimerOutputs
#### Exports ####
# High-level Functions
export solve, solve_extensive
# Callbacks
export Callback
export cb, mean_deviation, variable_fixing
export apply_to_subproblem
export SubproblemCallback, spcb
# Exceptions
export UnimplementedError
# ID types and functions
export Index, NodeID, ScenarioID, StageID, VariableID, XhatID
export index, scenario, stage, value
export scid, stid, index
export convert_to_variable_ids, convert_to_xhat_id, stage_id
# Penalty Parameter Interface
export AbstractPenaltyParameter
export get_penalty_value
export is_initial_value_dependent, is_subproblem_dependent, is_variable_dependent
export penalty_map
export process_penalty_initial_value
export process_penalty_subproblem
# Penalty Parameter (Concrete)
export ProportionalPenaltyParameter, ScalarPenaltyParameter, SEPPenaltyParameter
# PHData interaction function
export PHData
export consensus_variables, probability, scenario_tree, scenarios
export get_callback, get_callback_ext
# Result retrieval functions
export lower_bounds
export print_timing
export residuals
export retrieve_aug_obj_value, retrieve_obj_value
export retrieve_soln, retrieve_no_hats, retrieve_w
export retrieve_xhat_history, retrieve_no_hat_history, retrieve_w_history
# Scenario tree types and functions
export ScenarioNode, ScenarioTree
export add_node, add_leaf, root, two_stage_tree
# Subproblem Interface
export AbstractSubproblem, VariableInfo
export add_ph_objective_terms, objective_value, report_values, report_variable_info
export solve_subproblem, update_ph_terms
export warm_start
export ef_copy_model
export ef_node_dict_constructor
export report_penalty_info
export add_lagrange_terms, update_lagrange_terms
# Subproblems Types (Concrete)
export JuMPSubproblem
# (Consensus) Variable interaction functions
export HatVariable
export is_leaf, name, value, branch_value, leaf_value, w_value, xhat_value
export is_integer, scenario_bundle, value, variables
#### Includes ####
include("id_types.jl")
include("penalty_parameter_types.jl")
include("scenario_tree.jl")
include("subproblem.jl")
include("jumpsubproblem.jl")
include("subproblem_callback.jl")
include("message.jl")
include("worker.jl")
include("worker_management.jl")
include("structs.jl")
include("penalty_parameter_functions.jl")
include("utils.jl")
include("algorithm.jl")
include("setup.jl")
include("callbacks.jl")
#### Functions ####
"""
solve(tree::ScenarioTree,
subproblem_constructor::Function,
r<:Real,
other_args...;
max_iter::Int=1000,
atol::Float64=1e-6,
rtol::Float64=1e-6,
gap_tol::Float64=-1.0,
lower_bound::Int=0,
report::Int=0,
save_iterates::Int=0,
save_residuals::Bool=false,
timing::Bool=true,
warm_start::Bool=false,
callbacks::Vector{Callback}=Vector{Callback}(),
worker_assignments::Dict{Int,Set{ScenarioID}}=Dict{Int,Set{ScenarioID}}(),
args::Tuple=(),
kwargs...)
Solve the stochastic programming problem described by `tree` and the models created by `subproblem_constructor` using Progressive Hedging.
**Arguments**
* `tree::ScenararioTree` : Scenario tree describing the structure of the problem to be solved.
* `subproblem_constructor::Function` : User created function to construct a subproblem. Should accept a `ScenarioID` (a unique identifier for each scenario subproblem) as an argument and returns a subtype of `AbstractSubproblem`.
* `r<:AbstractPenaltyParameter` : PH penalty parameter
* `other_args` : Other arguments that should be passed to `subproblem_constructor`. See also keyword arguments `args` and `kwargs`.
**Keyword Arguments**
* `max_iter::Int` : Maximum number of iterations to perform before returning. Defaults to 1000.
* `atol::Float64` : Absolute error tolerance. Defaults to 1e-6.
* `rtol::Float64` : Relative error tolerance. Defaults to 1e-6.
* `gap_tol::Float64` : Relative gap tolerance. Terminate when the relative gap between the lower bound and objective are smaller than `gap_tol`. Any value < 0.0 disables this termination condition. Defaults to -1.0. See also the `lower_bound` keyword argument.
* `lower_bound::Int` : Compute and save a lower-bound using (Gade, et. al. 2016) every `lower_bound` iterations. Any value <= 0 disables lower-bound computation. Defaults to 0.
* `report::Int` : Print progress to screen every `report` iterations. Any value <= 0 disables printing. Defaults to 0.
* `save_iterates::Int` : Save PH iterates every `save_iterates` steps. Any value <= 0 disables saving iterates. Defaults to 0.
* `save_residuals::Int` : Save PH residuals every `save_residuals` steps. Any value <= 0 disables saving residuals. Defaults to 0.
* `timing::Bool` : Print timing info after solving if true. Defaults to true.
* `warm_start::Bool` : Flag indicating that solver should be "warm started" by using the previous solution as the starting point (not compatible with all solvers)
* `callbacks::Vector{Callback}` : Collection of `Callback` structs to call after each PH iteration. Callbacks will be executed in the order they appear. See `Callback` struct for more info. Defaults to empty vector.
* `subproblem_callbacks::Vector{SubproblemCallback}` : Collection of `SubproblemCallback` structs to call before solving each subproblem. Each callback is called on each subproblem but does not affect other subproblems. See `SubproblemCallback` struct for more info. Defaults to empty vector.
* `worker_assignments::Dict{Int,Set{ScenarioID}}` : Dictionary specifying which scenario subproblems a worker will create and solve. The key values are worker ids as given by Distributed (see `Distributed.workers()`). The user is responsible for ensuring the specified workers exist and that every scenario is assigned to a worker. If no dictionary is given, scenarios are assigned to workers in round robin fashion. Defaults to empty dictionary.
* `args::Tuple` : Tuple of arguments to pass to `model_cosntructor`. Defaults to (). See also `other_args` and `kwargs`.
* `kwargs` : Any keyword arguments not specified here that need to be passed to `subproblem_constructor`. See also `other_args` and `args`.
"""
function solve(tree::ScenarioTree,
subproblem_constructor::Function,
r::R,
other_args...;
max_iter::Int=1000,
atol::Float64=1e-6,
rtol::Float64=1e-6,
gap_tol::Float64=-1.0,
lower_bound::Int=0,
report::Int=0,
save_iterates::Int=0,
save_residuals::Int=0,
timing::Bool=false,
warm_start::Bool=false,
callbacks::Vector{Callback}=Vector{Callback}(),
subproblem_callbacks::Vector{SubproblemCallback}=Vector{SubproblemCallback}(),
worker_assignments::Dict{Int,Set{ScenarioID}}=Dict{Int,Set{ScenarioID}}(),
args::Tuple=(),
kwargs...
) where {R <: AbstractPenaltyParameter}
timo = TimerOutputs.TimerOutput()
if length(scenarios(tree)) == 1
@warn("Given scenario tree indicates a deterministic problem (only one scenario).")
elseif length(scenarios(tree)) <= 0
error("Given scenario tree has no scenarios specified. Make sure 'add_leaf' is being called on leaves of the scenario tree.")
end
psum = sum(values(tree.prob_map))
if !isapprox(psum, 1.0, atol=1e-8)
error("Total probability of scenarios in given scenario tree is $psum.")
end
# Initialization
if report > 0
println("Initializing...")
end
(phd, winf) = @timeit(timo,
"Intialization",
initialize(tree,
subproblem_constructor,
r,
worker_assignments,
warm_start,
timo,
report,
lower_bound,
subproblem_callbacks,
(other_args...,args...);
kwargs...)
)
for cb in callbacks
add_callback(phd, cb)
end
# Solution
if report > 0
println("Solving...")
end
(niter, abs_res, rel_res) = @timeit(timo,
"Solution",
hedge(phd,
winf,
max_iter,
atol,
rtol,
gap_tol,
report,
save_iterates,
save_residuals,
lower_bound)
)
# Post Processing
if report > 0
println("Done.")
end
soln_df = retrieve_soln(phd)
obj = retrieve_obj_value(phd)
if timing
print_timing(phd)
end
return (niter, abs_res, rel_res, obj, soln_df, phd)
end
"""
solve_extensive(tree::ScenarioTree,
subproblem_constructor::Function,
optimizer::Function,
other_args...;
opt_args::NamedTuple=NamedTuple(),
subproblem_type::Type{S}=JuMPSubproblem,
args::Tuple=(),
kwargs...)
Solve given problem using Progressive Hedging.
**Arguments**
* `tree::ScenararioTree` : Scenario tree describing the structure of the problem to be solved.
* `subproblem_constructor::Function` : User created function to construct a subproblem. Should accept a `ScenarioID` (a unique identifier for each scenario subproblem) as an argument and returns a subtype of `AbstractSubproblem` specified by `subproblem_type`.
* `optimizer::Function` : Function which works with `JuMP.set_optimizer`
* `other_args` : Other arguments that should be passed to `subproblem_constructor`. See also keyword arguments `args` and `kwargs`
**Keyword Arguments**
* `subproblem_type<:JuMP.AbstractModel` : Type of model to create or created by `subproblem_constructor` to represent the subproblems. Defaults to JuMPSubproblem
* `opt_args::NamedTuple` : arguments passed to function given by `optimizer`
* `args::Tuple` : Tuple of arguments to pass to `model_cosntructor`. Defaults to (). See also `other_args` and `kwargs`.
* `kwargs` : Any keyword arguments not specified here that need to be passed to `subproblem_constructor`. See also `other_args` and `args`.
"""
function solve_extensive(tree::ScenarioTree,
subproblem_constructor::Function,
optimizer::Function,
other_args...;
opt_args::NamedTuple=NamedTuple(),
subproblem_type::Type{S}=JuMPSubproblem,
args::Tuple=(),
kwargs...
) where {S <: AbstractSubproblem}
if length(scenarios(tree)) == 1
@warn("Given scenario tree indicates a deterministic problem (only one scenario).")
elseif length(scenarios(tree)) <= 0
error("Given scenario tree has no scenarios specified. Make sure 'add_leaf' is being called on leaves of the scenario tree.")
end
psum = sum(values(tree.prob_map))
if !isapprox(psum, 1.0, atol=1e-8)
error("Total probability of scenarios in given scenario tree is $psum.")
end
model = build_extensive_form(tree,
subproblem_constructor,
Tuple([other_args...,args...]),
subproblem_type;
kwargs...)
JuMP.set_optimizer(model, optimizer)
for (key, value) in pairs(opt_args)
JuMP.set_optimizer_attribute(model, string(key), value)
end
JuMP.optimize!(model)
return model
end
end # module
#### TODOs ####
# 1. Add flag to solve call to turn off parallelism
# 2. Add handling of nonlinear objective functions
# 3. Add tests for nonlinear constraints (these should work currently but testing is needed)
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 14055 |
function _copy_values(target::Dict{VariableID,Float64},
source::Dict{VariableID,Float64}
)::Nothing
for (vid, value) in pairs(source)
target[vid] = value
end
return
end
function _execute_callbacks(phd::PHData, winf::WorkerInf, niter::Int)::Bool
running = true
for cb in phd.callbacks
running &= cb.h(cb.ext, phd, winf, niter)
end
return running
end
function _process_reports(phd::PHData,
winf::WorkerInf,
report_type::Type{R}
)::Nothing where R <: Report
waiting_on = copy(scenarios(phd))
while !isempty(waiting_on)
msg = _retrieve_message_type(winf, report_type)
_verify_report(msg)
_update_values(phd, msg)
delete!(waiting_on, msg.scen)
end
return
end
function _report(niter::Int,
nsqrt::Float64,
residual::Float64,
xmax::Float64,
xhat_sq::Float64,
x_sq::Float64
)::Nothing
@printf("Iter: %4d AbsR: %12.6e RelR: %12.6e Xhat: %12.6e X: %12.6e\n",
niter, residual, residual / xmax,
sqrt(xhat_sq)/nsqrt, sqrt(x_sq)/nsqrt
)
flush(stdout)
return
end
function _report_lower_bound(niter::Int, bound::Float64, gap::Float64)::Nothing
@printf("Iter: %4d Bound: %12.4e Abs Gap: %12.4e Rel Gap: %8.4g\n",
niter, bound, gap, abs(gap/bound)
)
flush(stdout)
return
end
function _save_iterate(phd::PHData,
iter::Int,
)::Nothing
xhd = Dict{XhatID,Float64}()
xd = Dict{VariableID,Float64}()
wd = Dict{VariableID,Float64}()
for (xhid, xhat) in pairs(phd.xhat)
xhd[xhid] = value(xhat)
for vid in variables(xhat)
xd[vid] = branch_value(phd, vid)
wd[vid] = w_value(phd, vid)
end
end
_save_iterate(phd.history,
iter,
PHIterate(xhd, xd, wd)
)
return
end
function _save_residual(phd::PHData,
iter::Int,
xhat_sq::Float64,
x_sq::Float64,
absr::Float64,
relr::Float64,
)::Nothing
_save_residual(phd.history, iter, PHResidual(absr, relr, xhat_sq, x_sq))
return
end
function _send_solve_commands(phd::PHData,
winf::WorkerInf,
niter::Int
)::Nothing
@sync for (scen, sinfo) in pairs(phd.scenario_map)
(w_dict, xhat_dict) = create_ph_dicts(sinfo)
@async _send_message(winf,
sinfo.pid,
Solve(scen,
w_dict,
xhat_dict,
niter
)
)
end
return
end
function _send_lb_solve_commands(phd::PHData,
winf::WorkerInf,
)::Nothing
@sync for (scen, sinfo) in pairs(phd.scenario_map)
(w_dict, xhat_dict) = create_ph_dicts(sinfo)
@async _send_message(winf, sinfo.pid, SolveLowerBound(scen, w_dict))
end
return
end
function _update_si_xhat(phd::PHData)::Nothing
for (xhid, xhat) in pairs(phd.xhat)
for vid in variables(xhat)
sinfo = phd.scenario_map[scenario(vid)]
sinfo.xhat_vars[vid] = value(xhat)
end
end
return
end
function _update_values(phd::PHData,
msg::ReportBranch
)::Nothing
sinfo = phd.scenario_map[msg.scen]
pd = sinfo.problem_data
pd.obj = msg.obj
pd.sts = msg.sts
pd.time = msg.time
_copy_values(sinfo.branch_vars, msg.vals)
return
end
function _update_values(phd::PHData,
msg::ReportLeaf
)::Nothing
_copy_values(phd.scenario_map[msg.scen].leaf_vars, msg.vals)
return
end
function _update_values(phd::PHData,
msg::ReportLowerBound
)::Nothing
pd = phd.scenario_map[msg.scen].problem_data
pd.lb_obj = msg.obj
pd.lb_sts = msg.sts
pd.lb_time = msg.time
return
end
function _verify_report(msg::ReportBranch)::Nothing
if (msg.sts != MOI.OPTIMAL &&
msg.sts != MOI.LOCALLY_SOLVED &&
msg.sts != MOI.ALMOST_LOCALLY_SOLVED)
# TODO: Create user adjustable/definable behavior for when this happens
@error("Scenario $(msg.scen) subproblem returned $(msg.sts).")
end
return
end
function _verify_report(msg::ReportLeaf)::Nothing
# Intentional no-op
return
end
function _verify_report(msg::ReportLowerBound)::Nothing
if (msg.sts != MOI.OPTIMAL &&
msg.sts != MOI.LOCALLY_SOLVED &&
msg.sts != MOI.ALMOST_LOCALLY_SOLVED)
# TODO: Create user adjustable/definable behavior for when this happens
@error("Scenario $(msg.scen) lower-bound subproblem returned $(msg.sts).")
end
return
end
function compute_and_save_xhat(phd::PHData)::Float64
xhat_res = 0.0
for (xhid, xhat_var) in pairs(phd.xhat)
xhat = 0.0
norm = 0.0
for vid in variables(xhat_var)
s = scenario(vid)
p = phd.scenario_map[s].prob
x = branch_value(phd, vid)
xhat += p * x
norm += p
end
xhat_new = xhat / norm
xhat_old = value(xhat_var)
xhat_var.value = xhat_new
xhat_res += (xhat_new - xhat_old)^2
end
return xhat_res
end
function compute_and_save_w(phd::PHData)::Float64
kxsq = 0.0
for (xhid, xhat_var) in pairs(phd.xhat)
xhat = value(xhat_var)
exp = 0.0
norm = 0.0
for vid in variables(xhat_var)
s = scenario(vid)
p = phd.scenario_map[s].prob
kx = branch_value(phd, vid) - xhat
r = get_penalty_value(phd.r, xhid)
phd.scenario_map[s].w_vars[vid] += r * kx
kxsq += p * kx^2
exp += p * w_value(phd, vid)
norm += p
end
if abs(exp) > 1e-6
vname = name(phd, xhid)
@warn("Conditional expectation of " *
"W[$(vname)] occurring in stage " * stage_id(phd, xhid) *
" for scenarios " * stringify(scenario_bundle(phd, xhid)) *
" is non-zero: " * string(exp/norm))
end
end
return kxsq
end
function compute_gap(phd::PHData)::NTuple{2,Float64}
gap = 0.0
lb = 0.0
for s in scenarios(phd)
sinfo = phd.scenario_map[s]
pd = sinfo.problem_data
p = sinfo.prob
gap += p * abs(pd.obj - pd.lb_obj)
lb += p * pd.lb_obj
end
return (lb, gap)
end
function finish(phd::PHData,
winf::WorkerInf,
)::Nothing
# Send shutdown command to workers
_shutdown(winf)
# Wait for and process replies
_process_reports(phd, winf, ReportLeaf)
# Create hat variables for all leaf variables so
# that `retrieve_soln` picks up the values
for (scid, sinfo) in pairs(phd.scenario_map)
for (vid, vinfo) in pairs(sinfo.leaf_vars)
xhid = convert_to_xhat_id(phd, vid)
@assert(!haskey(phd.xhat, xhid))
# TODO: Correctly assign whether leaf variables are integers. For now,
# just say they aren't because it doesn't really matter.
phd.xhat[xhid] = HatVariable(value(phd, vid), vid, false)
end
end
# Wait for workers to exit cleanly
_wait_for_shutdown(winf)
return
end
function update_gap(phd::PHData, winf::WorkerInf, niter::Int)::NTuple{2,Float64}
@timeit(phd.time_info,
"Issuing lower bound solve commands",
_send_lb_solve_commands(phd, winf)
)
@timeit(phd.time_info,
"Collecting lower bound results",
_process_reports(phd, winf, ReportLowerBound)
)
(lb, gap) = @timeit(phd.time_info,
"Computing gap",
compute_gap(phd)
)
_save_lower_bound(phd.history,
niter,
PHLowerBound(lb, gap, abs(gap/lb))
)
return (lb, gap)
end
function update_ph_variables(phd::PHData)::NTuple{2,Float64}
xhat_sq = compute_and_save_xhat(phd)
x_sq = compute_and_save_w(phd)
return (xhat_sq, x_sq)
end
function solve_subproblems(phd::PHData,
winf::WorkerInf,
niter::Int,
)::Nothing
# Copy hat values to scenario base structure for easy dispersal
@timeit(phd.time_info,
"Other",
_update_si_xhat(phd))
# Send solve command to workers
@timeit(phd.time_info,
"Issuing solve commands",
_send_solve_commands(phd, winf, niter))
# Wait for and process replies
@timeit(phd.time_info,
"Collecting results",
_process_reports(phd, winf, ReportBranch))
return
end
function hedge(ph_data::PHData,
worker_inf::WorkerInf,
max_iter::Int,
atol::Float64,
rtol::Float64,
gap_tol::Float64,
report::Int,
save_iter::Int,
save_res::Int,
lower_bound::Int,
)::Tuple{Int,Float64,Float64}
niter = 0
report_flag = (report > 0)
save_iter_flag = (save_iter > 0)
save_res_flag = (save_res > 0)
lb_flag = (lower_bound > 0)
cr = ph_data.history.residuals[-1]
delete!(ph_data.history.residuals, -1)
xhat_res_sq = cr.xhat_sq
x_res_sq = cr.x_sq
nsqrt = max(sqrt(length(ph_data.xhat)), 1.0)
xmax = (length(ph_data.xhat) > 0
? max(maximum(abs.(value.(values(ph_data.xhat)))), 1e-12)
: 1.0)
residual = sqrt(xhat_res_sq + x_res_sq) / nsqrt
user_continue = @timeit(ph_data.time_info,
"User Callbacks",
_execute_callbacks(ph_data, worker_inf, niter)
)
if report_flag
_report(niter, nsqrt, residual, xmax, xhat_res_sq, x_res_sq)
end
if lb_flag
(lb, gap) = @timeit(ph_data.time_info,
"Update Gap",
update_gap(ph_data, worker_inf, niter)
)
if report_flag
_report_lower_bound(niter, lb, gap)
end
end
if save_iter_flag
_save_iterate(ph_data, 0)
end
if save_res_flag
_save_residual(ph_data, 0, xhat_res_sq, x_res_sq, residual, residual/xmax)
end
running = (user_continue
&& niter < max_iter
&& residual > atol
&& residual > rtol * xmax
&& (lb_flag ? gap > lb * gap_tol : true)
)
while running
niter += 1
# Solve subproblems
@timeit(ph_data.time_info,
"Solve subproblems",
solve_subproblems(ph_data, worker_inf, niter)
)
# Update xhat and w
(xhat_res_sq, x_res_sq) = @timeit(ph_data.time_info,
"Update PH Vars",
update_ph_variables(ph_data)
)
# Update stopping criteria -- xhat_res_sq measures the movement of
# xhat values from k^th iteration to the (k+1)^th iteration while
# x_res_sq measures the disagreement between the x variables and
# its corresponding xhat variable (so lack of consensus amongst the
# subproblems or violation of the nonanticipativity constraint)
residual = sqrt(xhat_res_sq + x_res_sq) / nsqrt
xmax = max(maximum(abs.(value.(values(ph_data.xhat)))), 1e-12)
user_continue = @timeit(ph_data.time_info,
"User Callbacks",
_execute_callbacks(ph_data, worker_inf, niter)
)
running = (user_continue
&& niter < max_iter
&& residual > atol
&& residual > rtol * xmax
&& (lb_flag ? gap > lb * gap_tol : true)
)
if report_flag && (niter % report == 0 || !running)
_report(niter, nsqrt, residual, xmax, xhat_res_sq, x_res_sq)
end
if lb_flag && (niter % lower_bound == 0 || !running)
(lb, gap) = @timeit(ph_data.time_info,
"Update Gap",
update_gap(ph_data, worker_inf, niter)
)
if report_flag
_report_lower_bound(niter, lb, gap)
end
end
if save_iter_flag && niter % save_iter == 0
_save_iterate(ph_data, niter)
end
if save_res_flag && niter % save_res == 0
_save_residual(ph_data,
niter,
xhat_res_sq,
x_res_sq,
residual,
residual/xmax
)
end
end
@timeit(ph_data.time_info,
"Finishing",
finish(ph_data, worker_inf)
)
if niter >= max_iter && residual > atol && residual > rtol * xmax
@warn("Performed $niter iterations without convergence. " *
"Consider increasing max_iter from $max_iter.")
end
return (niter, residual, residual/xmax)
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 3716 |
#### Canned Callbacks ####
"""
variable_fixing(; lag=2, eq_tol=1e-8)::Callback
Implementation of the variable fixing convergence acceleration heuristic in section 2.2 of (Watson & Woodruff 2010).
"""
function variable_fixing(; lag=2, eq_tol=1e-8)::Callback
ext = Dict{Symbol,Any}()
ext[:lag] = lag
ext[:eq_tol] = eq_tol
return Callback("variable_fixing",
_variable_fixing,
_variable_fixing_init,
ext)
end
function _variable_fixing_init(external::Dict{Symbol,Any}, phd::PHData)
# Between iterations
external[:value_count] = Dict{XhatID,Int}(
xhid => 0 for xhid in keys(consensus_variables(phd))
)
external[:value] = Dict{XhatID,Float64}(
xhid => value(xhat) for (xhid,xhat) in pairs(consensus_variables(phd))
)
external[:fixed] = Set{XhatID}()
return
end
function _variable_fixing(external::Dict{Symbol,Any},
phd::PHData,
winf::WorkerInf,
niter::Int)::Bool
lag = external[:lag]
nscen = length(scenarios(phd))
limit = lag * nscen
if niter >= limit
values = external[:value]
counts = external[:value_count]
fixed = external[:fixed]
tol = external[:eq_tol]
to_fix = Dict{ScenarioID,Dict{VariableID,Float64}}()
for (xhid, xhat) in pairs(consensus_variables(phd))
if xhid in fixed
continue
end
is_equal = true
for vid in variables(xhat)
is_equal &= isapprox(value(xhat), branch_value(phd, vid), atol=tol)
end
if is_equal
counts[xhid] = nrepeats = counts[xhid] + 1
if nrepeats >= limit
for vid in variables(xhat)
scen = scenario(vid)
if !haskey(to_fix, scen)
to_fix[scen] = Dict{VariableID,Float64}()
end
to_fix[scen][vid] = value(xhat)
end
push!(fixed, xhid)
end
else
values[xhid] = value(xhat)
counts[xhid] = 1
end
end
for (scen, value_dict) in pairs(to_fix)
apply_to_subproblem(fix_variables, phd, winf, scen, (value_dict,))
end
end
return true
end
"""
mean_deviation(;tol::Float64=1e-8,
save_deviations::Bool=false
)::Callback
Implementation of a termination criterion given in section 2.3 of (Watson & Woodruff 2010). There it is called 'td'.
"""
function mean_deviation(;tol::Float64=1e-8,
save_deviations::Bool=false
)::Callback
ext = Dict{Symbol,Any}(:tol => tol, :save => save_deviations)
if save_deviations
ext[:deviations] = Dict{Int,Float64}()
end
return Callback("mean_deviation",
_mean_deviation,
ext
)
end
function _mean_deviation(external::Dict{Symbol,Any},
phd::PHData,
winf::WorkerInf,
niter::Int)::Bool
nscen = length(scenarios(phd))
td = 0.0
for (xhid, xhat) in consensus_variables(phd)
deviation = 0.0
for vid in variables(xhat)
deviation += abs(branch_value(phd, vid) - value(xhat))
end
td += deviation / (value(xhat))
end
td /= nscen
if external[:save]
external[:deviations][niter] = td
end
return external[:tol] < td
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 3344 |
const NODE_ID = Int
const SCENARIO_ID = Int
const STAGE_ID = Int
const INDEX = Int
"""
Unique identifier for a `ScenarioNode` in a `ScenarioTree`.
"""
struct NodeID
value::NODE_ID
end
"""
value(nid::NodeID)
Return the raw (non-type safe) value of a [`NodeID`](@ref)
"""
value(nid::NodeID)::NODE_ID = nid.value
Base.isless(a::NodeID, b::NodeID) = value(a) < value(b)
"""
Unique, type-safe identifier for a scenario.
"""
struct ScenarioID
value::SCENARIO_ID
end
"""
value(scid::ScenarioID)
Return the raw (non-type safe) value of a [`ScenarioID`](@ref)
"""
value(scid::ScenarioID)::SCENARIO_ID = scid.value
Base.isless(a::ScenarioID, b::ScenarioID) = value(a) < value(b)
"""
Unique, type-safe identifier for a stage.
"""
struct StageID
value::STAGE_ID
end
"""
value(stid::StageID)
Return the raw (non-type safe) value of a [`StageID`](@ref)
"""
value(stid::StageID)::STAGE_ID = stid.value
_increment(sid::StageID)::StageID = StageID(value(sid) + one(STAGE_ID))
Base.isless(a::StageID, b::StageID) = value(a) < value(b)
"""
Unique, type-safe identifier for variables associated with the same scenario tree node.
"""
struct Index
value::INDEX
end
"""
value(idx::Index)
Return the raw (non-type safe) value of an [`Index`](@ref)
"""
value(idx::Index)::INDEX = idx.value
_increment(index::Index)::Index = Index(value(index) + one(INDEX))
Base.isless(a::Index, b::Index) = value(a) < value(b)
"""
Unique, type-safe identifier for any variable in a (multi-stage) stochastic programming problem. Composed of a `ScenarioID`, a `StageID` and an `Index`.
"""
struct VariableID
scenario::ScenarioID # scenario to which this variable belongs
stage::StageID # stage to which this variable belongs
index::Index # coordinate in vector
end
"""
scenario(vid::VariableID)::ScenarioID
Returns the [`ScenarioID`](@ref) of the specified [`VariableID`](@ref).
"""
function scenario(vid::VariableID)::ScenarioID
return vid.scenario
end
"""
stage(vid::VariableID)::StageID
Returns the [`StageID`](@ref) of the specified [`VariableID`](@ref).
"""
function stage(vid::VariableID)::StageID
return vid.stage
end
"""
index(vid::VariableID)::Index
Returns the [`Index`](@ref) of the specified [`VariableID`](@ref).
"""
function index(vid::VariableID)::Index
return vid.index
end
function Base.isless(a::VariableID, b::VariableID)
return (a.stage < b.stage ||
(a.stage == b.stage &&
(a.scenario < b.scenario ||
(a.scenario == b.scenario && a.index < b.index))))
end
"""
scid(n::$(SCENARIO_ID))::ScenarioID
Create `ScenarioID` from `n`.
"""
function scid(n::SCENARIO_ID)::ScenarioID
return ScenarioID(SCENARIO_ID(n))
end
"""
stid(n::$(STAGE_ID))::StageID
Create `StageID` from `n`.
"""
function stid(n::STAGE_ID)::StageID
return StageID(STAGE_ID(n))
end
"""
index(n::$(INDEX))::Index
Create `Index` from `n`.
"""
function index(n::INDEX)::Index
return Index(INDEX(n))
end
"""
Unique identifier for consensus variables. The scenario variables being driven to consensus with this variable is given by `convert_to_variable_ids`.
"""
struct XhatID
node::NodeID
index::Index
end
function Base.isless(a::XhatID, b::XhatID)
return (a.node < b.node ||
(a.node == b.node && a.index < b.index))
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 14242 | #### JuMPSubproblem Implementation ####
"""
Implementation of the [`AbstractSubproblem`](@ref) interface using JuMP.
"""
struct JuMPSubproblem <: AbstractSubproblem
model::JuMP.Model
scenario::ScenarioID
stage_map::Dict{StageID, Vector{JuMP.VariableRef}}
vars::Dict{VariableID, JuMP.VariableRef}
w_vars::Dict{VariableID, JuMP.VariableRef}
xhat_vars::Dict{VariableID, JuMP.VariableRef}
end
function JuMPSubproblem(m::JuMP.Model,
scid::ScenarioID,
stage_map::Dict{StageID, Vector{JuMP.VariableRef}}
)::JuMPSubproblem
return JuMPSubproblem(m, scid, stage_map,
Dict{VariableID, JuMP.VariableRef}(),
Dict{VariableID, JuMP.VariableRef}(),
Dict{VariableID, JuMP.VariableRef}()
)
end
## JuMPSubproblem Internal Structs ##
struct JSVariable
ref::JuMP.VariableRef
name::String
node_id::NodeID
end
## JuMPSubproblem Penalty Parameter Functions ##
function get_penalty_value(r::Float64,
vid::VariableID,
)::Float64
return r
end
function get_penalty_value(r::Dict{VariableID,Float64},
vid::VariableID
)::Float64
return r[vid]
end
## AbstractSubproblem Interface Functions ##
function add_lagrange_terms(js::JuMPSubproblem,
vids::Vector{VariableID}
)::Nothing
obj = JuMP.objective_function(js.model,
JuMP.GenericQuadExpr{Float64, JuMP.VariableRef}
)
jvi = JuMP.VariableInfo(false, NaN, # lower_bound
false, NaN, # upper_bound
true, 0.0, # fixed
false, NaN, # start value
false, false) # binary, integer
for vid in vids
var = js.vars[vid]
w_ref = JuMP.add_variable(js.model, JuMP.build_variable(error, jvi))
JuMP.add_to_expression!(obj, w_ref, var)
js.w_vars[vid] = w_ref
end
JuMP.set_objective_function(js.model, obj)
return
end
function add_ph_objective_terms(js::JuMPSubproblem,
vids::Vector{VariableID},
r::Union{Float64,Dict{VariableID,Float64}},
)::Nothing
add_lagrange_terms(js, vids)
add_proximal_terms(js, vids, r)
return
end
function objective_value(js::JuMPSubproblem)::Float64
return JuMP.objective_value(js.model)
end
function report_penalty_info(js::JuMPSubproblem,
vids::Vector{VariableID},
::Type{ProportionalPenaltyParameter},
)::Dict{VariableID,Float64}
return objective_coefficients(js, vids)
end
function report_penalty_info(js::JuMPSubproblem,
vids::Vector{VariableID},
::Type{SEPPenaltyParameter},
)::Dict{VariableID,Float64}
return objective_coefficients(js, vids)
end
function report_values(js::JuMPSubproblem,
vars::Vector{VariableID}
)::Dict{VariableID,Float64}
val_dict = Dict{VariableID, Float64}()
for vid in vars
val_dict[vid] = JuMP.value(js.vars[vid])
end
return val_dict
end
function report_variable_info(js::JuMPSubproblem,
st::ScenarioTree
)::Dict{VariableID, VariableInfo}
var_info = Dict{VariableID, VariableInfo}()
for node in scenario_nodes(st, js.scenario)
stid = stage(node)
for (k, var) in enumerate(js.stage_map[stid])
vid = VariableID(js.scenario, stid, Index(k))
js.vars[vid] = var
var_info[vid] = VariableInfo(JuMP.name(var),
JuMP.is_integer(var) || JuMP.is_binary(var),
)
end
end
return var_info
end
function solve_subproblem(js::JuMPSubproblem)::MOI.TerminationStatusCode
JuMP.optimize!(js.model)
return JuMP.termination_status(js.model)
end
function update_lagrange_terms(js::JuMPSubproblem,
w_vals::Dict{VariableID,Float64}
)::Nothing
for (wid, wval) in pairs(w_vals)
JuMP.fix(js.w_vars[wid], wval, force=true)
end
return
end
function update_ph_terms(js::JuMPSubproblem,
w_vals::Dict{VariableID,Float64},
xhat_vals::Dict{VariableID,Float64}
)::Nothing
update_lagrange_terms(js, w_vals)
update_proximal_terms(js, xhat_vals)
return
end
function warm_start(js::JuMPSubproblem)::Nothing
for var in JuMP.all_variables(js.model)
if !JuMP.is_fixed(var)
JuMP.set_start_value(var, JuMP.value(var))
end
end
return
end
function ef_copy_model(efm::JuMP.Model,
js::JuMPSubproblem,
scid::ScenarioID,
tree::ScenarioTree,
node_var_map::Dict{NodeID, Set{JSVariable}}
)::Dict{NodeID, Set{JSVariable}}
(snode_var_map, s_var_map) = _ef_copy_variables(efm, js, scid, tree, node_var_map)
processed = Set(keys(node_var_map))
_ef_copy_constraints(efm, js, s_var_map, processed)
_ef_copy_objective(efm, js, s_var_map, tree.prob_map[scid])
return snode_var_map
end
function ef_node_dict_constructor(::Type{JuMPSubproblem})
return Dict{NodeID, Set{JSVariable}}()
end
## JuMPSubproblem Specific Functions ##
function add_proximal_terms(js::JuMPSubproblem,
vids::Vector{VariableID},
r::Union{Float64,Dict{VariableID,Float64}}
)::Nothing
obj = JuMP.objective_function(js.model,
JuMP.GenericQuadExpr{Float64, JuMP.VariableRef}
)
jvi = JuMP.VariableInfo(false, NaN, # lower_bound
false, NaN, # upper_bound
true, 0.0, # fixed
false, NaN, # start value
false, false) # binary, integer
for vid in vids
var = js.vars[vid]
xhat_ref = JuMP.add_variable(js.model, JuMP.build_variable(error, jvi))
rho = get_penalty_value(r, vid)
JuMP.add_to_expression!(obj, 0.5 * rho * (var - xhat_ref)^2)
js.xhat_vars[vid] = xhat_ref
end
JuMP.set_objective_function(js.model, obj)
return
end
function fix_variables(js::JuMPSubproblem,
vids::Dict{VariableID,Float64}
)::Nothing
for (vid, val) in pairs(vids)
JuMP.fix(js.vars[vid], val, force=true)
end
return
end
function objective_coefficients(js::JuMPSubproblem,
vids::Vector{VariableID},
)::Dict{VariableID,Float64}
pen_dict = Dict{VariableID,Float64}()
obj = JuMP.objective_function(js.model)
for vid in vids
pen_dict[vid] = JuMP.coefficient(obj, js.vars[vid])
end
return pen_dict
end
function update_proximal_terms(js::JuMPSubproblem,
xhat_vals::Dict{VariableID,Float64}
)::Nothing
for (xhid, xhval) in pairs(xhat_vals)
JuMP.fix(js.xhat_vars[xhid], xhval, force=true)
end
return
end
## JuMPSubproblem Internal Functions ##
function _build_var_info(vref::JuMP.VariableRef)
hlb = JuMP.has_lower_bound(vref)
hub = JuMP.has_upper_bound(vref)
hf = JuMP.is_fixed(vref)
ib = JuMP.is_binary(vref)
ii = JuMP.is_integer(vref)
return JuMP.VariableInfo(hlb,
hlb ? JuMP.lower_bound(vref) : 0,
hub,
hub ? JuMP.upper_bound(vref) : 0,
hf,
hf ? JuMP.fix_value(vref) : 0,
false, # Some solvers don't accept starting values
0,
ib,
ii)
end
function _ef_add_variables(model::JuMP.Model,
js::JuMPSubproblem,
s::ScenarioID,
node::ScenarioNode,
)
smod = js.model
var_map = Dict{JuMP.VariableRef, JSVariable}()
new_vars = Set{JSVariable}()
for vref in js.stage_map[node.stage]
info = _build_var_info(vref)
var = JuMP.name(vref)
vname = var * "_{" * stringify(value.(scenario_bundle(node))) * "}"
new_vref = JuMP.add_variable(model,
JuMP.build_variable(error, info),
vname)
jsv = JSVariable(new_vref, vname, node.id)
var_map[vref] = jsv
push!(new_vars, jsv)
end
return (var_map, new_vars)
end
function _ef_map_variables(js::JuMPSubproblem,
node::ScenarioNode,
new_vars::Set{JSVariable},
)
var_map = Dict{JuMP.VariableRef, JSVariable}()
for vref in js.stage_map[stage(node)]
var = JuMP.name(vref)
for jsv in new_vars
@assert jsv.node_id == node.id
if occursin(var, jsv.name)
var_map[vref] = jsv
end
end
end
return var_map
end
function _ef_copy_variables(model::JuMP.Model,
js::JuMPSubproblem,
s::ScenarioID,
tree::ScenarioTree,
node_var_map::Dict{NodeID, Set{JSVariable}},
)
# Below for mapping variables in the subproblem model `smod` into variables for
# the extensive form model `model`
s_var_map = Dict{JuMP.VariableRef, JSVariable}()
# For saving updates to node_var_map and passing back up
snode_var_map = Dict{NodeID, Set{JSVariable}}()
smod = js.model
for node in scenario_nodes(tree, s)
# For the given model `smod`, either create extensive variables corresponding
# to this node or map them onto existing extensive variables.
if !haskey(node_var_map, id(node))
(var_map, new_vars) = _ef_add_variables(model, js, s, node)
snode_var_map[node.id] = new_vars
else
var_map = _ef_map_variables(js,
node,
node_var_map[node.id])
end
@assert(isempty(intersect(keys(s_var_map), keys(var_map))))
merge!(s_var_map, var_map)
end
return (snode_var_map, s_var_map)
end
function _ef_convert_and_add_expr(add_to::JuMP.QuadExpr,
convert::JuMP.AffExpr,
s_var_map::Dict{JuMP.VariableRef,JSVariable},
scalar::Real,
)::Set{NodeID}
nodes = Set{NodeID}()
JuMP.add_to_expression!(add_to, scalar * JuMP.constant(convert))
for (coef, var) in JuMP.linear_terms(convert)
vi = s_var_map[var]
nvar = vi.ref
JuMP.add_to_expression!(add_to, scalar*coef, nvar)
push!(nodes, vi.node_id)
end
return nodes
end
function _ef_convert_and_add_expr(add_to::JuMP.QuadExpr,
convert::JuMP.QuadExpr,
s_var_map::Dict{JuMP.VariableRef,JSVariable},
scalar::Real,
)::Set{NodeID}
nodes = _ef_convert_and_add_expr(add_to, convert.aff, s_var_map, scalar)
for (coef, var1, var2) in JuMP.quad_terms(convert)
vi1 = s_var_map[var1]
vi2 = s_var_map[var2]
nvar1 = vi1.ref
nvar2 = vi2.ref
JuMP.add_to_expression!(add_to, scalar*coef, nvar1, nvar2)
push!(nodes, vi1.node_id)
push!(nodes, vi2.node_id)
end
return nodes
end
function _ef_copy_constraints(model::JuMP.Model,
js::JuMPSubproblem,
s_var_map::Dict{JuMP.VariableRef,JSVariable},
processed::Set{NodeID},
)::Nothing
smod = js.model
constraint_list = JuMP.list_of_constraint_types(smod)
for (func,set) in constraint_list
if func == JuMP.VariableRef
# These constraints are handled by the variable bounds
# which are copied during copy variable creation so
# we skip them
continue
end
for cref in JuMP.all_constraints(smod, func, set)
cobj = JuMP.constraint_object(cref)
expr = zero(JuMP.QuadExpr)
nodes = _ef_convert_and_add_expr(expr,
JuMP.jump_function(cobj),
s_var_map,
1)
# If all variables in the expression are from processed nodes,
# then this constraint has already been added to the model
# and can be skipped.
if !issubset(nodes, processed)
JuMP.drop_zeros!(expr)
JuMP.@constraint(model, expr in JuMP.moi_set(cobj))
end
end
end
return
end
function _ef_copy_objective(model::JuMP.Model,
js::JuMPSubproblem,
s_var_map::Dict{JuMP.VariableRef,JSVariable},
prob::Real
)::Nothing
add_obj = JuMP.objective_function(js.model)
obj = JuMP.objective_function(model)
_ef_convert_and_add_expr(obj, add_obj, s_var_map, prob)
JuMP.drop_zeros!(obj)
JuMP.set_objective_function(model, obj)
return
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 1800 |
abstract type Message end
abstract type Report <: Message end
struct Abort <: Message end
struct DumpState <: Message end
struct Initialize{R <: AbstractPenaltyParameter} <: Message
create_subproblem::Function
create_subproblem_args::Tuple
create_subproblem_kwargs::NamedTuple
r::Type{R}
scenarios::Set{ScenarioID}
scenario_tree::ScenarioTree
warm_start::Bool
subproblem_callbacks::Vector{SubproblemCallback}
end
struct InitializeLowerBound <: Message
create_subproblem::Function
create_subproblem_args::Tuple
create_subproblem_kwargs::NamedTuple
scenarios::Set{ScenarioID}
scenario_tree::ScenarioTree
warm_start::Bool
end
struct PenaltyInfo <: Message
scen::ScenarioID
penalty::Union{Float64,Dict{VariableID,Float64}}
end
struct Ping <: Message end
struct ReportBranch <: Report
scen::ScenarioID
sts::MOI.TerminationStatusCode
obj::Float64
time::Float64
vals::Dict{VariableID,Float64}
end
struct ReportLeaf <: Report
scen::ScenarioID
vals::Dict{VariableID,Float64}
end
struct ReportLowerBound <: Report
scen::ScenarioID
sts::MOI.TerminationStatusCode
obj::Float64
time::Float64
end
struct ShutDown <: Message end
struct Solve <: Message
scen::ScenarioID
w_vals::Dict{VariableID,Float64}
xhat_vals::Dict{VariableID,Float64}
niter::Int
end
struct SolveLowerBound <: Message
scen::ScenarioID
w_vals::Dict{VariableID,Float64}
end
struct SubproblemAction <: Message
scen::ScenarioID
action::Function
args::Tuple
kwargs::NamedTuple
end
struct VariableMap <: Message
scen::ScenarioID
var_info::Dict{VariableID,VariableInfo} # VariableInfo definition in subproblem.jl
end
struct WorkerState{T} <: Message
id::Int
state::T
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 8636 |
# Functions separated from type definitions for compiler reasons
#### Abstract Interface Functions ####
"""
Returns the constant penalty parameter value. Only required if `is_variable_dependent` returns false.
"""
function get_penalty_value(r::AbstractPenaltyParameter)::Float64
throw(UnimplementedError("get_penalty_value is unimplemented for penalty parameter of type $(typeof(r))."))
end
"""
Returns the penalty value for the consensus variable associated with `xhid`.
"""
function get_penalty_value(r::AbstractPenaltyParameter,
xhid::XhatID
)::Float64
throw(UnimplementedError("get_penalty_value is unimplemented for penalty parameter of type $(typeof(r))."))
end
"""
Returns true if the penalty parameter value is dependent on the initial solutions of the subproblems.
"""
function is_initial_value_dependent(p::Type{P})::Bool where P <: AbstractPenaltyParameter
throw(UnimplementedError("is_initial_value_dependent is unimplemented for penalty parameter of type $(p)."))
end
"""
Returns true if the penalty parameter value is dependent on any data or values in the subproblems (e.g., the coefficients in the objective function).
"""
function is_subproblem_dependent(p::Type{P})::Bool where P <: AbstractPenaltyParameter
throw(UnimplementedError("is_subproblem_dependent is unimplemented for penalty parameter of type $(p)."))
end
"""
Returns true if the penalty parameter value may differ for different consensus variables.
"""
function is_variable_dependent(p::Type{P})::Bool where P <: AbstractPenaltyParameter
throw(UnimplementedError("is_variable_dependent is unimplemented for penalty parameter of type $(p)."))
end
"""
Returns a mapping of consensus variable ids to penalty parameter values.
Only required if `is_variable_dependent` returns false.
"""
function penalty_map(r::AbstractPenaltyParameter)::Dict{XhatID,Float64}
throw(UnimplementedError("penalty_map is unimplemented for penalty parameter of type $(typeof(r))."))
end
"""
Performs any computations for the penalty parameter based on the initial solutions of the subproblems.
**Arguments**
*`r::AbstractPenaltyParameter` : penalty parameter struct (replace with appropriate type)
*`phd::PHData` : PH data structure used for obtaining any required variable values. See help on `PHData` for details on available functions.
"""
function process_penalty_initial_value(r::AbstractPenaltyParameter,
phd::PHData,
)::Nothing
throw(UnimplementedError("process_penalty_initial_value is unimplemented for penalty parameter of type $(typeof(r))."))
end
"""
Performs any computations for the penalty parameter based data or values from the subproblems.
This function is called *before* the initial solution of subproblems. Any accessing of variable values in this function may result in undefined behavior.
**Arguments**
* `r::AbstractPenaltyParameter` : penalty parameter struct (replace with appropriate type)
* `phd::PHData` : PH data structure used for obtaining any values or information not provided by `scid` and `subproblem_dict`
* `scid::ScenarioID` : scenario id from which `subproblem_dict` comes
* `subproblem_dict::Dict{VariableID,Float64}` : Mapping specifying a value needed from a subproblem used in the computation of the penalty parameter.
"""
function process_penalty_subproblem(r::AbstractPenaltyParameter,
phd::PHData,
scid::ScenarioID,
subproblem_dict::Dict{VariableID,Float64}
)::Nothing
throw(UnimplementedError("process_penalty_subproblem is unimplemented for penalty parameter of type $(typeof(r))."))
end
#### Concrete Implementations ####
## Proportional Penalty Parameter ##
function ProportionalPenaltyParameter(constant::Real)
return ProportionalPenaltyParameter(constant, Dict{XhatID,Float64}())
end
function get_penalty_value(r::ProportionalPenaltyParameter,
xhid::XhatID,
)::Float64
return r.penalties[xhid]
end
function penalty_map(r::ProportionalPenaltyParameter)::Dict{XhatID,Float64}
return r.penalties
end
function process_penalty_subproblem(r::ProportionalPenaltyParameter,
phd::PHData,
scid::ScenarioID,
penalties::Dict{VariableID,Float64}
)::Nothing
for (vid, penalty) in pairs(penalties)
xhid = convert_to_xhat_id(phd, vid)
r_value = penalty == 0.0 ? r.constant : abs(penalty) * r.constant
if haskey(r.penalties, xhid)
if !isapprox(r.penalties[xhid], r_value)
error("Penalty parameter must match across scenarios. Got $(r.penalties[xhid]) instead of $(penalty) for variable $(name(phd, xhid)). This error likely means the coefficients in the objective function do not match in the scenario subproblems.")
end
else
r.penalties[xhid] = r_value
end
end
return
end
function is_initial_value_dependent(::Type{ProportionalPenaltyParameter})::Bool
return false
end
function is_subproblem_dependent(::Type{ProportionalPenaltyParameter})::Bool
return true
end
function is_variable_dependent(::Type{ProportionalPenaltyParameter})::Bool
return true
end
## Scalar Penalty Parameter ##
function get_penalty_value(r::ScalarPenaltyParameter)::Float64
return r.value
end
function get_penalty_value(r::ScalarPenaltyParameter,
xhid::XhatID,
)::Float64
return get_penalty_value(r)
end
function is_initial_value_dependent(::Type{ScalarPenaltyParameter})::Bool
return false
end
function is_subproblem_dependent(::Type{ScalarPenaltyParameter})::Bool
return false
end
function is_variable_dependent(::Type{ScalarPenaltyParameter})::Bool
return false
end
## SEP Penalty Parameter ##
function SEPPenaltyParameter(default::Float64=1.0)
return SEPPenaltyParameter(default, Dict{XhatID,Float64}())
end
function get_penalty_value(r::SEPPenaltyParameter,
xhid::XhatID,
)::Float64
return r.penalties[xhid]
end
function penalty_map(r::SEPPenaltyParameter)::Dict{XhatID,Float64}
return r.penalties
end
function is_initial_value_dependent(::Type{SEPPenaltyParameter})::Bool
return true
end
function process_penalty_initial_value(r::SEPPenaltyParameter,
phd::PHData,
)::Nothing
for (xhid, xhat) in pairs(consensus_variables(phd))
if is_integer(xhat)
xmin = typemax(Int)
xmax = typemin(Int)
for vid in variables(xhat)
xs = branch_value(phd, vid)
if xs < xmin
xmin = xs
end
if xs > xmax
xmax = xs
end
end
denom = xmax - xmin + 1
else
denom = 0.0
for vid in variables(xhat)
p = probability(phd, scenario(vid))
xs = branch_value(phd, vid)
denom += p * abs(xs - value(xhat))
end
denom = max(denom, 1.0)
end
obj_coeff = r.penalties[xhid]
r.penalties[xhid] = obj_coeff == 0.0 ? r.default : abs(obj_coeff)/denom
end
return
end
function is_subproblem_dependent(::Type{SEPPenaltyParameter})::Bool
return true
end
function process_penalty_subproblem(r::SEPPenaltyParameter,
phd::PHData,
scid::ScenarioID,
penalties::Dict{VariableID,Float64}
)::Nothing
for (vid, penalty) in pairs(penalties)
xhid = convert_to_xhat_id(phd, vid)
if haskey(r.penalties, xhid)
if !isapprox(r.penalties[xhid], penalty)
error("Penalty parameter must match across scenarios. Got $(r.penalties[xhid]) instead of $(penalty) for variable $(name(phd, xhid)). This error likely means the coefficients in the objective function do not match in the scenario subproblems.")
end
else
r.penalties[xhid] = penalty
end
end
return
end
function is_variable_dependent(::Type{SEPPenaltyParameter})::Bool
return true
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 2903 |
#### Abstract Types ####
"""
Abstract type for ProgressiveHedging penalty parameter.
Concrete subtypes determine how this penalty is used within the PH algorithm.
All concrete subtypes must implement the following methods:
* `get_penalty_value(r::<ConcreteSubtype>, xhid::XhatID)::Float64`
* `is_initial_value_dependent(::Type{<ConcreteSubtype>})::Bool`
* `is_subproblem_dependent(::Type{<ConcreteSubtype>})::Bool`
* `is_variable_dependent(::Type{<ConcreateSubtype>})::Bool`
If `is_initial_value_dependent` returns `true`, then the concrete subtype must implement
* `process_penalty_initial_value(r::<ConcreteSubtype>, ph_data::PHData)::Nothing`
If `is_subproblem_dependent` returns `true`, then the concrete subtype must implement
* `process_penalty_subproblem(r::<ConcreteSubtype>, ph_data::PHData, scenario::ScenarioID, penalties::Dict{VariableID,Float64})::Nothing`
Additionally, the concrete **subproblem type** must implement the function
* `report_penalty_info(as::AbstractSubproblem, pp<:AbstractPenaltyParameter)::Dict{VariableID,Float64}`
If `is_variable_dependent` returns `true`, then the concrete subtype must implement
* `penalty_map(r::<ConcreteSubtype>)::Dict{XhatID,Float64}`
If `is_variable_dependent` returns `false`, then the concrete subtype must implement
* `get_penalty_value(r::<ConcreteSubtype>)::Float64`
For more details, see the help on the individual functions.
"""
abstract type AbstractPenaltyParameter end
#### Concrete Types (Alphabetical Order) ####
"""
Variable dependent penalty parameter given by `k * c_i` where `c_i` is the linear coefficient of variable `i` in the objective function. If `c_i == 0` (that is, the variable has no linear coefficient in the objective function), then the penalty value is taken to be `k`.
!!! warning
The coefficients in the objective function **must** match across scenarios. An error will result if they do not.
Requires subproblem type to have implemented [`report_penalty_info`](@ref) for this type. This implementation should return the linear coefficient in the objective function for each variable.
"""
struct ProportionalPenaltyParameter <: AbstractPenaltyParameter
constant::Float64
penalties::Dict{XhatID,Float64}
end
"""
Constant scalar penalty parameter.
"""
struct ScalarPenaltyParameter <: AbstractPenaltyParameter
value::Float64
end
"""
Penalty parameter set with Watson-Woodruff SEP method. See (Watson and Woodruff 2011) for more details.
!!! warning
The coefficients in the objective function **must** match across scenarios. An error will result if they do not.
Requires subproblem type to have implemented [`report_penalty_info`](@ref) for this type. This implementation should return the linear coefficient in the objective function for each variable.
"""
struct SEPPenaltyParameter <: AbstractPenaltyParameter
default::Float64
penalties::Dict{XhatID,Float64}
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 6440 |
mutable struct Generator
next_node_id::NODE_ID
next_scenario_id::SCENARIO_ID
end
function Generator()::Generator
return Generator(0,0)
end
function _generate_node_id(gen::Generator)::NodeID
id = NodeID(gen.next_node_id)
gen.next_node_id += 1
return id
end
function _generate_scenario_id(gen::Generator)::ScenarioID
id = ScenarioID(gen.next_scenario_id)
gen.next_scenario_id += 1
return id
end
"""
Struct representing a node in a scenario tree.
"""
struct ScenarioNode
id::NodeID # id of this node
stage::StageID # stage of this node
scenario_bundle::Set{ScenarioID} # scenarios that are indistiguishable
parent::Union{Nothing,ScenarioNode}
children::Set{ScenarioNode}
end
function stringify(node::ScenarioNode)
node_str = "$(value(node.id)):{"
for s in sort!(collect(node.scenario_bundle))
node_str *= "$(value(s)),"
end
rstrip(node_str, ',')
node_str *= "}"
return node_str
end
Base.show(io::IO, sn::ScenarioNode) = print(io, "ScenarioNode($(sn.id), $(sn.stage), $(sn.scenario_bundle))")
function _add_child(parent::ScenarioNode,
child::ScenarioNode,
)::Nothing
push!(parent.children, child)
return
end
function _create_node(gen::Generator,
parent::Union{Nothing,ScenarioNode}
)::ScenarioNode
nid = _generate_node_id(gen)
stage = (parent==nothing ? StageID(1) : _increment(parent.stage))
sn = ScenarioNode(nid, stage,
Set{ScenarioID}(),
parent,
Set{ScenarioNode}())
if parent != nothing
_add_child(parent, sn)
end
return sn
end
function id(node::ScenarioNode)::NodeID
return node.id
end
function stage(node::ScenarioNode)::StageID
return node.stage
end
"""
Struct representing the scenario structure of a stochastic program.
Can be built up by the user using the functions `add_node` and `add_leaf`.
**Constructor**
ScenarioTree()
Default constructor generates the root node of the tree. Can get the root node with `root`.
"""
struct ScenarioTree
root::ScenarioNode
tree_map::Dict{NodeID, ScenarioNode} # map from NodeID to tree node
prob_map::Dict{ScenarioID, Float64}
id_gen::Generator
end
function ScenarioTree(root_node::ScenarioNode,
gen::Generator,
)::ScenarioTree
tree_map = Dict{NodeID, ScenarioNode}()
prob_map = Dict{ScenarioID, Float64}()
st = ScenarioTree(root_node,
tree_map,
prob_map,
gen)
_add_node(st, root_node)
return st
end
function ScenarioTree()::ScenarioTree
gen = Generator()
rn = _create_node(gen, nothing)
st = ScenarioTree(rn, gen)
return st
end
"""
root(tree::ScenarioTree)
Return the root node of the given ScenarioTree
"""
function root(tree::ScenarioTree)::ScenarioNode
return tree.root
end
function last_stage(tree::ScenarioTree)::StageID
return maximum(getfield.(values(tree.tree_map), :stage))
end
function is_leaf(tree::ScenarioTree, vid::VariableID)::Bool
return is_leaf(node(tree, vid.scenario, vid.stage))
end
function is_leaf(node::ScenarioNode)::Bool
return length(node.children) == 0 ||
(length(node.children) == 1 && is_leaf(first(node.children)))
end
function is_leaf(tree::ScenarioTree, nid::NodeID)::Bool
return is_leaf(tree.tree_map[nid])
end
function is_leaf(tree::ScenarioTree, node::ScenarioNode)::Bool
return is_leaf(tree.tree_map[node.id])
end
function _add_node(tree::ScenarioTree, node::ScenarioNode)::Nothing
tree.tree_map[node.id] = node
return
end
"""
add_node(tree::ScenarioTree, parent::ScenarioNode)
Add a node to the ScenarioTree `tree` with parent node `parent`. Return the added node. If the node to add is a leaf, use `add_leaf` instead.
"""
function add_node(tree::ScenarioTree,
parent::ScenarioNode,
)::ScenarioNode
new_node = _create_node(tree.id_gen, parent)
_add_node(tree, new_node)
return new_node
end
function _add_scenario_to_bundle(tree::ScenarioTree,
nid::NodeID,
scid::ScenarioID,
)::Nothing
push!(tree.tree_map[nid].scenario_bundle, scid)
return
end
"""
add_leaf(tree::ScenarioTree, parent::ScenarioNode, probability<:Real)
Add a leaf to the ScenarioTree `tree` with parent node `parent`. The probability of this scenario occuring is given by `probability`. Returns the ScenarioID representing the scenario.
"""
function add_leaf(tree::ScenarioTree,
parent::ScenarioNode,
probability::R,
)::ScenarioID where R <: Real
if probability < 0.0 || probability > 1.0
error("Invalid probability value: $probability")
end
leaf = add_node(tree, parent)
scid = _assign_scenario_id(tree)
tree.prob_map[scid] = probability
node = leaf
while node != nothing
id = node.id
_add_scenario_to_bundle(tree, id, scid)
node = node.parent
end
return scid
end
_assign_scenario_id(tree::ScenarioTree)::ScenarioID = _generate_scenario_id(tree.id_gen)
function node(tree::ScenarioTree,
nid::NodeID
)::ScenarioNode
return tree.tree_map[nid]
end
function node(tree::ScenarioTree,
scid::ScenarioID,
stid::StageID
)::Union{Nothing,ScenarioNode}
ret_node = nothing
for node in values(tree.tree_map)
if stage(node) == stid && scid in scenario_bundle(node)
ret_node = node
break
end
end
return ret_node
end
function scenario_bundle(node::ScenarioNode)::Set{ScenarioID}
return node.scenario_bundle
end
function scenario_bundle(tree::ScenarioTree, nid::NodeID)::Set{ScenarioID}
return scenario_bundle(tree.tree_map[nid])
end
scenarios(tree::ScenarioTree)::Set{ScenarioID} = tree.root.scenario_bundle
function scenario_nodes(tree::ScenarioTree)
return collect(values(tree_map))
end
function scenario_nodes(tree::ScenarioTree, scid::ScenarioID)
nodes = Vector{ScenarioNode}()
for node in values(tree.tree_map)
if scid in scenario_bundle(node)
push!(nodes, node)
end
end
return nodes
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 9576 |
function assign_scenarios_to_procs(scen_tree::ScenarioTree
)::Dict{Int,Set{ScenarioID}}
sp_map = Dict{Int, Set{ScenarioID}}()
nprocs = nworkers()
wrks = workers()
sp_map = Dict(w => Set{ScenarioID}() for w in wrks)
for (k,s) in enumerate(scenarios(scen_tree))
w = wrks[(k-1) % nprocs + 1]
push!(sp_map[w], s)
end
return sp_map
end
function _initialize_subproblems(sp_map::Dict{Int,Set{ScenarioID}},
wi::WorkerInf,
scen_tree::ScenarioTree,
constructor::Function,
constructor_args::Tuple,
r::AbstractPenaltyParameter,
warm_start::Bool,
subproblem_callbacks::Vector{SubproblemCallback};
kwargs...
)
# Send initialization commands
@sync for (wid, scenarios) in pairs(sp_map)
@async _send_message(wi,
wid,
Initialize(constructor,
constructor_args,
(;kwargs...),
typeof(r),
scenarios,
scen_tree,
warm_start,
subproblem_callbacks)
)
end
# Wait for and process initialization replies
var_maps = Dict{ScenarioID,Dict{VariableID,VariableInfo}}()
remaining_maps = copy(scenarios(scen_tree))
while !isempty(remaining_maps)
msg = _retrieve_message_type(wi, VariableMap)
var_maps[msg.scen] = msg.var_info
delete!(remaining_maps, msg.scen)
end
return var_maps
end
function _initialize_lb_subproblems(sp_map::Dict{Int,Set{ScenarioID}},
wi::WorkerInf,
scen_tree::ScenarioTree,
constructor::Function,
constructor_args::Tuple,
warm_start::Bool;
kwargs...
)::Nothing
@sync for (wid, scenarios) in pairs(sp_map)
@async _send_message(wi,
wid,
InitializeLowerBound(constructor,
constructor_args,
(;kwargs...),
scenarios,
scen_tree,
warm_start)
)
end
return
end
function _set_initial_values(phd::PHData,
wi::WorkerInf,
)::Float64
# Wait for and process mapping replies
remaining_init = copy(scenarios(phd.scenario_tree))
while !isempty(remaining_init)
msg = _retrieve_message_type(wi, ReportBranch)
_verify_report(msg)
_update_values(phd, msg)
delete!(remaining_init, msg.scen)
end
# Start computation of initial PH values -- W values are computed at
# the end of `_set_penalty_parameter`.
xhat_res_sq = compute_and_save_xhat(phd)
return xhat_res_sq
end
function _set_penalty_parameter(phd::PHData,
wi::WorkerInf,
)::Float64
if is_subproblem_dependent(typeof(phd.r))
# Wait for and process penalty parameter messages
remaining_maps = copy(scenarios(phd.scenario_tree))
while !isempty(remaining_maps)
msg = _retrieve_message_type(wi, PenaltyInfo)
process_penalty_subproblem(phd.r, phd, msg.scen, msg.penalty)
delete!(remaining_maps, msg.scen)
end
end
if is_initial_value_dependent(typeof(phd.r))
# Compute penalty parameter values
process_penalty_initial_value(phd.r, phd)
end
if is_variable_dependent(typeof(phd.r))
# Convert dictionary to subproblem format
pen_map = Dict{ScenarioID,Dict{VariableID,Float64}}(
s => Dict{VariableID,Float64}() for s in scenarios(phd)
)
for (xhid,penalty) in pairs(penalty_map(phd.r))
for vid in convert_to_variable_ids(phd, xhid)
pen_map[scenario(vid)][vid] = penalty
end
end
else
pen_map = Dict{ScenarioID,Float64}(
s => get_penalty_value(phd.r) for s in scenarios(phd)
)
end
# Send penalty parameter values to workers
@sync for (scid, sinfo) in pairs(phd.scenario_map)
@async begin
wid = sinfo.pid
penalty = pen_map[scid]
_send_message(wi, wid, PenaltyInfo(scid, penalty))
end
end
# Complete computation of initial PH values -- Xhat values are computed at
# the end of `_set_initial_values`.
x_res_sq = compute_and_save_w(phd)
return x_res_sq
end
function initialize(scen_tree::ScenarioTree,
model_constructor::Function,
r::AbstractPenaltyParameter,
user_sp_map::Dict{Int,Set{ScenarioID}},
warm_start::Bool,
timo::TimerOutputs.TimerOutput,
report::Int,
lower_bound::Int,
subproblem_callbacks::Vector{SubproblemCallback},
constructor_args::Tuple,;
kwargs...
)::Tuple{PHData,WorkerInf}
# Assign scenarios to processes
scen_proc_map = isempty(user_sp_map) ? assign_scenarios_to_procs(scen_tree) : user_sp_map
scen_per_worker = maximum(length.(collect(values(scen_proc_map))))
n_scenarios = length(scenarios(scen_tree))
# Start worker loops
if report > 0
println("...launching workers...")
end
worker_inf = @timeit(timo,
"Launch Workers",
_launch_workers(2*scen_per_worker, n_scenarios)
)
# Initialize subproblems
if report > 0
println("...initializing subproblems...")
flush(stdout)
end
var_map = @timeit(timo,
"Initialize Subproblems",
_initialize_subproblems(scen_proc_map,
worker_inf,
scen_tree,
model_constructor,
constructor_args,
r,
warm_start,
subproblem_callbacks;
kwargs...)
)
if lower_bound > 0
if report > 0
println("...initializing lower-bound subproblems...")
flush(stdout)
end
@timeit(timo,
"Initialze Lower Bound Subproblems",
_initialize_lb_subproblems(scen_proc_map,
worker_inf,
scen_tree,
model_constructor,
constructor_args,
warm_start;
kwargs...)
)
end
# Construct master ph object
phd = @timeit(timo,
"Other",
PHData(r,
scen_tree,
scen_proc_map,
var_map,
timo)
)
# Initial values
xhat_res_sq = @timeit(timo,
"Initial Values",
_set_initial_values(phd, worker_inf)
)
# Check for penalty parameter update
x_res_sq = @timeit(timo,
"Penalty Parameter",
_set_penalty_parameter(phd,
worker_inf)
)
# Save residual
_save_residual(phd, -1, xhat_res_sq, x_res_sq, 0.0, 0.0)
return (phd, worker_inf)
end
function build_extensive_form(tree::ScenarioTree,
model_constructor::Function,
constructor_args::Tuple,
sub_type::Type{S};
kwargs...
)::JuMP.Model where {S <: AbstractSubproblem}
model = JuMP.Model()
JuMP.set_objective_sense(model, MOI.MIN_SENSE)
JuMP.set_objective_function(model, zero(JuMP.QuadExpr))
# Below for mapping subproblem variables onto existing extensive form variables
node_var_map = ef_node_dict_constructor(sub_type)
for s in scenarios(tree)
smod = model_constructor(s, constructor_args...; kwargs...)
snode_var_map = ef_copy_model(model, smod, s, tree, node_var_map)
@assert(isempty(intersect(keys(node_var_map), keys(snode_var_map))))
merge!(node_var_map, snode_var_map)
end
return model
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 22447 |
#### Exceptions ####
"""
Exception indicating that the specified method is not implemented for an interface.
"""
struct UnimplementedError <: Exception
msg::String
end
#### Internal Types and Methods ####
struct Indexer
next_index::Dict{NodeID, Index}
indices::Dict{NodeID, Dict{String, Index}}
end
function Indexer()::Indexer
idxr = Indexer(Dict{NodeID, Index}(),
Dict{NodeID, Dict{String,Index}}())
return idxr
end
function _retrieve_and_advance_index(idxr::Indexer, nid::NodeID)::Index
if !haskey(idxr.next_index, nid)
idxr.next_index[nid] = Index(zero(INDEX))
end
idx = idxr.next_index[nid]
idxr.next_index[nid] = _increment(idx)
return idx
end
function index(idxr::Indexer, nid::NodeID, name::String)::Index
if !haskey(idxr.indices, nid)
idxr.indices[nid] = Dict{String, Index}()
end
node_vars = idxr.indices[nid]
if haskey(node_vars, name)
idx = node_vars[name]
else
idx = _retrieve_and_advance_index(idxr, nid)
node_vars[name] = idx
end
return idx
end
struct VariableData
name::String
xhat_id::XhatID
end
mutable struct ProblemData
obj::Float64
sts::MOI.TerminationStatusCode
time::Float64
lb_obj::Float64
lb_sts::MOI.TerminationStatusCode
lb_time::Float64
end
ProblemData() = ProblemData(0.0, MOI.OPTIMIZE_NOT_CALLED, 0.0,
0.0, MOI.OPTIMIZE_NOT_CALLED, 0.0)
struct ScenarioInfo
pid::Int
prob::Float64
branch_vars::Dict{VariableID, Float64}
leaf_vars::Dict{VariableID, Float64}
w_vars::Dict{VariableID, Float64}
xhat_vars::Dict{VariableID, Float64}
problem_data::ProblemData
end
function ScenarioInfo(pid::Int,
prob::Float64,
branch_ids::Set{VariableID},
leaf_ids::Set{VariableID}
)::ScenarioInfo
branch_map = Dict{VariableID, Float64}()
w_dict = Dict{VariableID, Float64}()
x_dict = Dict{VariableID, Float64}()
for vid in branch_ids
branch_map[vid] = 0.0
w_dict[vid] = 0.0
x_dict[vid] = 0.0
end
leaf_map = Dict{VariableID, Float64}(vid => 0.0 for vid in leaf_ids)
return ScenarioInfo(pid,
prob,
branch_map,
leaf_map,
w_dict,
x_dict,
ProblemData())
end
function create_ph_dicts(sinfo::ScenarioInfo)
return (sinfo.w_vars, sinfo.xhat_vars)
end
function objective_value(sinfo::ScenarioInfo)::Float64
return sinfo.problem_data.obj
end
function retrieve_variable_value(sinfo::ScenarioInfo, vid::VariableID)::Float64
if haskey(sinfo.branch_vars, vid)
vi = sinfo.branch_vars[vid]
else
vi = sinfo.leaf_vars[vid]
end
return vi
end
struct PHIterate
xhat::Dict{XhatID,Float64}
x::Dict{VariableID,Float64}
w::Dict{VariableID,Float64}
end
struct PHLowerBound
lower_bound::Float64
gap::Float64
rel_gap::Float64
end
struct PHResidual
abs_res::Float64
rel_res::Float64
xhat_sq::Float64
x_sq::Float64
end
struct PHHistory
iterates::Dict{Int, PHIterate}
residuals::Dict{Int, PHResidual}
lower_bounds::Dict{Int, PHLowerBound}
end
function PHHistory()
return PHHistory(Dict{Int, PHIterate}(),
Dict{Int, PHResidual}(),
Dict{Int, PHLowerBound}(),
)
end
function _save_iterate(phh::PHHistory,
iter::Int,
phi::PHIterate
)::Nothing
phh.iterates[iter] = phi
return
end
function _save_lower_bound(phh::PHHistory,
iter::Int,
phlb::PHLowerBound
)::Nothing
phh.lower_bounds[iter] = phlb
return
end
function _save_residual(phh::PHHistory, iter::Int, res::PHResidual)::Nothing
phh.residuals[iter] = res
return
end
#### User Facing Types ####
"""
Struct for user callbacks.
**Fields**
* `name::String` : User's name for the callback. Defaults to `string(h)`.
* `h::Function` : Callback function. See notes below for calling signature.
* `initialize::Function` : Function to initialize `ext` *after* subproblem creation has occurred.
* `ext::Dict{Symbol,Any}` : Dictionary to store data between callback calls or needed parameters.
The callback function `h` must have the signature
`h(ext::Dict{Symbol,Any}, phd::PHData, winf::WorkerInf, niter::Int)::Bool`
where `ext` is the same dictionary given to the `Callback` constructor, `phd` is the standard PH data structure (see `PHData`), `winf` is used for communicating with subproblems (see `apply_to_subproblem`) and `niter` is the current iteration. The callback may return `false` to stop PH.
The `initialize` function must have the signature
`initialize(ext::Dict{Symbol,Any}, phd::PHData)`
where `ext` is the same dictionary given to the `Callback` constructor and `phd` is the standard PH data structure (see `PHData`).
"""
struct Callback
name::String
h::Function
initialize::Function
ext::Dict{Symbol,Any}
end
function Base.show(io::IO, cb::Callback)
print(io, cb.name)
return
end
"""
Type representing a consensus variable.
The following functions are available to the user to interact with consensus variables
* [`is_integer`](@ref)
* [`value`](@ref)
* [`variables`](@ref)
"""
mutable struct HatVariable
value::Float64 # Current value of variable
vars::Set{VariableID} # All nonhat variable ids that contribute to this variable
is_integer::Bool # Flag indicating that this variable is an integer (includes binary)
end
HatVariable(is_int::Bool)::HatVariable = HatVariable(0.0, Set{VariableID}(),is_int)
function HatVariable(val::Float64,vid::VariableID, is_int::Bool)
return HatVariable(val, Set{VariableID}([vid]), is_int)
end
## Primary PH Data Structure ##
"""
Data structure used to store information and results for a stochastic programming problem.
See the following functions make use of this object:
* [`apply_to_subproblem`](@ref)
* [`branch_value`](@ref)
* [`consensus_variables`](@ref)
* [`convert_to_variable_ids`](@ref)
* [`convert_to_xhat_id`](@ref)
* [`get_callback`](@ref)
* [`get_callback_ext`](@ref)
* [`is_leaf`](@ref)
* [`name`](@ref)
* [`probability`](@ref)
* [`scenario_bundle`](@ref)
* [`scenarios`](@ref)
* [`stage_id`](@ref)
* [`value`](@ref)
* [`w_value`](@ref)
* [`xhat_value`](@ref)
The following post solution functions are also available:
* [`leaf_value`](@ref)
* [`retrieve_soln`](@ref)
* [`retrieve_aug_obj_value`](@ref)
* [`retrieve_obj_value`](@ref)
* [`retrieve_no_hats`](@ref)
* [`retrieve_w`](@ref)
If the corresponding save options are enabled, the saved terms may be accessed with one of the following:
* [`lower_bounds`](@ref)
* [`residuals`](@ref)
* [`retrieve_xhat_history`](@ref)
* [`retrieve_no_hat_history`](@ref)
* [`retrieve_w_history`](@ref)
"""
struct PHData
r::AbstractPenaltyParameter
scenario_tree::ScenarioTree
scenario_map::Dict{ScenarioID, ScenarioInfo}
callbacks::Vector{Callback}
xhat::Dict{XhatID, HatVariable}
variable_data::Dict{VariableID, VariableData}
history::PHHistory
time_info::TimerOutputs.TimerOutput
end
function PHData(r::AbstractPenaltyParameter,
tree::ScenarioTree,
scen_proc_map::Dict{Int, Set{ScenarioID}},
var_map::Dict{ScenarioID, Dict{VariableID, VariableInfo}},
time_out::TimerOutputs.TimerOutput
)::PHData
var_data = Dict{VariableID,VariableData}()
xhat_dict = Dict{XhatID, HatVariable}()
idxr = Indexer()
scenario_map = Dict{ScenarioID, ScenarioInfo}()
for (pid, scenarios) in pairs(scen_proc_map)
for scen in scenarios
branch_ids = Set{VariableID}()
leaf_ids = Set{VariableID}()
for (vid, vinfo) in pairs(var_map[scen])
vnode = node(tree, vid.scenario, vid.stage)
if isnothing(vnode)
error("Unable to locate scenario tree node for variable '$(vinfo.name)' occuring in scenario $(vid.scenario) and stage $(vid.stage).")
end
idx = index(idxr, vnode.id, vinfo.name)
xhid = XhatID(vnode.id, idx)
vdata = VariableData(vinfo.name, xhid)
var_data[vid] = vdata
if is_leaf(vnode)
push!(leaf_ids, vid)
else
push!(branch_ids, vid)
if haskey(xhat_dict, xhid)
if is_integer(xhat_dict[xhid]) != vinfo.is_integer
error("Variable '$(vinfo.name)' must be integer or non-integer in all scenarios in which it is used.")
end
else
xhat_dict[xhid] = HatVariable(vinfo.is_integer)
end
add_variable(xhat_dict[xhid], vid)
end
end
scenario_map[scen] = ScenarioInfo(pid,
tree.prob_map[scen],
branch_ids,
leaf_ids,
)
end
end
return PHData(r,
tree,
scenario_map,
Vector{Callback}(),
xhat_dict,
var_data,
PHHistory(),
time_out,
)
end
function Base.show(io::IO, phd::PHData)
nscen = length(scenarios(phd))
print(io, "PH structure for a stochastic program with $(nscen) scenarios.")
return
end
#### User Facing Functions ####
## Callback Functions ##
"""
Callback(f::Function)
Creates a `Callback` structure for function `f`.
"""
function Callback(f::Function)
return Callback(string(f), f, (::Dict{Symbol,Any},::PHData)->(), Dict{Symbol,Any}())
end
"""
Callback(f::Function, ext::Dict{Symbol,Any})
Creates a `Callback` structure for function `f` with the external data dictionary `ext`.
"""
function Callback(f::Function, ext::Dict{Symbol,Any})
return Callback(string(f), f, (::Dict{Symbol,Any},::PHData)->(), ext)
end
"""
Callback(f::Function, initialize::Function)
Creates a `Callback` structure for function `f` with initializer `initialize`.
"""
function Callback(f::Function, initialize::Function)
return Callback(string(f), f, initialize, Dict{Symbol,Any}())
end
"""
Callback(name::String, f::Function, ext::Dict{Symbol,Any})
Creates a `Callback` structure for function `f` with the name `name` and the external data dictionary `ext`.
"""
function Callback(name::String, f::Function, ext::Dict{Symbol,Any})
return Callback(name, f, (::Dict{Symbol,Any},::PHData)->(), ext)
end
"""
Callback(f::Function, initialize::Function, ext::Dict{Symbol,Any})
Creates a `Callback` structure for function `f` with the external data dictionary `ext` which will be initialized with `initialize`.
"""
function Callback(f::Function, initialize::Function, ext::Dict{Symbol,Any})
return Callback(string(f), f, initialize, ext)
end
"""
cb(f::Function)
cb(f::Function, ext::Dict{Symbol,Any})
cb(f::Function, initialize::Function)
cb(f::Function, initialize::Function, ext::Dict{Symbol,Any})
cb(name::String, f::Function, ext::Dict{Symbol,Any})
Shorthand for [`Callback`](@ref) functions with the same signature.
"""
cb(f::Function) = Callback(f)
cb(f::Function, ext::Dict{Symbol,Any}) = Callback(f, ext)
cb(f::Function, initialize::Function) = Callback(f, initialize)
cb(f::Function, initialize::Function, ext::Dict{Symbol,Any}) = Callback(f, initialize, ext)
cb(name::String, f::Function, ext::Dict{Symbol,Any}) = Callback(name, f, ext)
cb(name::String, f::Function, initialize::Function, ext::Dict{Symbol,Any}) = Callback(name, f, initialize, ext)
## Consensus Variable Functions ##
function add_variable(a::HatVariable, vid::VariableID)
push!(a.vars, vid)
return
end
"""
is_integer(a::HatVariable)::Bool
Returns true if the consensus variable is an integer variable. The consensus variable is an integer if the contributing subproblem variables are all integer variables.
"""
function is_integer(a::HatVariable)::Bool
return a.is_integer
end
"""
set_value(a::HatVariable, v::Float64)
Sets the current value of `a` to `v`.
"""
function set_value(a::HatVariable, v::Float64)::Nothing
a.value = v
return
end
"""
value(a::HatVariable)::Float64
Returns the current value of `a`.
"""
function value(a::HatVariable)::Float64
return a.value
end
"""
variables(a::HatVariable)::Set{VariableID}
Returns the variable ids for all subproblem variables contributing to this variable.
"""
function variables(a::HatVariable)::Set{VariableID}
return a.vars
end
## PHData Interaction Functions ##
# NOTE: Additional, more complicated functions are in utils.jl
"""
add_callback(phd::PHData,
cb::Callback
)::Nothing
Adds the callback `cb` to the given PH problem.
"""
function add_callback(phd::PHData,
cb::Callback
)::Nothing
push!(phd.callbacks, cb)
cb.initialize(cb.ext, phd)
return
end
"""
apply_to_subproblem(to_apply::Function,
phd::PHData,
winf::WorkerInf,
scid::ScenarioID,
args::Tuple=(),
kwargs::NamedTuple=NamedTuple(),
)
Applies the function `to_apply` to the subproblem with scenario id `scid`.
"""
function apply_to_subproblem(to_apply::Function,
phd::PHData,
winf::WorkerInf,
scid::ScenarioID,
args::Tuple=(),
kwargs::NamedTuple=NamedTuple(),
)
_send_message(winf,
phd.scenario_map[scid].pid,
SubproblemAction(scid,
to_apply,
args,
kwargs)
)
return
end
"""
branch_value(phd::PHData, vid::VariableID)::Float64
Returns the value of the variable associated with `vid`. Must be a branch variable.
See also: [`leaf_value`](@ref), [`value`](@ref)
"""
function branch_value(phd::PHData, vid::VariableID)::Float64
return phd.scenario_map[scenario(vid)].branch_vars[vid]
end
"""
branch_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
Returns the value of the variable associated with with scenario `scen`, stage `stage` and index `idx`. Must be a branch variable.
See also: [`leaf_value`](@ref), [`value`](@ref)
"""
function branch_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
return branch_value(phd, VariableID(scen, stage, idx))
end
"""
consensus_variables(phd::PHData)::Dict{XhatID,HatVariable}
Returns the collection of consensus variables for the problem.
"""
function consensus_variables(phd::PHData)::Dict{XhatID,HatVariable}
return phd.xhat
end
"""
convert_to_variable_ids(phd::PHData, xid::XhatID)::Set{VariableID}
Convert the given consensus variable id to the contributing individual subproblem variable ids.
**Arguments**
* `phd::PHData` : PH data structure for the corresponding problem
* `xid::XhatID` : consensus variable id to convert
"""
function convert_to_variable_ids(phd::PHData, xid::XhatID)::Set{VariableID}
return variables(phd.xhat[xid])
end
"""
convert_to_xhat_id(phd::PHData, vid::VariableID)::XhatID
Convert the given `VariableID` to the consensus variable id (`XhatID`).
**Arguments**
* `phd::PHData` : PH data structure for the corresponding problem
* `vid::VariableID` : variable id to convert
"""
function convert_to_xhat_id(phd::PHData, vid::VariableID)::XhatID
return phd.variable_data[vid].xhat_id
end
"""
get_callback(phd::PHData, name::String)::Callback
Retrieve the callback with name `name`.
"""
function get_callback(phd::PHData, name::String)::Callback
return_cb = nothing
for cb in phd.callbacks
if cb.name == name
return_cb = cb
end
end
if isnothing(return_cb)
error("Unable to find callback $name.")
end
return return_cb
end
"""
get_callback_ext(phd::PHData, name::String)::Dict{Symbol,Any}
Retrieve the external dictionary for callback `name`.
"""
function get_callback_ext(phd::PHData, name::String)::Dict{Symbol,Any}
cb = get_callback(phd, name)
return cb.ext
end
"""
is_leaf(phd::PHData, xhid::XhatID)::Bool
Returns true if the given consensus variable id belongs to a leaf vertex in the scenario tree.
"""
function is_leaf(phd::PHData, xhid::XhatID)::Bool
return is_leaf(phd.scenario_tree, xhid.node)
end
"""
leaf_value(phd::PHData, vid::VariableID)::Float64
leaf_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
Returns the value of the variable associated with `vid` or with scenario `scen`, stage `stage` and index `idx`. Must be a leaf variable.
**WARNING:** For computational efficiency, leaf values are collected only at the end of a PH run. Therefore, using this function in a callback will result in an error.
See also: [`branch_value`](@ref), [`value`](@ref)
"""
function leaf_value(phd::PHData, vid::VariableID)::Float64
return phd.scenario_map[scenario(vid)].leaf_vars[vid]
end
function leaf_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
return leaf_value(phd, VariableID(scen, stage, idx))
end
"""
name(phd::PHData, vid::VariableID)::String
Returns the name of the consensus variable for the given `VariableID`.
"""
function name(phd::PHData, vid::VariableID)::String
if !haskey(phd.variable_data, vid)
error("No name available for variable id $vid")
end
return phd.variable_data[vid].name
end
"""
name(phd::PHData, xid::XhatID)::String
Returns the name of the consensus variable for the given [`XhatID`](@ref). The name is the same given to the individual scenario variables.
"""
function name(phd::PHData, xid::XhatID)::String
return name(phd, first(convert_to_variable_ids(phd, xid)))
end
"""
probability(phd::PHData, scenario::ScenarioID)::Float64
Returns the probability of the given scenario.
"""
function probability(phd::PHData, scenario::ScenarioID)::Float64
return phd.scenario_map[scenario].prob
end
"""
scenario_bundle(phd::PHData, xid::XhatID)::Set{ScenarioID}
Returns the scenarios contributing to the consensus variable associated with `xid`.
"""
function scenario_bundle(phd::PHData, xid::XhatID)::Set{ScenarioID}
return scenario_bundle(phd.scenario_tree, xid.node)
end
"""
scenario_tree(phd::PHData)::ScenarioTree
Returns the scenario tree for created stochastic programming problem.
"""
function scenario_tree(phd::PHData)::ScenarioTree
return phd.scenario_tree
end
"""
scenarios(phd::PHData)::Set{ScenarioID}
Returns the set of all scenarios for the stochastic problem.
"""
function scenarios(phd::PHData)::Set{ScenarioID}
return scenarios(phd.scenario_tree)
end
"""
stage_id(phd::PHData, xid::XhatID)::StageID
Returns the [`StageID`](@ref) in which the given consensus variable is.
"""
function stage_id(phd::PHData, xid::XhatID)::StageID
return phd.scenario_tree.tree_map[xid.node].stage
end
"""
print_timing([io::IO], phd::PHData)
Prints timining information from the Progressive Hedging solve.
"""
function print_timing(phd::PHData)
println(phd.time_info)
return
end
function print_timing(io::IO, phd::PHData)
println(io, phd.time_info)
return
end
"""
value(phd::PHData, vid::VariableID)
Returns the value of the variable associated with `vid`.
See also: [`branch_value`](@ref), [`leaf_value`](@ref)
"""
function value(phd::PHData, vid::VariableID)::Float64
return retrieve_variable_value(phd.scenario_map[scenario(vid)], vid)
end
"""
value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
Returns the value of the variable associated with scenario `scen`, stage `stage` and index `idx`.
See also: [`branch_value`](@ref), [`leaf_value`](@ref)
"""
function value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
vid = VariableID(scen, stage, idx)
return value(phd, vid)
end
"""
w_value(phd::PHData, vid::VariableID)
Returns the value of the variable associated with `vid`. Only available for branch variables.
"""
function w_value(phd::PHData, vid::VariableID)::Float64
return phd.scenario_map[scenario(vid)].w_vars[vid]
end
"""
w_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
Returns the value of the variable associated with scenario `scen`, stage `stage` and index `idx`. Only available for branch variables.
"""
function w_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
return w_value(phd, VariableID(scen, stage, idx))
end
"""
xhat_value(phd::PHData, xhid::VariableID)::Float64
Returns the value of the consensus variable associated with `xhid`. Only available for leaf variables after calling `solve`. Available for branch variables at any time.
"""
function xhat_value(phd::PHData, xhat_id::XhatID)::Float64
return value(phd.xhat[xhat_id])
end
"""
xhat_value(phd::PHData, vid::VariableID)::Float64
Returns the value of the consensus variable associated with `vid`. Only available for leaf variables after calling `solve`. Available for branch variables at any time.
"""
function xhat_value(phd::PHData, vid::VariableID)::Float64
return xhat_value(phd, convert_to_xhat_id(phd, vid))
end
"""
xhat_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
Returns the value of the consensus variable associated with scenario `scen`, stage `stage` and index `idx`. Only available for leaf variables after calling `solve`. Available for branch variables at any time.
"""
function xhat_value(phd::PHData, scen::ScenarioID, stage::StageID, idx::Index)::Float64
return xhat_value(phd, VariableID(scen, stage, idx))
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 11677 | #### PH Types Used in Interface ####
"""
Struct containing all information needed by PH about a variable (along with the variable id) to run the PH algorithm.
**Fields**
* `name::String` : User specified name of the variable
* `is_integer::Bool` : True if the variable is an integer or binary
"""
struct VariableInfo
name::String
is_integer::Bool # true if variable is integer or binary
end
#### PH Subproblem Interface ####
"""
Abstract type for ProgressiveHedging subproblem types.
A concrete subtype handles all details of creating, solving and updating subproblems for ProgressiveHedging (PH). In particular, it handles all interaction with any modeling language that the subproblem is written in. See `JuMPSubproblem` for an implementation that uses JuMP as the optimization modeling language.
Variables and their values are identified and exchanged between PH and a Subproblem type using the `VariableID` type. A unique `VariableID` is associated with each variable in the subproblem by the Subproblem implementation by using the `ScenarioID` of the subproblem as well as the `StageID` to which this variable belongs. This combination uniquely identifies a node in the scenario tree to which the variable can be associated. Variables associated with the same node in a scenario tree and sharing the same name are assumed to be consensus variables whose optimal value is determined by PH. The final component of a `VariableID` is an `Index` which is just a counter assigned to a variable to differentiate it from other variables at the same node. See `VariableID` type for more details.
Any concrete subtype **must** implement the following functions:
* [`add_ph_objective_terms`](@ref)
* [`objective_value`](@ref)
* [`report_values`](@ref)
* [`report_variable_info`](@ref)
* [`solve_subproblem`](@ref)
* [`update_ph_terms`](@ref)
See help strings on each function for details on arguments, returned objects and expected performance of each function. See JuMPSubproblem for an example using JuMP.
To use `warm_start=true` the concrete subtype must also implement
* [`warm_start`](@ref)
See help on `warm_start` for more information. See JuMPSubproblem for an example using JuMP.
To use the extensive form functionality, the concrete subtype must implement
* [`ef_copy_model`](@ref)
* [`ef_node_dict_constructor`](@ref)
See the help on the functions for more details. See JuMPSubproblem for an example using JuMP. Note that the extensive form model is always constructed as a `JuMP.Model` object.
To use penalty parameter types other than `ScalarPenaltyParameter`, concrete subproblem types also need to implement
* [`report_penalty_info`](@ref)
See the help on individual penalty parameter types and `report_penalty_info` for more details.
To use lower bound computation functionality, the concrete subtype must also implement
* [`add_lagrange_terms`](@ref)
* [`update_lagrange_terms`](@ref)
See the help on these functions for more details.
"""
abstract type AbstractSubproblem end
## Required Interface Functions ##
# The below functions must be implemented by any new subtype of AbstractSubproblem.
# Note they all default to throwing an `UnimplementedError`.
"""
add_ph_objective_terms(as::AbstractSubproblem,
vids::Vector{VariableID},
r::Union{Float64,Dict{VariableID,Float64}}
)::Dict{VariableID,Float64}
Create model variables for Lagrange multipliers and hat variables and add Lagrange and proximal terms to the objective function.
Returns mapping of the variable to any information needed from the subproblem to compute the penalty parameter. Only used if `is_subproblem_dependent(typeof(r))` returns `true`.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
* `vids::Vector{VariableID}` : list of `VariableIDs` which need ph terms created
* `r::AbstractPenaltyParameter` : penalty parameter on quadratic term
"""
function add_ph_objective_terms(as::AbstractSubproblem,
vids::Vector{VariableID},
r::Union{Float64,Dict{VariableID,Float64}},
)::Nothing
throw(UnimplementedError("add_ph_objective_terms is unimplemented"))
end
"""
objective_value(as::AbstractSubproblem)::Float64
Return the objective value of the solved subproblem.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
"""
function objective_value(as::AbstractSubproblem)::Float64
throw(UnimplementedError("objective_value is unimplemented"))
end
"""
report_penalty_info(as::AbstractSubproblem,
pp<:AbstractPenaltyParameter,
)::Dict{VariableID,Float64}
Returns mapping of variable to a value used to compute the penalty parameter.
This function must be implemented for any concrete penalty parameter type for which `is_subproblem_dependent` returns true and any concrete subproblem type wishing to use that penalty parameter. The mapping must contain all subproblem values needed for processing by `process_penalty_subproblem`. The returned mapping is handed unaltered to `process_penalty_subproblem` as the `subproblem_dict` argument.
**Arguments**
*`as::AbstractSubproblem` : subproblem object (replace with appropriate type)
*`pp<:AbstractPenaltyParameter` : penalty parameter type
"""
function report_penalty_info(as::AbstractSubproblem,
pp::Type{P},
)::Dict{VariableID,Float64} where P <: AbstractPenaltyParameter
throw(UnimplementedError("report_penalty_info is unimplmented for subproblem of type $(typeof(as)) and penalty parameter of type $(pp)."))
end
"""
report_variable_info(as::AbstractSubproblem,
st::ScenarioTree
)::Dict{VariableID, VariableInfo}
Assign `VariableID`s to all model variables and build a map from those ids to the required variable information (e.g., variable name). See `VariableInfo` help for details on required variable information.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
* `st::ScenarioTree` : scenario tree for the entire PH problem
"""
function report_variable_info(as::AbstractSubproblem,
st::ScenarioTree
)::Dict{VariableID, VariableInfo}
throw(UnimplementedError("report_variable_info is unimplemented"))
end
"""
report_values(as::AbstractSubproblem,
vars::Vector{VariableID}
)::Dict{VariableID, Float64}
Return the variable values specified by `vars`.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
* `vars::Vector{VariableID}` : collection of `VariableID`s to gather values for
"""
function report_values(as::AbstractSubproblem,
vars::Vector{VariableID}
)::Dict{VariableID, Float64}
throw(UnimplementedError("report_values is unimplemented"))
end
"""
solve_subproblem(as::AbstractSubproblem)::MOI.TerminationStatusCode
Solve the subproblem specified by `as` and return the status code.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
"""
function solve_subproblem(as::AbstractSubproblem)::MOI.TerminationStatusCode
throw(UnimplementedError("solve_subproblem is unimplemented"))
end
"""
update_ph_terms(as::AbstractSubproblem,
w_vals::Dict{VariableID,Float64},
xhat_vals::Dict{VariableID,Float64}
)::Nothing
Update the values of the PH variables in this subproblem with those given by `w_vals` and `xhat_vals`.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
* `w_vals::Dict{VariableID,Float64}` : Values to update Lagrangian variables with
* `xhat_vals::Dict{VariableID,Float64}` : Values to update proximal variables with
"""
function update_ph_terms(as::AbstractSubproblem,
w_vals::Dict{VariableID,Float64},
xhat_vals::Dict{VariableID,Float64}
)::Nothing
throw(UnimplementedError("update_ph_terms is unimplemented"))
end
"""
warm_start(as::AbstractSubproblem)::Nothing
Use the values of previous solves non-PH variables as starting points of the next solve.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
"""
function warm_start(as::AbstractSubproblem)::Nothing
throw(UnimplementedError("warm_start is unimplemented"))
end
## Optional Interface Functions ##
"""
add_lagrange_terms(as::AbstractSubproblem,
vids::Vector{VariableID}
)::Nothing
Create model variables for Lagrange multipliers and adds the corresponding terms to the objective function.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
* `vids::Vector{VariableID}` : list of `VariableIDs` which need Lagrange terms
See also [`add_ph_objective_terms`](@ref).
"""
function add_lagrange_terms(as::AbstractSubproblem,
vids::Vector{VariableID}
)::Nothing
throw(UnimplementedError("add_lagrange_terms is unimplemented"))
end
"""
update_lagrange_terms(as::AbstractSubproblem,
w_vals::Dict{VariableID,Float64}
)::Nothing
Update the values of the dual variables in this subproblem with those given by `w_vals`.
**Arguments**
* `as::AbstractSubproblem` : subproblem object (replace with appropriate type)
* `w_vals::Dict{VariableID,Float64}` : values to update Lagrange dual variables with
See also [`update_ph_terms`](@ref).
"""
function update_lagrange_terms(as::AbstractSubproblem,
w_vals::Dict{VariableID,Float64}
)::Nothing
throw(UnimplementedError("update_lagrange_terms is unimplemented"))
end
# These functions are required only if an extensive form construction is desired
"""
ef_copy_model(destination::JuMP.Model,
original::AbstractSubproblem,
scid::ScenarioID,
scen_tree::ScenarioTree,
node_dict::Dict{NodeID, Any}
)
Copy the subproblem described by `original` to the extensive form model `destination`.
**Arguments**
* `destination::JuMP.Model` : extensive form of the model that is being built
* `original::AbstractSubproblem` : subproblem object (replace with appropriate type)
* `scid::ScenarioID` : `ScenarioID` corresponding to this subproblem
* `scen_tree::ScenarioTree` : scenario tree for the entire PH problem
* `node_dict::Dict{NodeID, Any}` : dictionary for transferring nodal information from one submodel to another
"""
function ef_copy_model(destination::JuMP.Model,
original::AbstractSubproblem,
scid::ScenarioID,
scen_tree::ScenarioTree,
node_dict::Dict{NodeID, Any}
)
throw(UnimplementedError("ef_copy_model is unimplemented"))
end
"""
ef_node_dict_constructor(::Type{S}) where S <: AbstractSubproblem
Construct dictionary that is used to carry information between subproblems for `ef_copy_model`.
**Arguments**
* `::Type{S}` : Subproblem type
"""
function ef_node_dict_constructor(::Type{S}) where S <: AbstractSubproblem
throw(UnimplementedError("ef_node_dict_constructor is unimplemented"))
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 1764 | """
Struct for user supbroblem callbacks.
**Fields**
* `name::String` : User's name for the callback. Defaults to `string(h)`.
* `h::Function` : Callback function. See notes below for calling signature.
* `ext::Dict{Symbol,Any}` : Dictionary to store data between callback calls or needed parameters.
The callback function `h` must have the signature
`h(ext::Dict{Symbol,Any}, sp::T, niter::Int, scenario_id::ScenarioID) where T <: AbstractSubproblem`
where `ext` is the same dictionary given to the `Callback` constructor, `sp` is a concrete type of `AbstractSubproblem` (see `AbstractSubproblem`), `niter` is the current iteration and `scenario_id` is a scenario identifier (see `ScenarioID`).
"""
struct SubproblemCallback
name::String
h::Function
ext::Dict{Symbol,Any}
end
function Base.show(io::IO, spcb::SubproblemCallback)
print(io, spcb.name)
return
end
"""
SubproblemCallback(f::Function)
Creates a `SubproblemCallback` structure for function `f`.
"""
function SubproblemCallback(f::Function)
return SubproblemCallback(string(f), f, Dict{Symbol,Any}())
end
"""
SubproblemCallback(f::Function, ext::Dict{Symbol,Any})
Creates a `SubproblemCallback` structure for function `f` with the external data dictionary `ext`.
"""
function SubproblemCallback(f::Function, ext::Dict{Symbol,Any})
return SubproblemCallback(string(f), f, ext)
end
"""
spcb(f::Function)
spcb(f::Function, ext::Dict{Symbol,Any})
spcb(name::String, f::Function, ext::Dict{Symbol,Any})
Shorthand for `SubproblemCallback`.
"""
spcb(f::Function) = SubproblemCallback(f)
spcb(f::Function, ext::Dict{Symbol,Any}) = SubproblemCallback(f, ext)
spcb(name::String, f::Function, ext::Dict{Symbol,Any}) = SubproblemCallback(name, f, ext)
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 9724 |
## Helper Functions ##
function stringify(set::Set{K})::String where K
str = ""
for s in sort!(collect(set))
str *= string(s) * ","
end
return rstrip(str, [',',' '])
end
function stringify(array::Vector{K})::String where K
str = ""
for s in sort(array)
str *= string(s) * ","
end
return rstrip(str, [',',' '])
end
## Generic Utility Functions ##
function _two_stage_tree(n::Int, p::Vector{R})::ScenarioTree where R <: Real
st = ScenarioTree()
for s in 1:n
add_leaf(st, root(st), p[s])
end
return st
end
"""
two_stage_tree(n::Int)::ScenarioTree
two_stage_tree(p::Vector{R})::ScenarioTree where R <: Real
Construct and return a two-stage scenario tree with `n` scenarios with equal probability or a two-stage scenario tree with `length(p)` scenarios where probability of scenario s is `p[s+1]`.
"""
function two_stage_tree(n::Int)::ScenarioTree
return _two_stage_tree(n, [1.0/n for k in 1:n])
end
function two_stage_tree(p::Vector{R})::ScenarioTree where R <: Real
if !isapprox(sum(p), 1.0, atol=1e-8)
@warn("Given probability vector has total probability $(sum(p)). Normalizing to 1.")
p /= sum(p)
end
return _two_stage_tree(length(p), p)
end
function visualize_tree(phd::PHData)
# TODO: Implement this...
@warn("Not yet implemented")
return
end
## Complex PHData Interaction Functions ##
# NOTE: These functions are almost all post-processing functions
"""
lower_bounds(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with the computed and saved lower bounds. See the `lower_bound` keyword argument on [`solve`](@ref).
"""
function lower_bounds(phd::PHData)::DataFrames.DataFrame
lb_df = nothing
lower_bounds = phd.history.lower_bounds
for iter in sort!(collect(keys(lower_bounds)))
lb = lower_bounds[iter]
data = Dict{String,Any}("iteration" => iter,
"bound" => lb.lower_bound,
"absolute gap" => lb.gap,
"relative gap" => lb.rel_gap,
)
if isnothing(lb_df)
lb_df = DataFrames.DataFrame(data)
else
push!(lb_df, data)
end
end
if isnothing(lb_df)
lb_df = DataFrames.DataFrame()
end
return lb_df
end
"""
residuals(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with absolute and relative residuals along with the components. See the `save_residuals` keyword argument on [`solve`](@ref).
"""
function residuals(phd::PHData)::DataFrames.DataFrame
res_df = nothing
residuals = phd.history.residuals
for iter in sort!(collect(keys(residuals)))
res = residuals[iter]
data = Dict{String,Any}("iteration" => iter,
"absolute" => res.abs_res,
"relative" => res.rel_res,
"xhat_sq" => res.xhat_sq,
"x_sq" => res.x_sq
)
if isnothing(res_df)
res_df = DataFrames.DataFrame(data)
else
push!(res_df, data)
end
end
if isnothing(res_df)
res_df = DataFrames.DataFrame()
end
return res_df
end
"""
retrieve_soln(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with the solution values of all consensus and leaf variables.
"""
function retrieve_soln(phd::PHData)::DataFrames.DataFrame
vars = Vector{String}()
vals = Vector{Float64}()
stages = Vector{STAGE_ID}()
scens = Vector{String}()
for xid in sort!(collect(keys(phd.xhat)))
vid = first(convert_to_variable_ids(phd, xid))
push!(vars, name(phd, vid))
push!(vals, xhat_value(phd, xid))
push!(stages, value(stage_id(phd, xid)))
push!(scens, stringify(value.(scenario_bundle(phd, xid))))
end
soln_df = DataFrames.DataFrame(variable=vars, value=vals, stage=stages,
scenarios=scens)
return soln_df
end
"""
retrieve_aug_obj_value(phd::PHData)::Float64
Return the current objective value including Lagrange and proximal PH terms of the stochastic program.
"""
function retrieve_aug_obj_value(phd::PHData)::Float64
obj_value = 0.0
for (scid, sinfo) in pairs(phd.scenario_map)
obj_value += sinfo.prob * objective_value(sinfo)
end
return obj_value
end
"""
retrieve_obj_value(phd::PHData)::Float64
Return the current objective value without Lagrange and proximal PH terms.
"""
function retrieve_obj_value(phd::PHData)::Float64
obj_value = 0.0
for (scid, sinfo) in pairs(phd.scenario_map)
obj_s = objective_value(sinfo)
# Remove PH terms
for (vid, x_val) in pairs(sinfo.branch_vars)
w_val = sinfo.w_vars[vid]
xhat_val = xhat_value(phd, vid)
r = get_penalty_value(phd.r, convert_to_xhat_id(phd, vid))
obj_s -= w_val * x_val + 0.5 * r * (x_val - xhat_val)^2
end
obj_value += sinfo.prob * obj_s
end
return obj_value
end
"""
retrieve_no_hats(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with the final nonconsensus variable values.
"""
function retrieve_no_hats(phd::PHData)::DataFrames.DataFrame
vars = Vector{String}()
vals = Vector{Float64}()
stage = Vector{STAGE_ID}()
scenario = Vector{SCENARIO_ID}()
index = Vector{INDEX}()
variable_map = Dict{VariableID, Float64}()
for (scid,sinfo) in phd.scenario_map
merge!(variable_map, sinfo.branch_vars, sinfo.leaf_vars)
end
for vid in sort!(collect(keys(variable_map)))
push!(vars, name(phd, vid))
push!(vals, variable_map[vid])
push!(stage, value(vid.stage))
push!(scenario, value(vid.scenario))
push!(index, value(vid.index))
end
soln_df = DataFrames.DataFrame(variable=vars, value=vals, stage=stage,
scenario=scenario, index=index)
return soln_df
end
"""
retrieve_w(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with the final anticipativity constraint Lagrange multiplier values.
"""
function retrieve_w(phd::PHData)::DataFrames.DataFrame
vars = Vector{String}()
vals = Vector{Float64}()
stage = Vector{STAGE_ID}()
scenario = Vector{SCENARIO_ID}()
index = Vector{INDEX}()
variable_map = Dict{VariableID, Float64}()
for (scid,sinfo) in phd.scenario_map
merge!(variable_map, sinfo.w_vars)
end
for vid in sort!(collect(keys(variable_map)))
push!(vars, "W_" * name(phd, vid))
push!(vals, variable_map[vid])
push!(stage, value(vid.stage))
push!(scenario, value(vid.scenario))
push!(index, value(vid.index))
end
soln_df = DataFrames.DataFrame(variable=vars, value=vals, stage=stage,
scenario=scenario, index=index)
return soln_df
end
"""
retrieve_xhat_history(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with the saved consensus variable values. See the `save_iterates` keyword argument on [`solve`](@ref).
"""
function retrieve_xhat_history(phd::PHData)::DataFrames.DataFrame
xhat_df = nothing
iterates = phd.history.iterates
for iter in sort!(collect(keys(iterates)))
data = Dict{String,Any}("iteration" => iter)
for xhid in sort!(collect(keys(phd.xhat)))
if !is_leaf(phd, xhid)
vname = name(phd, xhid) * "_" * stringify(value.(scenario_bundle(phd, xhid)))
data[vname] = iterates[iter].xhat[xhid]
end
end
if isnothing(xhat_df)
xhat_df = DataFrames.DataFrame(data)
else
push!(xhat_df, data)
end
end
if isnothing(xhat_df)
xhat_df = DataFrames.DataFrame()
end
return xhat_df
end
"""
retrieve_no_hat_history(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with the saved nonconsensus variable values. See the `save_iterates` keyword argument on [`solve`](@ref).
"""
function retrieve_no_hat_history(phd::PHData)::DataFrames.DataFrame
x_df = nothing
iterates = phd.history.iterates
for iter in sort!(collect(keys(iterates)))
current_iterate = iterates[iter]
data = Dict{String,Any}("iteration" => iter)
for vid in sort!(collect(keys(current_iterate.x)))
vname = name(phd, vid) * "_$(value(scenario(vid)))"
data[vname] = current_iterate.x[vid]
end
if isnothing(x_df)
x_df = DataFrames.DataFrame(data)
else
push!(x_df, data)
end
end
if isnothing(x_df)
x_df = DataFrames.DataFrame()
end
return x_df
end
"""
retrieve_w_history(phd::PHData)::DataFrames.DataFrame
Return a `DataFrame` with the saved PH Lagrange variable values. See the `save_iterates` keyword argument on [`solve`](@ref).
"""
function retrieve_w_history(phd::PHData)::DataFrames.DataFrame
w_df = nothing
iterates = phd.history.iterates
for iter in sort!(collect(keys(iterates)))
current_iterate = iterates[iter]
data = Dict{String,Any}("iteration" => iter)
for vid in sort!(collect(keys(current_iterate.w)))
vname = "W_" * name(phd, vid) * "_$(value(scenario(vid)))"
data[vname] = current_iterate.w[vid]
end
if isnothing(w_df)
w_df = DataFrames.DataFrame(data)
else
push!(w_df, data)
end
end
if isnothing(w_df)
w_df = DataFrames.DataFrame()
end
return w_df
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 10633 | #### Worker Structs ####
struct SubproblemRecord
problem::AbstractSubproblem
branch_vars::Vector{VariableID}
leaf_vars::Vector{VariableID}
subproblem_callbacks::Vector{SubproblemCallback}
end
mutable struct WorkerRecord
id::Int
warm_start::Bool
subproblems::Dict{ScenarioID,SubproblemRecord}
lb_subproblems::Dict{ScenarioID,SubproblemRecord}
end
function WorkerRecord(id::Int)
return WorkerRecord(id,
false,
Dict{ScenarioID,SubproblemRecord}(),
Dict{ScenarioID,SubproblemRecord}(),
)
end
#### Worker Functions ####
function worker_loop(id::Int,
input::RemoteChannel,
output::RemoteChannel,
)::Int
running = true
my_record = WorkerRecord(id)
try
while running
msg = take!(input)
running = process_message(msg, my_record, output)
end
catch e
while isready(input)
take!(input)
end
rethrow()
finally
; # intentional no-op
end
return 0
end
function process_message(msg::Message,
record::WorkerRecord,
output::RemoteChannel
)::Bool
error("Worker unable to process message type: $(typeof(msg))")
return false
end
function process_message(msg::Abort,
record::WorkerRecord,
output::RemoteChannel
)::Bool
return false
end
function process_message(msg::DumpState,
record::WorkerRecord,
output::RemoteChannel
)::Bool
put!(output, WorkerState(record.id, record))
return true
end
function process_message(msg::Initialize,
record::WorkerRecord,
output::RemoteChannel
)::Bool
record.warm_start = msg.warm_start
# Master process needs the variable map messages to proceed. Initial solves are
# not needed until much later in the process. So get all variable maps back first
# then start working on the initial solves and the objective augmentation
_build_subproblems(output,
record,
msg.scenarios,
msg.scenario_tree,
msg.create_subproblem,
msg.create_subproblem_args,
msg.create_subproblem_kwargs,
msg.subproblem_callbacks
)
_initial_solve(output, record)
_penalty_parameter_preprocess(output, record, msg.r)
return true
end
function process_message(msg::InitializeLowerBound,
record::WorkerRecord,
output::RemoteChannel,
)::Bool
for scen in msg.scenarios
lb_sub = msg.create_subproblem(scen,
msg.create_subproblem_args...;
msg.create_subproblem_kwargs...
)
var_map = report_variable_info(lb_sub, msg.scenario_tree)
(branch_ids, leaf_ids) = _split_variables(msg.scenario_tree,
collect(keys(var_map))
)
add_lagrange_terms(lb_sub, branch_ids)
record.lb_subproblems[scen] = SubproblemRecord(lb_sub,
branch_ids,
leaf_ids,
SubproblemCallback[]
)
end
return true
end
function process_message(msg::PenaltyInfo,
record::WorkerRecord,
output::RemoteChannel,
)::Bool
if !haskey(record.subproblems, msg.scen)
error("Worker $(record.id) received penalty parameter values for scenario $(msg.scen). This worker was not assigned this scenario.")
end
sub = record.subproblems[msg.scen]
add_ph_objective_terms(sub.problem,
sub.branch_vars,
msg.penalty)
return true
end
function process_message(msg::Ping,
record::WorkerRecord,
output::RemoteChannel
)::Bool
put!(output, Ping())
return true
end
function process_message(msg::Solve,
record::WorkerRecord,
output::RemoteChannel
)::Bool
if !haskey(record.subproblems, msg.scen)
error("Worker $(record.id) received solve command for scenario $(msg.scen). This worker was not assigned this scenario.")
end
sub = record.subproblems[msg.scen]
update_ph_terms(sub.problem, msg.w_vals, msg.xhat_vals)
_execute_subproblem_callbacks(sub, msg.niter, msg.scen)
if record.warm_start
warm_start(sub.problem)
end
start = time()
sts = solve_subproblem(sub.problem)
stop = time()
var_vals = report_values(sub.problem, sub.branch_vars)
put!(output, ReportBranch(msg.scen,
sts,
objective_value(sub.problem),
stop - start,
var_vals)
)
return true
end
function process_message(msg::SolveLowerBound,
record::WorkerRecord,
output::RemoteChannel
)::Bool
if !haskey(record.lb_subproblems, msg.scen)
error("Worker $(record.id) received lower-bound solve command for scenario $(msg.scen). This worker was not assigned this scenario.")
end
lb_sub = record.lb_subproblems[msg.scen]
update_lagrange_terms(lb_sub.problem, msg.w_vals)
if record.warm_start
warm_start(lb_sub.problem)
end
start = time()
sts = solve_subproblem(lb_sub.problem)
stop = time()
put!(output, ReportLowerBound(msg.scen,
sts,
objective_value(lb_sub.problem),
stop - start)
)
return true
end
function process_message(msg::ShutDown,
record::WorkerRecord,
output::RemoteChannel
)::Bool
for (s, sub) in pairs(record.subproblems)
leaf_vals = report_values(sub.problem, sub.leaf_vars)
put!(output, ReportLeaf(s, leaf_vals))
end
return false
end
function process_message(msg::SubproblemAction,
record::WorkerRecord,
output::RemoteChannel
)::Bool
sub = record.subproblems[msg.scen].problem
msg.action(sub, msg.args...; msg.kwargs...)
return true
end
#### Internal Functions ####
function _build_subproblems(output::RemoteChannel,
record::WorkerRecord,
scenarios::Set{ScenarioID},
scen_tree::ScenarioTree,
create_subproblem::Function,
create_subproblem_args::Tuple,
create_subproblem_kwargs::NamedTuple,
subproblem_callbacks::Vector{SubproblemCallback}
)::Nothing
for scen in scenarios
# Create subproblem
sub = create_subproblem(scen,
create_subproblem_args...;
create_subproblem_kwargs...)
# Assign variable ids (scenario, stage, index) to variable names and send
# that map to the master process -- master process expects names to match
# for variables that have anticipativity constraints
var_map = report_variable_info(sub, scen_tree)
put!(output, VariableMap(scen, var_map))
# Break variables into branch and leaf
(branch_ids, leaf_ids) = _split_variables(scen_tree,
collect(keys(var_map)))
# Save subproblem and relevant data
record.subproblems[scen] = SubproblemRecord(sub,
branch_ids,
leaf_ids,
subproblem_callbacks
)
end
return
end
function _execute_subproblem_callbacks(sub::SubproblemRecord,
niter::Int,
scen::ScenarioID
)::Nothing
for spcb in sub.subproblem_callbacks
spcb.h(spcb.ext, sub.problem, niter, scen)
end
return
end
function _initial_solve(output::RemoteChannel,
record::WorkerRecord
)::Nothing
for (scen, sub) in record.subproblems
start = time()
sts = solve_subproblem(sub.problem)
stop = time()
var_vals = report_values(sub.problem, sub.branch_vars)
put!(output, ReportBranch(scen,
sts,
objective_value(sub.problem),
stop - start,
var_vals)
)
end
return
end
function _penalty_parameter_preprocess(output::RemoteChannel,
record::WorkerRecord,
r::Type{P},
) where P <: AbstractPenaltyParameter
if is_subproblem_dependent(r)
for (scen, sub) in record.subproblems
pen_map = report_penalty_info(sub.problem, sub.branch_vars, r)
put!(output, PenaltyInfo(scen, pen_map))
end
end
return
end
function _split_variables(scen_tree::ScenarioTree,
vars::Vector{VariableID},
)::NTuple{2,Vector{VariableID}}
branch_vars = Vector{VariableID}()
leaf_vars = Vector{VariableID}()
for vid in vars
if is_leaf(scen_tree, vid)
push!(leaf_vars, vid)
else
push!(branch_vars, vid)
end
end
return (branch_vars, leaf_vars)
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 4512 | # Type containing information on workers.
struct WorkerInf
inputs::Dict{Int,RemoteChannel{Channel{Message}}}
output::RemoteChannel{Channel{Message}}
wait::Vector{Message}
results::Dict{Int,Future}
end
function WorkerInf(inputs::Dict{Int,RemoteChannel{Channel{Message}}},
output::RemoteChannel{Channel{Message}},
results::Dict{Int,Future}
) where T
return WorkerInf(inputs,
output,
Vector{Message}(),
results)
end
function _abort(wi::WorkerInf)::Nothing
for (wid, rc) in pairs(wi.inputs)
put!(rc, Abort())
end
while isready(wi.output)
# Ensure that workers aren't blocked
take!(wi.output)
end
return
end
function _check_wait(wi::WorkerInf,
msg_type::Type{M}
)::Union{Nothing,M} where M <: Message
# println("Checking wait queue...")
retval = nothing
for (k,msg) in enumerate(wi.wait)
if typeof(msg) <: msg_type
retval = msg
deleteat!(wi.wait, k)
break
end
end
return retval
end
function _is_running(wi::WorkerInf)
return length(wi.results) > 0
end
function _launch_workers(min_worker_size::Int,
min_result_size::Int,
)::WorkerInf
worker_q_size = min_worker_size
result_q_size = max(2*nworkers(), min_result_size)
worker_results = RemoteChannel(()->Channel{Message}(result_q_size))
worker_qs = Dict{Int,RemoteChannel{Channel{Message}}}()
futures = Dict{Int,Future}()
@sync for wid in workers()
@async begin
worker_q = RemoteChannel(()->Channel{Message}(worker_q_size), wid)
futures[wid] = remotecall(worker_loop, wid, wid, worker_q, worker_results)
worker_qs[wid] = worker_q
end
end
wi = WorkerInf(worker_qs, worker_results, futures)
_monitor_workers(wi)
return wi
end
function _monitor_workers(wi::WorkerInf)::Nothing
# println("Checking worker status...")
for (pid, f) in pairs(wi.results)
if isready(f)
# Whatever the return value, this worker is done and
# we can stop checking on it
delete!(wi.results, pid)
delete!(wi.inputs, pid)
try
# Fetch on a remote process result will throw and error here
# whereas fetch on a task requires that it is thrown. Hence
# the try-catch AND the type check for an exception.
e = fetch(f)
if typeof(e) <: Int
# Normal Exit -- do nothing
elseif typeof(e) <: Exception
throw(e)
else
error("Unexpected return code from worker: $e")
end
catch e
_abort(wi)
rethrow()
finally
;
end
end
end
return
end
function _number_workers(wi::WorkerInf)
return length(wi.results)
end
function _retrieve_message(wi::WorkerInf)::Message
# println("Checking message queue...")
while !isready(wi.output) && _is_running(wi)
_monitor_workers(wi)
yield()
end
msg = take!(wi.output)
return msg
end
function _retrieve_message_type(wi::WorkerInf,
msg_type::Type{M}
)::M where M <: Message
# Check if we have this type of message in the wait queue
msg = _check_wait(wi, msg_type)
while isnothing(msg)
# Check get messages from the remote channel
msg = _retrieve_message(wi)
# If it's wrong put it on the wait queue for later and keep looking
if !(typeof(msg) <: msg_type)
push!(wi.wait, msg)
msg = nothing
end
end
return msg
end
function _send_message(wi::WorkerInf,
wid::Int,
msg::Message,
)
# println("Sending message of type $(typeof(msg)) to worker $(wid)")
put!(wi.inputs[wid], msg)
return
end
function _shutdown(wi::WorkerInf)
@sync for rchan in values(wi.inputs)
@async put!(rchan, ShutDown())
end
return
end
function _wait_for_shutdown(wi::WorkerInf)::Nothing
while _is_running(wi)
_monitor_workers(wi)
yield()
end
return
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 7384 |
@everywhere function create_model(scenario_id::PH.ScenarioID;
opt=()->Ipopt.Optimizer(),
opt_args=(print_level=0,)
)
model = JuMP.Model(opt)
for (key,value) in pairs(opt_args)
JuMP.set_optimizer_attribute(model, string(key), value)
end
scid = PH.value(scenario_id)
c = [1.0, 10.0, 0.01]
d = 7.0
a = 16.0
α = 1.0
β = 1.0
γ = 1.0
δ = 1.0
ϵ = 1.0
s1 = 8.0
s2 = 4.0
s11 = 9.0
s12 = 16.0
s21 = 5.0
s22 = 18.0
stage1 = JuMP.@variable(model, x[1:3] >= 0.0)
JuMP.@constraint(model, x[3] <= 1.0)
obj = zero(JuMP.GenericQuadExpr{Float64,JuMP.VariableRef})
JuMP.add_to_expression!(obj, sum(c.*x))
# Second stage
stage2 = Vector{JuMP.VariableRef}()
if scid < 2
vref = JuMP.@variable(model, y >= 0.0)
JuMP.@constraint(model, α*sum(x) + β*y >= s1)
JuMP.add_to_expression!(obj, d*y)
else
vref = JuMP.@variable(model, y >= 0.0)
JuMP.@constraint(model, α*sum(x) + β*y >= s2)
JuMP.add_to_expression!(obj, d*y)
end
push!(stage2, vref)
# Third stage
stage3 = Vector{JuMP.VariableRef}()
if scid == 0
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s11)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
elseif scid == 1
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s12)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
elseif scid == 2
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s21)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
else
vref = JuMP.@variable(model, z[1:2])
JuMP.@constraint(model, ϵ*sum(x) + γ*y + δ*sum(z) == s22)
JuMP.add_to_expression!(obj, a*sum(z[i]^2 for i in 1:2))
end
append!(stage3, vref)
JuMP.@objective(model, Min, obj)
vdict = Dict{PH.StageID, Vector{JuMP.VariableRef}}(PH.stid(1) => stage1,
PH.stid(2) => stage2,
PH.stid(3) => stage3,
)
return JuMPSubproblem(model, scenario_id, vdict)
end
function build_scen_tree()
probs = [0.5*0.75, 0.5*0.25, 0.5*0.75, 0.5*0.25]
tree = PH.ScenarioTree()
for k in 1:2
node2 = PH.add_node(tree, tree.root)
for l in 1:2
PH.add_leaf(tree, node2, probs[(k-1)*2 + l])
end
end
return tree
end
function timeout_wait(t::Task, limit::Real=10, interval::Real=1)
count = 0
success = false
while true
sleep(interval)
count += 1
if istaskdone(t)
success = true
break
elseif count >= limit
break
end
end
return success
end
function invert_map(my_map::Dict{A,B})::Dict{B,A} where {A,B}
inv_map = Dict{B,A}()
for (k,v) in pairs(my_map)
inv_map[v] = k
end
@assert length(inv_map) == length(my_map)
return inv_map
end
@everywhere function two_stage_model(scenario_id::PH.ScenarioID)
model = JuMP.Model(()->Ipopt.Optimizer())
JuMP.set_optimizer_attribute(model, "print_level", 0)
JuMP.set_optimizer_attribute(model, "tol", 1e-12)
JuMP.set_optimizer_attribute(model, "acceptable_tol", 1e-12)
scen = PH.value(scenario_id)
ref = JuMP.@variable(model, 0.0 <= x <= 1000.0)
stage1 = [ref]
push!(stage1, JuMP.@variable(model, 0.0 <= u <= 1.0))
ref = JuMP.@variable(model, y >= 0.0)
stage2 = [ref]
val = scen == 0 ? 11.0 : 4.0
JuMP.@constraint(model, x + y + u == val)
c_y = scen == 0 ? 1.5 : 2.0
JuMP.@objective(model, Min, 1.0*x + c_y * y)
return PH.JuMPSubproblem(model, scenario_id, Dict(PH.stid(1) => stage1,
PH.stid(2) => stage2)
)
end
if isdefined(Main, :Xpress)
function two_stage_int(scenario_id::PH.ScenarioID)
model = JuMP.Model(()->Xpress.Optimizer())
JuMP.set_optimizer_attribute(model, "OUTPUTLOG", 0)
scen = PH.value(scenario_id)
ref = JuMP.@variable(model, 4 <= k <= 10, Int)
stage1 = [ref]
ref = JuMP.@variable(model, y)
stage2 = [ref]
val = 2.0 * scen
JuMP.@constraint(model, k + y == val)
c_y = (scen % 2 == 0 ? 1.0 : 5.0)
JuMP.@objective(model, Min, c_y * y^2 + 2.0*k)
return PH.JuMPSubproblem(model, scenario_id, Dict(PH.stid(1) => stage1,
PH.stid(2) => stage2)
)
end
end
function build_var_map(n::Int,
m1::Int,
m2::Int)
vmap = Dict{PH.ScenarioID, Dict{PH.VariableID, PH.VariableInfo}}()
vval = Dict{PH.ScenarioID, Dict{PH.VariableID, Float64}}()
for k in 1:n
scid = PH.scid(k-1)
vars = Dict{PH.VariableID, PH.VariableInfo}()
vals = Dict{PH.VariableID, Float64}()
# Stage 1 variables
for j in 1:m1
vid = PH.VariableID(scid, PH.stid(1), PH.index(j + k - 1))
vars[vid] = PH.VariableInfo("a$j",false) # convert(Float64, j)
vals[vid] = convert(Float64, j)
end
# Stage 2 variables
for j in 1:m2
vid = PH.VariableID(scid, PH.stid(2), PH.index(j-1))
vars[vid] = PH.VariableInfo("b$j", false) # convert(Float64, k*j + n)
vals[vid] = convert(Float64, k*j + n)
end
vmap[scid] = vars
vval[scid] = vals
end
return (vmap, vval)
end
function fake_phdata(nv1::Int, nv2::Int; add_leaves=true)
nscen = 2
st = two_stage_tree(nscen)
(var_map, var_val) = build_var_map(nscen, nv1, nv2)
phd = PH.PHData(PH.ScalarPenaltyParameter(1.0),
st,
Dict(1=>copy(PH.scenarios(st))),
var_map,
TimerOutputs.TimerOutput()
)
for (scid, sinfo) in pairs(phd.scenario_map)
for vid in keys(sinfo.branch_vars)
xhid = PH.convert_to_xhat_id(phd, vid)
sinfo.branch_vars[vid] = var_val[scid][vid]
phd.xhat[xhid].value = var_val[scid][vid]
end
if add_leaves
# Create entries for leaf variables. This is normally done at the end of the
# solve call but since we aren't calling that here...
for vid in keys(sinfo.leaf_vars)
xhid = PH.convert_to_xhat_id(phd, vid)
sinfo.leaf_vars[vid] = var_val[scid][vid]
phd.xhat[xhid] = PH.HatVariable(var_val[scid][vid], vid, false)
end
end
end
return phd
end
function fake_worker_info(queue_size::Int=10)
worker_results = RemoteChannel(()->Channel{PH.Message}(queue_size))
worker_queue = RemoteChannel(()->Channel{PH.Message}(queue_size))
return PH.WorkerInf(Dict(1=>worker_queue),
worker_results,
Dict(1=>Future())
)
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 1313 |
using ProgressiveHedging
const PH = ProgressiveHedging
using Test
using Distributed
using Ipopt
using JuMP
using MathOptInterface
const MOI = MathOptInterface
using Suppressor
using TimerOutputs
macro optional_using(pkg)
quote
try
using $pkg
catch e
if typeof(e) != ArgumentError
rethrow(e)
end
end
end
end
@optional_using(Xpress)
include("common.jl")
@testset "ProgressiveHedging" begin
@testset "Scenario Tree" begin
include("test_tree.jl")
end
@testset "Sanity Checks" begin
include("test_sanity.jl")
end
@testset "Utils" begin
include("test_utils.jl")
end
@testset "Subproblem" begin
include("test_subproblem.jl")
end
@testset "Workers" begin
include("test_worker.jl")
end
@testset "Penalty Parameters" begin
include("test_penalty.jl")
end
@testset "Callbacks" begin
include("test_callback.jl")
end
@testset "Setup" begin
include("test_setup.jl")
end
@testset "Algorithm" begin
include("test_algorithm.jl")
end
@testset "Distributed" begin
include("test_distributed.jl")
end
@testset "Post Processing" begin
include("test_post.jl")
end
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 9860 |
r = PH.ScalarPenaltyParameter(25.0)
atol = 1e-8
rtol = 1e-12
max_iter = 500
obj_val = 178.3537498401004
var_vals = Dict([
"x[1]_{0,1,2,3}" => 7.5625,
"x[2]_{0,1,2,3}" => 0.0,
"x[3]_{0,1,2,3}" => 1.0,
"y_{0,1}" => 1.75,
"y_{2,3}" => 0.0,
"z[1]_{0}" => -0.65625,
"z[2]_{0}" => -0.65625,
"z[1]_{1}" => 2.84375,
"z[2]_{1}" => 2.84375,
"z[1]_{2}" => -1.78125,
"z[2]_{2}" => -1.78125,
"z[1]_{3}" => 4.71875,
"z[2]_{3}" => 4.71875,
])
@testset "Solve Extensive" begin
efm = PH.solve_extensive(build_scen_tree(),
create_model,
()->Ipopt.Optimizer();
opt_args=(print_level=0,tol=1e-12)
)
@test JuMP.num_variables(efm) == length(keys(var_vals))
cnum = 0
for (f,s) in JuMP.list_of_constraint_types(efm)
cnum += JuMP.num_constraints(efm, f, s)
end
@test cnum == 12
@test JuMP.termination_status(efm) == MOI.LOCALLY_SOLVED
@test isapprox(JuMP.objective_value(efm), obj_val)
for var in JuMP.all_variables(efm)
@test isapprox(JuMP.value(var), var_vals[JuMP.name(var)])
end
struct FakeSubproblem <: AbstractSubproblem end
fake_constructor(scen::Int) = FakeSubproblem()
@test_throws(ProgressiveHedging.UnimplementedError,
PH.solve_extensive(build_scen_tree(),
fake_constructor,
()->Ipopt.Optimizer(),
subproblem_type=FakeSubproblem)
)
end
@testset "Solve (Scalar)" begin
(n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
timing=false,
warm_start=false)
@test err < atol
@test isapprox(obj, obj_val)
@test n < max_iter
for row in eachrow(soln)
var = row[:variable] * "_{" * row[:scenarios] * "}"
@test isapprox(row[:value], var_vals[var], atol=1e-7)
end
end
@testset "Solve (Proportional)" begin
prop_max_iter = 500
prop_atol = 1e-8
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
two_stage_model,
PH.ProportionalPenaltyParameter(25.0),
atol=prop_atol,
rtol=1e-12,
max_iter=prop_max_iter,
report=0,
timing=false,
warm_start=false
)
@test err < prop_atol
@test isapprox(obj, 8.25, atol=1e-6)
@test n < prop_max_iter
for row in eachrow(soln)
if row[:variable] == "x"
@test isapprox(row[:value], 3.0)
elseif row[:variable] == "u"
@test isapprox(row[:value], 1.0)
elseif row[:variable] == "y"
if row[:scenarios] == "0"
@test isapprox(row[:value], 7.0)
else
@test isapprox(row[:value], 0.0, atol=1e-8)
end
end
end
end
@testset "Solve (SEP)" begin
prop_max_iter = 500
prop_atol = 1e-8
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
two_stage_model,
PH.SEPPenaltyParameter(),
atol=prop_atol,
rtol=1e-12,
max_iter=prop_max_iter,
report=0,
timing=false,
warm_start=false
)
@test err < prop_atol
@test isapprox(obj, 8.25, atol=1e-6)
@test n < prop_max_iter
for row in eachrow(soln)
if row[:variable] == "x"
@test isapprox(row[:value], 3.0)
elseif row[:variable] == "u"
@test isapprox(row[:value], 1.0)
elseif row[:variable] == "y"
if row[:scenarios] == "0"
@test isapprox(row[:value], 7.0)
else
@test isapprox(row[:value], 0.0, atol=1e-8)
end
end
end
end
@testset "Warm-start" begin
(n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=-5,
timing=false,
warm_start=true)
@test err < atol
@test isapprox(obj, obj_val)
@test n < max_iter
for row in eachrow(soln)
var = row[:variable] * "_{" * row[:scenarios] * "}"
@test isapprox(row[:value], var_vals[var], atol=1e-7)
end
end
@testset "Max iteration termination" begin
max_iter = 4
regex = r".*"
@info "Ignore the following warning."
(n, err, rerr, obj, soln, phd) = @test_warn(regex,
PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
timing=false)
)
@test err > atol
@test rerr > rtol
@test n == max_iter
end
@testset "Relative tolerance termination" begin
rtol = 1e-6
(n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
timing=false,
warm_start=true)
# xmax = maximum(soln[soln[:,:stage] .!= 3,:value])
@test err > atol
@test n < max_iter
#@test err < rtol * xmax
@test rerr < rtol
end
@testset "Lower Bound Algorithm" begin
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
two_stage_model,
PH.ScalarPenaltyParameter(2.0),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
lower_bound=5,
timing=false,
warm_start=false
)
@test err < atol
@test isapprox(obj, 8.25, atol=1e-6)
@test n < max_iter
lb_df = PH.lower_bounds(phd)
for row in eachrow(lb_df)
@test row[:bound] <= 8.25
end
@test size(lb_df,1) == 12
@test isapprox(lb_df[size(lb_df,1), "absolute gap"], 0.0, atol=1e-7)
@test isapprox(lb_df[size(lb_df,1), "relative gap"], 0.0, atol=(1e-7/8.25))
end
@testset "Lower Bound Termination" begin
gap_tol = 1e-3
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
two_stage_model,
PH.ScalarPenaltyParameter(2.0),
gap_tol=gap_tol,
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
lower_bound=5,
timing=false,
warm_start=false
)
lb_df = PH.lower_bounds(phd)
@test err > atol
@test rerr > rtol
@test n < max_iter
@test lb_df[size(lb_df,1), "relative gap"] < gap_tol
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 12818 |
macro cb_gen(name, num)
fn = Symbol(name * "_" * string(num))
quote
function $(esc(fn))(ext::Dict{Symbol,Any},
phd::PH.PHData,
winfo::PH.WorkerInf,
niter::Int
)::Bool
return true
end
end
end
function fake_init(ext::Dict{Symbol,Any}, phd::PHData)
ext[:fake] = rand() + 1.0
return
end
@testset "Callback Utilities" begin
@cb_gen("cb", 1)
@cb_gen("cb", 2)
@cb_gen("cb", 3)
@cb_gen("cb", 4)
@cb_gen("cb", 5)
@cb_gen("cb", 6)
my_cbs = [cb(cb_1),
cb(cb_2, Dict{Symbol,Any}(:b=>"TESTING!")),
cb(cb_3, fake_init),
cb(cb_4, fake_init, Dict{Symbol,Any}(:d => "Still a test")),
cb("Fifth CB", cb_5, Dict{Symbol,Any}(:e => "More of a test")),
cb("Sixth CB", cb_6, fake_init, Dict{Symbol,Any}(:f => "This is only a test")),
]
phd = fake_phdata(3,4)
for (k,cb) in enumerate(my_cbs)
PH.add_callback(phd, cb)
if k == 1
@test isempty(cb.ext)
@test cb.h === cb_1
elseif k == 2
@test cb.ext[:b] == "TESTING!"
@test cb.h === cb_2
elseif k == 3
@test cb.ext[:fake] > 1.0
@test cb.h === cb_3
elseif k == 4
@test cb.ext[:d] == "Still a test"
@test cb.ext[:fake] > 1.0
@test cb.h === cb_4
elseif k == 5
@test cb.name == "Fifth CB"
@test cb.ext[:e] == "More of a test"
@test cb.h === cb_5
else
@test cb.name == "Sixth CB"
@test cb.ext[:f] == "This is only a test"
@test cb.ext[:fake] > 1.0
@test cb.h === cb_6
end
end
for cb in my_cbs
@test cb === get_callback(phd, cb.name)
@test cb.ext === get_callback_ext(phd, cb.name)
end
@test_throws ErrorException get_callback(phd, "'Tis but a flesh wound")
end
@testset "Callback Termination" begin
function my_term_cb(ext::Dict{Symbol,Any},
phd::PH.PHData,
winf::PH.WorkerInf,
niter::Int
)::Bool
return niter < 5
end
the_cb = cb(my_term_cb)
io = IOBuffer()
Base.show(io, the_cb)
@test String(take!(io)) == "my_term_cb"
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
two_stage_model,
PH.ScalarPenaltyParameter(2.0),
atol=1e-8,
rtol=1e-12,
max_iter=500,
timing=false,
warm_start=false,
callbacks=[the_cb]
)
@test err > 1e-8
@test rerr > 1e-12
@test n == 5
end
@testset "Callback Subproblem" begin
struct TestSubproblem <: PH.AbstractSubproblem
scenario::PH.ScenarioID
names::Dict{PH.VariableID,PH.VariableInfo}
values::Dict{PH.VariableID,Float64}
end
function create_test(scen::PH.ScenarioID)::TestSubproblem
return TestSubproblem(scen,
Dict{PH.VariableID,PH.VariableInfo}(),
Dict{PH.VariableID,Float64}())
end
function PH.add_ph_objective_terms(ts::TestSubproblem,
vids::Vector{PH.VariableID},
r::Union{Float64,
Dict{VariableID,Float64}},
)::Nothing
return
end
function PH.objective_value(ts::TestSubproblem)::Float64
return 0.0
end
function PH.report_values(ts::TestSubproblem,
vars::Vector{PH.VariableID},
)::Dict{PH.VariableID,Float64}
vals = Dict{PH.VariableID,Float64}()
for vid in vars
vals[vid] = ts.values[vid]
end
return vals
end
function PH.report_variable_info(ts::TestSubproblem,
st::ScenarioTree
)::Dict{VariableID,PH.VariableInfo}
for node in PH.scenario_nodes(st, ts.scenario)
stid = PH.stage(node)
stage = PH.value(stid)
vid = PH.VariableID(ts.scenario, stid, PH.Index(0))
ts.names[vid] = PH.VariableInfo(string('a' + stage - 1), false)
ts.values[vid] = rand()
end
return ts.names
end
function PH.solve_subproblem(ts::TestSubproblem)::MOI.TerminationStatusCode
return MOI.OPTIMAL
end
function PH.update_ph_terms(ts::TestSubproblem,
w_vals::Dict{PH.VariableID,Float64},
xhat_vals::Dict{VariableID,Float64}
)::Nothing
return
end
function to_apply(ts::TestSubproblem, set_values::Dict{VariableID,Float64})
for (vid, value) in pairs(set_values)
ts.values[vid] = value
end
return
end
function my_test_cb(ext::Dict{Symbol,Any},
phd::PH.PHData,
winf::PH.WorkerInf,
niter::Int
)::Bool
if niter == 1
vid0 = PH.VariableID(PH.ScenarioID(0), PH.StageID(1), PH.Index(0))
val1 = PH.branch_value(phd, PH.ScenarioID(1), PH.StageID(1), PH.Index(0))
values = Dict(vid0 => val1)
ext[:value] = val1
ext[:iter] = niter
PH.apply_to_subproblem(to_apply,
phd,
winf,
PH.ScenarioID(0),
(values,)
)
end
return true
end
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
create_test,
PH.ScalarPenaltyParameter(2.0),
atol=1e-8,
rtol=1e-12,
max_iter=500,
timing=false,
warm_start=false,
callbacks=[PH.Callback(my_test_cb)]
)
@test err == 0.0
@test rerr == 0.0
@test obj == 0.0
@test n == 3
cb_ext = phd.callbacks[1].ext
value = cb_ext[:value]
@test PH.branch_value(phd, PH.ScenarioID(0), PH.StageID(1), PH.Index(0)) == value
@test PH.branch_value(phd, PH.ScenarioID(1), PH.StageID(1), PH.Index(0)) == value
@test cb_ext[:iter] == 1
end
@testset "Variable Fixing Callback" begin
phd = fake_phdata(3, 4; add_leaves=false)
winf = fake_worker_info()
nscen = length(PH.scenarios(phd))
lag = 2
PH.add_callback(phd, PH.variable_fixing(lag=lag))
phd.scenario_map[PH.scid(0)].branch_vars[PH.VariableID(PH.scid(0), PH.stid(1), PH.index(1))] = -1.0
PH.compute_and_save_xhat(phd)
for niter in 1:(2*lag*nscen)
PH._execute_callbacks(phd, winf, niter)
end
cb_ext = phd.callbacks[1].ext
for (xhid, xhat) in pairs(PH.consensus_variables(phd))
if PH.name(phd, xhid) == "a1"
@test !(xhid in cb_ext[:fixed])
else
@test xhid in cb_ext[:fixed]
end
end
msg_count = 0
while isready(winf.inputs[1])
msg = take!(winf.inputs[1])
msg_count += 1
@test typeof(msg) == PH.SubproblemAction
@test string(msg.action) == "fix_variables"
s = msg.scen
value_dict = msg.args[1]
for (vid, value) in pairs(value_dict)
xhid = PH.convert_to_xhat_id(phd, vid)
xhat = phd.xhat[xhid]
@test value == PH.value(xhat)
@test xhid in cb_ext[:fixed]
end
end
@test msg_count == nscen
end
@testset "Mean Deviation Callback" begin
phd = fake_phdata(3, 4; add_leaves=false)
winf = fake_worker_info()
nscen = length(PH.scenarios(phd))
tol = 1e-8
PH.add_callback(phd, PH.mean_deviation(tol=tol, save_deviations=true))
PH.compute_and_save_xhat(phd)
user_continue = PH._execute_callbacks(phd, winf, 1)
@test user_continue == false
md_ext = PH.get_callback_ext(phd, "mean_deviation")
@test isapprox(md_ext[:deviations][1], 0.0, atol=1e-8)
@test md_ext[:tol] == tol
phd.scenario_map[PH.scid(0)].branch_vars[PH.VariableID(PH.scid(0), PH.stid(1), PH.index(1))] = 4.0
PH.compute_and_save_xhat(phd)
user_continue = PH._execute_callbacks(phd, winf, 2)
@test user_continue == true
@test isapprox(md_ext[:deviations][2], 0.6)
phd = fake_phdata(3, 4; add_leaves=false)
phd.scenario_map[PH.scid(0)].branch_vars[PH.VariableID(PH.scid(0), PH.stid(1), PH.index(1))] = 4.0
PH.add_callback(phd, PH.mean_deviation(tol=1.0, save_deviations=false))
PH.compute_and_save_xhat(phd)
user_continue = PH._execute_callbacks(phd, winf, 1)
@test user_continue == false
end
macro spcb_gen(name, num)
fn = Symbol(name * "_" * string(num))
quote
function $(esc(fn))(ext::Dict{Symbol,Any},
sp::T,
niter::Int,
scid::PH.ScenarioID
)::Bool where T <: AbstractSubproblem
return
end
end
end
@testset "Subproblem Callback Utilities" begin
@spcb_gen("spcb", 1)
@spcb_gen("spcb", 2)
@spcb_gen("spcb", 3)
my_spcbs = [spcb(spcb_1),
spcb(spcb_2, Dict{Symbol,Any}(:b=>"TESTING!")),
spcb("Third CB", spcb_3, Dict{Symbol,Any}(:c => "This is a test.",
:d => "This is only a test.")
),
]
for (k,spcb) in enumerate(my_spcbs)
io = IOBuffer()
Base.show(io, spcb)
@test String(take!(io)) == spcb.name
if k == 1
@test isempty(spcb.ext)
@test spcb.h === spcb_1
elseif k == 2
@test length(spcb.ext) == 1
@test spcb.ext[:b] == "TESTING!"
@test spcb.h === spcb_2
else
@test length(spcb.ext) == 2
@test spcb.ext[:c] == "This is a test."
@test spcb.ext[:d] == "This is only a test."
@test spcb.name == "Third CB"
@test spcb.h === spcb_3
end
end
end
@testset "Subproblem Callback" begin
function my_subproblem_callback(ext::Dict{Symbol,Any},
sp::JuMPSubproblem,
niter::Int,
scenario_id::ScenarioID
)
if niter == 1 && PH.value(scenario_id) == 0
ext[:check] += 1
sp.model.ext[:check] = 5
end
if niter == 2 && PH.value(scenario_id) == 0
ext[:sp_check] = sp.model.ext[:check]
end
if niter == 3
for vref in values(sp.vars)
if JuMP.name(vref) == "u"
JuMP.@constraint(sp.model, vref == 1.0)
elseif JuMP.name(vref) == "x"
JuMP.@constraint(sp.model, vref == 3.0)
end
end
end
return
end
ext = Dict{Symbol,Any}(:check => 0)
my_spcb = SubproblemCallback(my_subproblem_callback, ext)
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
two_stage_model,
PH.ScalarPenaltyParameter(1.0),
atol=1e-8,
rtol=1e-8,
max_iter=10,
report=0,
timing=false,
warm_start=false,
subproblem_callbacks=[my_spcb]
)
@test ext[:check] == 1
@test ext[:sp_check] == 5
@test n == 4
@test err < 1e-8
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 5257 |
r = PH.ScalarPenaltyParameter(25.0)
atol = 1e-8
rtol = 1e-12
max_iter = 500
obj_val = 178.3537498401004
var_vals = Dict([
"x[1]_{0,1,2,3}" => 7.5625,
"x[2]_{0,1,2,3}" => 0.0,
"x[3]_{0,1,2,3}" => 1.0,
"y_{0,1}" => 1.75,
"y_{2,3}" => 0.0,
"z[1]_{0}" => -0.65625,
"z[2]_{0}" => -0.65625,
"z[1]_{1}" => 2.84375,
"z[2]_{1}" => 2.84375,
"z[1]_{2}" => -1.78125,
"z[2]_{2}" => -1.78125,
"z[1]_{3}" => 4.71875,
"z[2]_{3}" => 4.71875,
])
# Setup distributed stuff
nw = 2
diff = nw - nworkers()
diff > 0 && Distributed.addprocs(nw)
@assert Distributed.nworkers() == nw
@everywhere using Pkg
@everywhere Pkg.activate(@__DIR__)
@everywhere using ProgressiveHedging
@everywhere const PH = ProgressiveHedging
@everywhere using Ipopt
@everywhere using JuMP
include("common.jl")
@testset "Error Handling" begin
ch_size = 10
worker_inf = PH._launch_workers(ch_size, ch_size)
@everywhere struct MakeWorkerError <: PH.Message end
PH._send_message(worker_inf, first(workers()), MakeWorkerError())
my_task = @async begin
PH._wait_for_shutdown(worker_inf)
end
if timeout_wait(my_task)
@test istaskfailed(my_task)
@test typeof(my_task.exception) <: RemoteException
else
error("Timed out on test")
end
my_task = @async begin
PH._wait_for_shutdown(worker_inf)
return PH._is_running(worker_inf)
end
if timeout_wait(my_task)
@test !fetch(my_task)
else
error("Timed out on test")
end
end
@testset "Solve" begin
# Solve the problem
(n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
atol=atol,
rtol=rtol,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
max_iter=max_iter,
report=0,
timing=false,
warm_start=true)
@test err < atol
@test isapprox(obj, obj_val)
@test n < max_iter
for row in eachrow(soln)
var = row[:variable] * "_{" * row[:scenarios] * "}"
@test isapprox(row[:value], var_vals[var], atol=1e-7)
end
end
@testset "User Specified Workers" begin
st = build_scen_tree()
worker_assignments = Dict(k=>Set{PH.ScenarioID}() for k in 2:3)
for s in PH.scenarios(st)
if PH.value(s) < 3
push!(worker_assignments[2], s)
else
push!(worker_assignments[3], s)
end
end
# Solve the problem
(n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r;
atol=atol,
rtol=rtol,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
max_iter=max_iter,
report=0,
worker_assignments=worker_assignments,
timing=false,
warm_start=true)
@test err < atol
@test isapprox(obj, obj_val)
@test n < max_iter
for row in eachrow(soln)
var = row[:variable] * "_{" * row[:scenarios] * "}"
@test isapprox(row[:value], var_vals[var], atol=1e-7)
end
for s in PH.scenarios(phd)
if PH.value(s) < 3
@test phd.scenario_map[s].pid == 2
else
@test phd.scenario_map[s].pid == 3
end
end
end
@testset "Lower Bound Algorithm" begin
(n, err, rerr, obj, soln, phd) = PH.solve(PH.two_stage_tree(2),
two_stage_model,
PH.ScalarPenaltyParameter(2.0),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
lower_bound=5,
timing=false,
warm_start=false
)
@test err < atol
@test isapprox(obj, 8.25, atol=1e-6)
@test n < max_iter
lb_df = PH.lower_bounds(phd)
for row in eachrow(lb_df)
@test row[:bound] <= 8.25
end
@test size(lb_df,1) == 12
@test isapprox(lb_df[size(lb_df,1), "absolute gap"], 0.0, atol=1e-7)
@test isapprox(lb_df[size(lb_df,1), "relative gap"], 0.0, atol=(1e-7/8.25))
end
# Tear down distrbuted stuff
Distributed.rmprocs(Distributed.workers())
@assert Distributed.nprocs() == 1
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 6627 |
@testset "Penalty Parameter Interface" begin
struct Fake <: PH.AbstractPenaltyParameter end
fake = Fake()
xhid = PH.XhatID(PH.NodeID(0), PH.Index(0))
phd = fake_phdata(3, 4; add_leaves=false)
@test_throws PH.UnimplementedError PH.get_penalty_value(fake)
@test_throws PH.UnimplementedError PH.get_penalty_value(fake, xhid)
@test_throws PH.UnimplementedError PH.is_initial_value_dependent(Fake)
@test_throws PH.UnimplementedError PH.is_subproblem_dependent(Fake)
@test_throws PH.UnimplementedError PH.is_variable_dependent(Fake)
@test_throws PH.UnimplementedError PH.penalty_map(fake)
@test_throws PH.UnimplementedError PH.process_penalty_initial_value(fake, phd)
@test_throws PH.UnimplementedError PH.process_penalty_subproblem(fake,
phd,
PH.scid(0),
Dict{PH.VariableID,
Float64}()
)
end
@testset "Scalar Penalty" begin
@test PH.is_initial_value_dependent(PH.ScalarPenaltyParameter) == false
@test PH.is_subproblem_dependent(PH.ScalarPenaltyParameter) == false
@test PH.is_variable_dependent(PH.ScalarPenaltyParameter) == false
rflt = 10.0*rand()
r = PH.ScalarPenaltyParameter(rflt)
@test PH.get_penalty_value(r) == rflt
@test PH.get_penalty_value(r, PH.XhatID(PH.NodeID(0), PH.Index(0))) == rflt
end
@testset "Proportional Penalty" begin
@test PH.is_initial_value_dependent(PH.ProportionalPenaltyParameter) == false
@test PH.is_subproblem_dependent(PH.ProportionalPenaltyParameter) == true
@test PH.is_variable_dependent(PH.ProportionalPenaltyParameter) == true
N = 2
st = PH.two_stage_tree(N)
var_map = Dict{PH.ScenarioID,Dict{PH.VariableID,PH.VariableInfo}}()
coef_map = Dict{Int,Dict{PH.VariableID,Float64}}()
for s in 0:(N-1)
js = two_stage_model(PH.scid(s))
svm = PH.report_variable_info(js, st)
var_map[PH.scid(s)] = svm
(br_vars, lf_vars) = PH._split_variables(st, collect(keys(svm)))
coef_map[s] = PH.report_penalty_info(js,
br_vars,
PH.ProportionalPenaltyParameter
)
end
c_rho = 10.0 * (rand() + 1e-12) # Avoid the possibility of c_rho == 0.0
phd = PH.PHData(PH.ProportionalPenaltyParameter(c_rho),
st,
Dict(1 => Set([PH.scid(0), PH.scid(1)])),
var_map,
TimerOutputs.TimerOutput()
)
for s in 0:(N-1)
PH.process_penalty_subproblem(phd.r, phd, PH.scid(s), coef_map[s])
end
for (xhid, rho) in pairs(phd.r.penalties)
@test st.tree_map[xhid.node].stage == PH.stid(1)
@test isapprox(rho, c_rho) || isapprox(rho, phd.r.constant)
end
end
@testset "SEP Penalty" begin
@test PH.is_initial_value_dependent(PH.SEPPenaltyParameter) == true
@test PH.is_subproblem_dependent(PH.SEPPenaltyParameter) == true
@test PH.is_variable_dependent(PH.SEPPenaltyParameter) == true
N = 2
st = PH.two_stage_tree(N)
var_map = Dict{PH.ScenarioID,Dict{PH.VariableID,PH.VariableInfo}}()
var_vals = Dict{Int,Dict{PH.VariableID,Float64}}()
coef_map = Dict{Int,Dict{PH.VariableID,Float64}}()
for s in 0:(N-1)
js = two_stage_model(PH.scid(s))
svm = PH.report_variable_info(js, st)
var_map[PH.scid(s)] = svm
(br_vars, lf_vars) = PH._split_variables(st, collect(keys(svm)))
PH.solve_subproblem(js)
var_vals[s] = PH.report_values(js, collect(keys(svm)))
coef_map[s] = PH.report_penalty_info(js,
br_vars,
PH.SEPPenaltyParameter
)
end
phd = PH.PHData(PH.SEPPenaltyParameter(),
st,
Dict(1 => Set([PH.scid(0), PH.scid(1)])),
var_map,
TimerOutputs.TimerOutput()
)
for s in 0:(N-1)
PH._copy_values(phd.scenario_map[PH.scid(s)].branch_vars, var_vals[s])
PH.process_penalty_subproblem(phd.r, phd, PH.scid(s), coef_map[s])
end
PH.compute_and_save_xhat(phd)
PH.process_penalty_initial_value(phd.r, phd)
value = 0.5 * (10.0 + 3.0)
value = 0.5 * (10.0 - value) + 0.5 * (value - 3.0)
rho_val = 1.0 / value
for (xhid, rho) in pairs(phd.r.penalties)
@test st.tree_map[xhid.node].stage == PH.stid(1)
@test isapprox(rho, rho_val) || isapprox(rho, phd.r.default)
end
if isdefined(Main, :Xpress)
N = 8
st = PH.two_stage_tree(N)
var_map = Dict{PH.ScenarioID,Dict{PH.VariableID,PH.VariableInfo}}()
var_vals = Dict{Int,Dict{PH.VariableID,Float64}}()
coef_map = Dict{Int,Dict{PH.VariableID,Float64}}()
for s in 0:(N-1)
js = two_stage_int(PH.scid(s))
svm = PH.report_variable_info(js, st)
var_map[PH.scid(s)] = svm
(br_vars, lf_vars) = PH._split_variables(st, collect(keys(svm)))
PH.solve_subproblem(js)
var_vals[s] = PH.report_values(js, collect(keys(svm)))
coef_map[s] = PH.report_penalty_info(js,
br_vars,
PH.SEPPenaltyParameter
)
end
phd = PH.PHData(PH.SEPPenaltyParameter(),
st,
Dict(1 => Set([PH.scid(s) for s in 0:(N-1)])),
var_map,
TimerOutputs.TimerOutput()
)
for s in 0:(N-1)
PH._copy_values(phd.scenario_map[PH.scid(s)].branch_vars, var_vals[s])
PH.process_penalty_subproblem(phd.r, phd, PH.scid(s), coef_map[s])
end
PH.compute_and_save_xhat(phd)
PH.process_penalty_initial_value(phd.r, phd)
value = (10 - 4 + 1)
rho_val = 2.0 / value
for (xhid, rho) in pairs(phd.r.penalties)
@test st.tree_map[xhid.node].stage == PH.stid(1)
@test isapprox(rho, rho_val)
end
else
println("Skipping SEP integer setting tests.")
end
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 7223 |
atol = 1e-8
rtol = 1e-16
max_iter = 500
r = PH.ScalarPenaltyParameter(25.0)
@testset "Residuals" begin
(n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
save_residuals=1,
timing=false,
warm_start=false)
res_df = residuals(phd)
@test size(res_df,1) == n + 1
rid = n + 1
@test res_df[rid, :iteration] == n
@test res_df[rid, :absolute] == err
@test res_df[rid, :relative] == rerr
end
@testset "Iterates" begin
(n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=0,
save_iterates=1,
timing=false,
warm_start=false)
rid = n + 1
xhat_df = retrieve_xhat_history(phd)
@test size(xhat_df,1) == n + 1
@test xhat_df[rid, :iteration] == n
for (k,var) in enumerate(soln[:,:variable])
if soln[k,:stage] < 3
vname = var * "_" * soln[k,:scenarios]
@test xhat_df[rid, vname] == soln[k, :value]
end
end
x_hist_df = retrieve_no_hat_history(phd)
x_df = retrieve_no_hats(phd)
@test size(x_hist_df,1) == n + 1
@test x_hist_df[rid, :iteration] == n
for (k,var) in enumerate(x_df[:,:variable])
if x_df[k,:stage] < 3
vname = var * "_" * string(x_df[k,:scenario])
@test x_hist_df[rid, vname] == x_df[k,:value]
end
end
w_hist_df = retrieve_w_history(phd)
w_df = retrieve_w(phd)
@test size(w_hist_df,1) == n + 1
@test w_hist_df[rid, :iteration] == n
for (k,var) in enumerate(w_df[:,:variable])
vname = var * "_" * string(w_df[k,:scenario])
@test w_hist_df[rid, vname] == w_df[k,:value]
end
end
@testset "Reporting" begin
global n, err, rerr, obj, soln, phd
reports = @capture_out((n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,
tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=1,
lower_bound=1,
save_residuals=1,
timing=false,
warm_start=false)
)
report_rex = r"Iter:\s*(\d+)\s*AbsR:\s*(\d\.\d+e[+-]\d+)\s*RelR:\s*(\d\.\d+e[+-]\d+)\s*Xhat:\s*(\d\.\d+e[+-]\d+)\s*X:\s*(\d\.\d+e[+-]\d+)"
bound_rex = r"Iter:\s*(\d+)\s*Bound:\s*(-?\d\.\d+e[+-]\d+)\s*Abs Gap:\s*(\d\.\d+e[+-]\d+)\s*Rel Gap:\s*((\d)+\.\d+(e[+-]\d+)?)"
res_df = residuals(phd)
lb_df = lower_bounds(phd)
N = 5 # number of consensus variables
nreps = 0
nbds = 0
for line in split(reports,"\n")
if occursin(report_rex, line)
nreps += 1
if nreps == Int(floor(n/2))
m = match(report_rex, line)
iter = parse(Int, m.captures[1])
abs = parse(Float64, m.captures[2])
@test isapprox(res_df[iter + 1, :absolute], abs, rtol=1e-6)
rel = parse(Float64, m.captures[3])
@test isapprox(res_df[iter + 1, :relative], rel, rtol=1e-6)
xhat = parse(Float64, m.captures[4])
@test isapprox(res_df[iter + 1, :xhat_sq], xhat^2 * N, rtol=1e-6)
x = parse(Float64, m.captures[5])
@test isapprox(res_df[iter + 1, :x_sq], x^2 * N, rtol=1e-6)
end
elseif occursin(bound_rex, line)
nbds += 1
if nbds == Int(floor(n/2))
m = match(bound_rex, line)
iter = parse(Int, m.captures[1])
bound = parse(Float64, m.captures[2])
@test isapprox(lb_df[iter + 1, "bound"], bound, rtol=1e-3)
abs = parse(Float64, m.captures[3])
@test isapprox(lb_df[iter + 1, "absolute gap"], abs, rtol=1e-3)
rel = parse(Float64, m.captures[4])
@test isapprox(lb_df[iter + 1, "relative gap"], rel, rtol=1e-3)
end
end
end
@test nreps == n + 1
@test nbds == n + 1
end
@testset "Timing" begin
global n, err, rerr, obj, soln, phd
reports = @capture_out((n, err, rerr, obj, soln, phd) = PH.solve(build_scen_tree(),
create_model,
r,
opt=Ipopt.Optimizer,
opt_args=(print_level=0,
tol=1e-12),
atol=atol,
rtol=rtol,
max_iter=max_iter,
report=1,
save_residuals=1,
timing=false,
warm_start=false)
)
@test length(reports) > 1
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 1204 |
@testset "Invalid Scenario Tree Checks" begin
st = PH.ScenarioTree()
PH.add_node(st, root(st))
PH.add_node(st, root(st))
@test_throws(ErrorException,
PH.solve_extensive(st, two_stage_model, ()->Ipopt.Optimizer()),
)
@test_throws(ErrorException,
PH.solve(st, two_stage_model, PH.ScalarPenaltyParameter(2.0))
)
end
@testset "Probability Checks" begin
st = PH.ScenarioTree()
PH.add_leaf(st, root(st), 0.25)
PH.add_leaf(st, root(st), 0.5)
@test_throws(ErrorException,
PH.solve_extensive(st, two_stage_model, ()->Ipopt.Optimizer())
)
@test_throws(ErrorException,
PH.solve(st, two_stage_model, PH.ScalarPenaltyParameter(2.0))
)
st = PH.ScenarioTree()
PH.add_leaf(st, root(st), 0.25)
PH.add_leaf(st, root(st), 0.5)
PH.add_leaf(st, root(st), 0.5)
@test_throws(ErrorException,
PH.solve_extensive(st, two_stage_model, ()->Ipopt.Optimizer())
)
@test_throws(ErrorException,
PH.solve(st, two_stage_model, PH.ScalarPenaltyParameter(2.0))
)
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 20618 |
@testset "Initialization" begin
@testset "Split Variables" begin
st = build_scen_tree()
js = create_model(PH.scid(0))
vid_name_map = PH.report_variable_info(js, st)
(branch_ids, leaf_ids) = PH._split_variables(st, collect(keys(vid_name_map)))
for br_vid in branch_ids
vname = vid_name_map[br_vid].name
@test (vname == "y") || occursin("x", vname)
if vname == "y"
@test br_vid.stage == PH.stid(2)
else
@test br_vid.stage == PH.stid(1)
end
end
for lf_vid in leaf_ids
vname = vid_name_map[lf_vid].name
@test occursin("z", vname)
@test lf_vid.stage == PH.stid(3)
end
end
@testset "Build Subproblems" begin
st = build_scen_tree()
wr = PH.WorkerRecord(myid())
rc = RemoteChannel(()->Channel(2*length(PH.scenarios(st))), myid())
PH._build_subproblems(rc, wr, PH.scenarios(st), st,
create_model, (), NamedTuple(), SubproblemCallback[]
)
for (scid, sub) in pairs(wr.subproblems)
@test length(JuMP.all_variables(sub.problem.model)) == 6
ncons = 0
for (ftype,stype) in JuMP.list_of_constraint_types(sub.problem.model)
ncons += JuMP.num_constraints(sub.problem.model, ftype, stype)
end
@test ncons == 7
end
count = 0
my_var_map = Dict{PH.VariableID,PH.VariableInfo}()
while isready(rc)
count += 1
msg = take!(rc)
@test typeof(msg) <: PH.VariableMap
merge!(my_var_map, msg.var_info)
for (vid,vinfo) in pairs(msg.var_info)
@test vid.scenario == msg.scen
end
end
@test length(my_var_map) == 24
end
@testset "Initialize Subproblems (Scalar)" begin
st = build_scen_tree()
sp_map = Dict(1 => Set([PH.ScenarioID(0), PH.ScenarioID(1), PH.ScenarioID(2)]),
2 => Set([PH.ScenarioID(3)])
)
worker_input_queues = Dict(1 => RemoteChannel(()->Channel{PH.Message}(10), myid()),
2 => RemoteChannel(()->Channel{PH.Message}(10), myid())
)
worker_output_queue = RemoteChannel(()->Channel{PH.Message}(10), myid())
futures = Dict(1 => remotecall(PH.worker_loop,
myid(),
1,
worker_input_queues[1],
worker_output_queue),
2 => remotecall(PH.worker_loop,
myid(),
2,
worker_input_queues[2],
worker_output_queue),
)
wi = PH.WorkerInf(worker_input_queues, worker_output_queue, futures)
my_task = @async begin
PH._initialize_subproblems(sp_map,
wi,
st,
create_model,
(),
PH.ScalarPenaltyParameter(1.0),
false,
SubproblemCallback[])
end
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
var_map = fetch(my_task)
for scen in PH.scenarios(st)
for (vid, vinfo) in var_map[scen]
vname = vinfo.name
@test vid.scenario == scen
if vid.stage == PH.stid(1)
@test occursin("x", vname)
elseif vid.stage == PH.stid(2)
@test vname == "y"
elseif vid.stage == PH.stid(3)
@test occursin("z", vname)
else
stage_int = PH.value(vid.stage)
error("Stage $(stage_int)! There is no stage $(stage_int)!!")
end
end
end
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timed out")
end
phd = PH.PHData(PH.ScalarPenaltyParameter(1.0),
st,
sp_map,
var_map,
TimerOutputs.TimerOutput()
)
for (xhid, xhat) in pairs(phd.xhat)
vname = phd.variable_data[first(xhat.vars)].name
for vid in xhat.vars
@test xhid == phd.variable_data[vid].xhat_id
@test vname == phd.variable_data[vid].name
end
end
for (scen, sinfo) in phd.scenario_map
for vid in keys(sinfo.branch_vars)
if occursin("x", phd.variable_data[vid].name)
@test vid.stage == PH.stid(1)
else
@test vid.stage == PH.stid(2)
end
end
for vid in keys(sinfo.leaf_vars)
@test vid.stage == PH.stid(3)
end
end
my_task = @async begin
count = 0
messages = Vector{PH.Message}()
while count < length(PH.scenarios(st))
msg = PH._retrieve_message_type(wi, PH.ReportBranch)
push!(messages, msg)
count += 1
end
return messages
end
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
msgs = fetch(my_task)
@test length(msgs) == length(PH.scenarios(st))
msg_from_scen = Set{PH.ScenarioID}()
for msg in msgs
scen = msg.scen
push!(msg_from_scen, scen)
sinfo = phd.scenario_map[scen]
@test keys(sinfo.branch_vars) == keys(msg.vals)
@test (msg.sts == MOI.OPTIMAL ||
msg.sts == MOI.LOCALLY_SOLVED ||
msg.sts == MOI.ALMOST_LOCALLY_SOLVED
)
put!(wi.output, msg)
end
@test msg_from_scen == PH.scenarios(st)
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timed out")
end
my_task = @async PH._set_initial_values(phd, wi)
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
@test fetch(my_task) >= 0.0
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timedout")
end
my_task = @async PH._set_penalty_parameter(phd, wi)
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
@test fetch(my_task) >= 0.0
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timedout")
end
PH._shutdown(wi)
PH._wait_for_shutdown(wi)
end
@testset "Initialize Subproblems (Proportional)" begin
st = build_scen_tree()
sp_map = Dict(1 => Set([PH.ScenarioID(0), PH.ScenarioID(1), PH.ScenarioID(2)]),
2 => Set([PH.ScenarioID(3)])
)
worker_input_queues = Dict(1 => RemoteChannel(()->Channel{PH.Message}(10), myid()),
2 => RemoteChannel(()->Channel{PH.Message}(10), myid())
)
worker_output_queue = RemoteChannel(()->Channel{PH.Message}(10), myid())
futures = Dict(1 => remotecall(PH.worker_loop,
myid(),
1,
worker_input_queues[1],
worker_output_queue),
2 => remotecall(PH.worker_loop,
myid(),
2,
worker_input_queues[2],
worker_output_queue),
)
wi = PH.WorkerInf(worker_input_queues, worker_output_queue, futures)
my_task = @async begin
PH._initialize_subproblems(sp_map,
wi,
st,
create_model,
(),
PH.ProportionalPenaltyParameter(1.0),
false,
SubproblemCallback[])
end
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
var_map = fetch(my_task)
for scen in PH.scenarios(st)
for (vid, vinfo) in var_map[scen]
vname = vinfo.name
@test vid.scenario == scen
if vid.stage == PH.stid(1)
@test occursin("x", vname)
elseif vid.stage == PH.stid(2)
@test vname == "y"
elseif vid.stage == PH.stid(3)
@test occursin("z", vname)
else
stage_int = PH.value(vid.stage)
error("Stage $(stage_int)! There is no stage $(stage_int)!!")
end
end
end
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timed out")
end
phd = PH.PHData(PH.ProportionalPenaltyParameter(1.0),
st,
sp_map,
var_map,
TimerOutputs.TimerOutput()
)
for (xhid, xhat) in pairs(phd.xhat)
vname = phd.variable_data[first(xhat.vars)].name
for vid in xhat.vars
@test xhid == phd.variable_data[vid].xhat_id
@test vname == phd.variable_data[vid].name
end
end
for (scen, sinfo) in phd.scenario_map
for vid in keys(sinfo.branch_vars)
if occursin("x", phd.variable_data[vid].name)
@test vid.stage == PH.stid(1)
else
@test vid.stage == PH.stid(2)
end
end
for vid in keys(sinfo.leaf_vars)
@test vid.stage == PH.stid(3)
end
end
my_task = @async begin
messages = Vector{PH.Message}()
count = 0
while count < 2*length(PH.scenarios(st))
msg = PH._retrieve_message_type(wi, Union{PH.ReportBranch,PH.PenaltyInfo})
push!(messages, msg)
count += 1
end
return messages
end
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
msgs = fetch(my_task)
@test length(msgs) == 2 * length(PH.scenarios(st))
iv_msg_from_scen = Set{PH.ScenarioID}()
pp_msg_from_scen = Set{PH.ScenarioID}()
for msg in msgs
scen = msg.scen
sinfo = phd.scenario_map[scen]
if typeof(msg) <: PH.ReportBranch
push!(iv_msg_from_scen, scen)
@test (msg.sts == MOI.OPTIMAL ||
msg.sts == MOI.LOCALLY_SOLVED ||
msg.sts == MOI.ALMOST_LOCALLY_SOLVED
)
@test keys(sinfo.branch_vars) == keys(msg.vals)
elseif typeof(msg) <: PH.PenaltyInfo
push!(pp_msg_from_scen, scen)
@test keys(sinfo.branch_vars) == keys(msg.penalty)
else
error("Unexpected message of type $(typeof(msg))")
end
put!(wi.output, msg)
end
@test iv_msg_from_scen == PH.scenarios(st)
@test pp_msg_from_scen == PH.scenarios(st)
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timed out")
end
my_task = @async PH._set_initial_values(phd, wi)
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
@test fetch(my_task) >= 0.0
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timedout")
end
my_task = @async PH._set_penalty_parameter(phd, wi)
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
@test fetch(my_task) >= 0.0
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timedout")
end
PH._shutdown(wi)
PH._wait_for_shutdown(wi)
end
@testset "Initialize Subproblems (SEP)" begin
st = build_scen_tree()
sp_map = Dict(1 => Set([PH.ScenarioID(0), PH.ScenarioID(1), PH.ScenarioID(2)]),
2 => Set([PH.ScenarioID(3)])
)
worker_input_queues = Dict(1 => RemoteChannel(()->Channel{PH.Message}(10), myid()),
2 => RemoteChannel(()->Channel{PH.Message}(10), myid())
)
worker_output_queue = RemoteChannel(()->Channel{PH.Message}(10), myid())
futures = Dict(1 => remotecall(PH.worker_loop,
myid(),
1,
worker_input_queues[1],
worker_output_queue),
2 => remotecall(PH.worker_loop,
myid(),
2,
worker_input_queues[2],
worker_output_queue),
)
wi = PH.WorkerInf(worker_input_queues, worker_output_queue, futures)
my_task = @async begin
PH._initialize_subproblems(sp_map,
wi,
st,
create_model,
(),
PH.SEPPenaltyParameter(),
false,
SubproblemCallback[])
end
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
var_map = fetch(my_task)
for scen in PH.scenarios(st)
for (vid, vinfo) in var_map[scen]
vname = vinfo.name
@test vid.scenario == scen
if vid.stage == PH.stid(1)
@test occursin("x", vname)
elseif vid.stage == PH.stid(2)
@test vname == "y"
elseif vid.stage == PH.stid(3)
@test occursin("z", vname)
else
stage_int = PH.value(vid.stage)
error("Stage $(stage_int)! There is no stage $(stage_int)!!")
end
end
end
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timed out")
end
phd = PH.PHData(PH.SEPPenaltyParameter(),
st,
sp_map,
var_map,
TimerOutputs.TimerOutput()
)
for (xhid, xhat) in pairs(phd.xhat)
vname = phd.variable_data[first(xhat.vars)].name
for vid in xhat.vars
@test xhid == phd.variable_data[vid].xhat_id
@test vname == phd.variable_data[vid].name
end
end
for (scen, sinfo) in phd.scenario_map
for vid in keys(sinfo.branch_vars)
if occursin("x", phd.variable_data[vid].name)
@test vid.stage == PH.stid(1)
else
@test vid.stage == PH.stid(2)
end
end
for vid in keys(sinfo.leaf_vars)
@test vid.stage == PH.stid(3)
end
end
my_task = @async begin
messages = Vector{PH.Message}()
count = 0
while count < 2*length(PH.scenarios(st))
msg = PH._retrieve_message_type(wi, Union{PH.ReportBranch,PH.PenaltyInfo})
push!(messages, msg)
count += 1
end
return messages
end
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
msgs = fetch(my_task)
@test length(msgs) == 2 * length(PH.scenarios(st))
iv_msg_from_scen = Set{PH.ScenarioID}()
pp_msg_from_scen = Set{PH.ScenarioID}()
for msg in msgs
scen = msg.scen
sinfo = phd.scenario_map[scen]
if typeof(msg) <: PH.ReportBranch
push!(iv_msg_from_scen, scen)
@test (msg.sts == MOI.OPTIMAL ||
msg.sts == MOI.LOCALLY_SOLVED ||
msg.sts == MOI.ALMOST_LOCALLY_SOLVED
)
@test keys(sinfo.branch_vars) == keys(msg.vals)
elseif typeof(msg) <: PH.PenaltyInfo
push!(pp_msg_from_scen, scen)
@test keys(sinfo.branch_vars) == keys(msg.penalty)
else
error("Unexpected message of type $(typeof(msg))")
end
put!(wi.output, msg)
end
@test iv_msg_from_scen == PH.scenarios(st)
@test pp_msg_from_scen == PH.scenarios(st)
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timed out")
end
my_task = @async PH._set_initial_values(phd, wi)
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
@test fetch(my_task) >= 0.0
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timedout")
end
my_task = @async PH._set_penalty_parameter(phd, wi)
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
@test fetch(my_task) >= 0.0
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timedout")
end
PH._shutdown(wi)
PH._wait_for_shutdown(wi)
end
@testset "Lower Bound Initialization" begin
st = build_scen_tree()
sp_map = PH.assign_scenarios_to_procs(st)
worker_input_queues = Dict(1 => RemoteChannel(()->Channel{PH.Message}(10), myid()))
worker_output_queue = RemoteChannel(()->Channel{PH.Message}(10), myid())
futures = Dict(1 => remotecall(PH.worker_loop,
myid(),
1,
worker_input_queues[1],
worker_output_queue)
)
wi = PH.WorkerInf(worker_input_queues, worker_output_queue, futures)
PH._initialize_lb_subproblems(sp_map, wi, st, create_model, (), false)
PH._send_message(wi, 1, PH.DumpState())
my_task = @async PH._retrieve_message(wi)
if timeout_wait(my_task, 90) && !istaskfailed(my_task)
msg = fetch(my_task)
elseif istaskfailed(my_task)
throw(my_task.exception)
else
error("Test timedout")
end
@test typeof(msg) <: PH.WorkerState{PH.WorkerRecord}
@test length(msg.state.lb_subproblems) == length(scenarios(st))
for (scen,sub) in pairs(msg.state.lb_subproblems)
@test scen in [PH.scid(0), PH.scid(1), PH.scid(2), PH.scid(3)]
@test length(sub.branch_vars) == 4
@test length(sub.leaf_vars) == 2
end
PH._shutdown(wi)
PH._wait_for_shutdown(wi)
end
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 10098 | @testset "Unimplemented Error" begin
# TODO: This is a pain to debug if it fails. Try to fix it.
struct InterfaceFunction
f::Function
args::Tuple
end
function IF(f::Function, args...)
return InterfaceFunction(f, args)
end
struct Unimplemented <: PH.AbstractSubproblem
end
to_test = [
IF(PH.add_ph_objective_terms, Vector{PH.VariableID}(), 2.25),
IF(PH.objective_value),
IF(PH.report_values, Vector{PH.VariableID}()),
IF(PH.report_variable_info, build_scen_tree()),
IF(PH.solve_subproblem),
IF(PH.update_ph_terms, Dict{PH.VariableID,Float64}(), Dict{PH.VariableID,Float64}()),
IF(PH.warm_start),
IF(PH.report_penalty_info, PH.ProportionalPenaltyParameter),
IF(PH.add_lagrange_terms, Vector{VariableID}()),
IF(PH.update_lagrange_terms, Dict{VariableID,Float64}()),
]
subprob = Unimplemented()
for interface_function in to_test
@test_throws PH.UnimplementedError begin
interface_function.f(subprob, interface_function.args...)
end
end
@test_throws PH.UnimplementedError begin
PH.ef_copy_model(JuMP.Model(),
subprob,
PH.scid(0),
build_scen_tree(),
Dict{PH.NodeID,Any}()
)
end
@test_throws PH.UnimplementedError begin
PH.ef_node_dict_constructor(typeof(subprob))
end
end
@testset "Scenario Subproblem Functions" begin
st = build_scen_tree()
js = create_model(PH.scid(0))
org_obj_func = JuMP.objective_function(js.model, JuMP.QuadExpr)
vid_name_map = PH.report_variable_info(js, st)
@test length(vid_name_map) == length(JuMP.all_variables(js.model))
for (vid, vinfo) in pairs(vid_name_map)
if vid.stage == PH.stid(1)
@test occursin("x", vinfo.name)
elseif vid.stage == PH.stid(2)
@test vinfo.name == "y"
else
@test occursin("z", vinfo.name)
end
end
ref_map = invert_map(js.vars)
observed_vids = Set{PH.VariableID}()
for var in JuMP.all_variables(js.model)
vid = ref_map[var]
@test !(vid in observed_vids)
push!(observed_vids, vid)
end
@test length(observed_vids) == length(JuMP.all_variables(js.model))
(br_vids, lf_vids) = PH._split_variables(st, collect(keys(vid_name_map)))
sts = PH.solve_subproblem(js)
@test sts == MOI.LOCALLY_SOLVED
@test sts == JuMP.termination_status(js.model)
@test PH.objective_value(js) == JuMP.objective_value(js.model)
org_obj_val = PH.objective_value(js)
vals = PH.report_values(js, collect(keys(vid_name_map)))
@test length(vals) == length(JuMP.all_variables(js.model))
for var in JuMP.all_variables(js.model)
@test JuMP.value(var) == vals[ref_map[var]]
end
r = PH.ScalarPenaltyParameter(10.0)
rhalf = 0.5 * 10.0
PH.add_ph_objective_terms(js, br_vids, r.value)
ph_obj_func = JuMP.objective_function(js.model, JuMP.QuadExpr)
diff = ph_obj_func - org_obj_func
JuMP.drop_zeros!(diff)
@test length(JuMP.linear_terms(diff)) == 0
@test length(JuMP.quad_terms(diff)) == (4 * length(br_vids))
for qt in JuMP.quad_terms(diff)
coef = qt[1]
@test (isapprox(coef, rhalf) || isapprox(coef, -r.value) || isapprox(coef, 1.0))
end
w_vals = Dict{PH.VariableID,Float64}()
for (k,w) in enumerate(keys(js.w_vars))
w_vals[w] = k * rand()
end
xhat_vals = Dict{PH.VariableID,Float64}()
for (k,xhat) in enumerate(keys(js.xhat_vars))
xhat_vals[xhat] = k * rand()
end
PH.update_ph_terms(js, w_vals, xhat_vals)
PH.warm_start(js)
sts = PH.solve_subproblem(js)
@test sts == MOI.LOCALLY_SOLVED
@test org_obj_val != PH.objective_value(js)
for (wid, wref) in pairs(js.w_vars)
@test JuMP.value(wref) == w_vals[wid]
end
for (xhid, xhref) in pairs(js.xhat_vars)
@test JuMP.value(xhref) == xhat_vals[xhid]
end
end
# @testset "Extensive Form" begin
# #TODO: Make tests for this case
# end
@testset "Penalties" begin
st = build_scen_tree()
# Scalar Penalty
js = create_model(PH.scid(0))
vid_name_map = PH.report_variable_info(js, st)
(br_vids, lf_vids) = PH._split_variables(st, collect(keys(vid_name_map)))
obj = JuMP.objective_function(js.model)
PH.add_ph_objective_terms(js, br_vids, 10.0)
ph_obj_func = JuMP.objective_function(js.model, JuMP.QuadExpr)
diff = ph_obj_func - obj
JuMP.drop_zeros!(diff)
@test length(JuMP.linear_terms(diff)) == 0
@test length(JuMP.quad_terms(diff)) == (4 * length(br_vids))
for vid in br_vids
x_ref = js.vars[vid]
w_ref = js.w_vars[vid]
xhat_ref = js.xhat_vars[vid]
for (c, v1, v2) in JuMP.quad_terms(diff)
if (x_ref == v1 && x_ref == v2) || (xhat_ref == v1 && xhat_ref == v2)
@test isapprox(c, 5.0)
elseif (x_ref == v1 && xhat_ref == v2) || (xhat_ref == v1 && x_ref == v2)
@test isapprox(c, -10.0)
elseif (x_ref == v1 && w_ref == v2) || (w_ref == v1 && x_ref == v2)
@test isapprox(c, 1.0)
end
end
end
# Proportional Penalty
js = create_model(PH.scid(0))
vid_name_map = PH.report_variable_info(js, st)
(br_vids, lf_vids) = PH._split_variables(st, collect(keys(vid_name_map)))
coef_dict = PH.report_penalty_info(js, br_vids, PH.ProportionalPenaltyParameter)
obj = JuMP.objective_function(js.model)
for (vid, coef) in pairs(coef_dict)
ref = js.vars[vid]
for lt in JuMP.linear_terms(obj)
if lt[2] == ref
@test lt[1] == coef
break
end
end
coef_dict[vid] = 10.0 * coef
end
PH.add_ph_objective_terms(js, br_vids, coef_dict)
ph_obj_func = JuMP.objective_function(js.model, JuMP.QuadExpr)
diff = ph_obj_func - obj
JuMP.drop_zeros!(diff)
@test length(JuMP.linear_terms(diff)) == 0
@test length(JuMP.quad_terms(diff)) == (4 * length(br_vids))
for vid in br_vids
x_ref = js.vars[vid]
w_ref = js.w_vars[vid]
xhat_ref = js.xhat_vars[vid]
for (c, v1, v2) in JuMP.quad_terms(diff)
if (x_ref == v1 && x_ref == v2) || (xhat_ref == v1 && xhat_ref == v2)
@test isapprox(c, 0.5 * coef_dict[vid])
elseif (x_ref == v1 && xhat_ref == v2) || (xhat_ref == v1 && x_ref == v2)
@test isapprox(c, -1.0 * coef_dict[vid])
elseif (x_ref == v1 && w_ref == v2) || (w_ref == v1 && x_ref == v2)
@test isapprox(c, 1.0)
end
end
end
# SEP Penalty
js = create_model(PH.scid(0))
vid_name_map = PH.report_variable_info(js, st)
(br_vids, lf_vids) = PH._split_variables(st, collect(keys(vid_name_map)))
coef_dict = PH.report_penalty_info(js, br_vids, PH.SEPPenaltyParameter)
obj = JuMP.objective_function(js.model)
for (vid, coef) in pairs(coef_dict)
ref = js.vars[vid]
for lt in JuMP.linear_terms(obj)
if lt[2] == ref
@test lt[1] == coef
break
end
end
coef_dict[vid] = rand() * coef
end
PH.add_ph_objective_terms(js, br_vids, coef_dict)
ph_obj_func = JuMP.objective_function(js.model, JuMP.QuadExpr)
diff = ph_obj_func - obj
JuMP.drop_zeros!(diff)
@test length(JuMP.linear_terms(diff)) == 0
@test length(JuMP.quad_terms(diff)) == (4 * length(br_vids))
for vid in br_vids
x_ref = js.vars[vid]
w_ref = js.w_vars[vid]
xhat_ref = js.xhat_vars[vid]
for (c, v1, v2) in JuMP.quad_terms(diff)
if (x_ref == v1 && x_ref == v2) || (xhat_ref == v1 && xhat_ref == v2)
@test isapprox(c, 0.5 * coef_dict[vid])
elseif (x_ref == v1 && xhat_ref == v2) || (xhat_ref == v1 && x_ref == v2)
@test isapprox(c, -1.0 * coef_dict[vid])
elseif (x_ref == v1 && w_ref == v2) || (w_ref == v1 && x_ref == v2)
@test isapprox(c, 1.0)
end
end
end
end
@testset "Fix Variables" begin
js = create_model(PH.scid(0))
PH.report_variable_info(js, build_scen_tree())
is_fixed = Dict{PH.VariableID,Float64}()
is_free = Vector{PH.VariableID}()
for vid in keys(js.vars)
if PH.value(PH.index(vid)) % 2 == 0 # r > 0.5
is_fixed[vid] = rand()
else
push!(is_free, vid)
end
end
PH.fix_variables(js, is_fixed)
sts = PH.solve_subproblem(js)
@test sts == MOI.LOCALLY_SOLVED
for (vid,var) in pairs(js.vars)
if haskey(is_fixed, vid)
@test JuMP.is_fixed(var)
@test JuMP.value(var) == is_fixed[vid]
elseif vid in is_free
@test !JuMP.is_fixed(var)
else
error("Vid $vid is neither fixed nor free")
end
end
end
@testset "Lagrange Terms" begin
st = build_scen_tree()
js = create_model(PH.scid(0))
org_obj_func = JuMP.objective_function(js.model, JuMP.QuadExpr)
vid_name_map = PH.report_variable_info(js, st)
(br_vids, lf_vids) = PH._split_variables(st, collect(keys(vid_name_map)))
PH.add_lagrange_terms(js, br_vids)
ph_obj_func = JuMP.objective_function(js.model, JuMP.QuadExpr)
diff = ph_obj_func - org_obj_func
JuMP.drop_zeros!(diff)
@test length(JuMP.linear_terms(diff)) == 0
@test length(JuMP.quad_terms(diff)) == length(br_vids)
for qt in JuMP.quad_terms(diff)
coef = qt[1]
@test isapprox(coef, 1.0)
end
w_vals = Dict{PH.VariableID,Float64}()
for (k,w) in enumerate(keys(js.w_vars))
w_vals[w] = k * rand()
end
PH.update_lagrange_terms(js, w_vals)
sts = PH.solve_subproblem(js)
@test sts == MOI.LOCALLY_SOLVED
for (wid, wref) in pairs(js.w_vars)
@test JuMP.value(wref) == w_vals[wid]
end
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 2126 |
@testset "Scenario Tree Errors" begin
st = PH.ScenarioTree()
@test_throws(ErrorException, PH.add_leaf(st, PH.root(st), -1.0))
end
@testset "Scenario Tree Functions" begin
# First stage -- Creates root/first stage node automatically
st = PH.ScenarioTree()
# Second stage
n1 = PH.add_node(st, PH.root(st))
n2 = PH.add_node(st, PH.root(st))
# Third stage
sc0 = PH.add_leaf(st, n1, 0.25*0.75)
sc1 = PH.add_leaf(st, n1, 0.75*0.75)
sc2 = PH.add_leaf(st, n2, 0.25)
@test length(n1.children) == 2
(n3, n4) = n1.children
if n3.id > n4.id
temp = n4
n4 = n3
n3 = temp
end
@test length(n2.children) == 1
n5 = first(n2.children) # only element in the set
@test PH.last_stage(st) == PH.StageID(3)
@test PH.is_leaf(st.root) == false
@test PH.is_leaf(n1) == false
@test PH.is_leaf(n2) == true # only having 1 child scenario means this is actually a leaf
@test PH.is_leaf(n3) == true
@test PH.is_leaf(n4) == true
@test PH.is_leaf(n5) == true
@test st.prob_map[sc0] == 0.25*0.75
@test st.prob_map[sc1] == 0.75*0.75
@test st.prob_map[sc2] == 0.25
nodes = [st.root, n1, n2, n3, n4, n5]
for n in nodes
@test st.tree_map[n.id] == n
end
@test PH.scenarios(st) == Set([sc0, sc1, sc2])
@test PH.scenario_bundle(st.root) == Set([sc0, sc1, sc2])
@test PH.scenario_bundle(n1) == Set([sc0, sc1])
@test PH.scenario_bundle(n2) == Set([sc2])
@test PH.scenario_bundle(n3) == Set([sc0])
@test PH.scenario_bundle(n4) == Set([sc1])
@test PH.scenario_bundle(n5) == Set([sc2])
end
@testset "Scenario Tree Utilities" begin
N = 10
p = rand(N)
p /= sum(p)
st = PH.two_stage_tree(p)
@test PH.last_stage(st) == PH.stid(2)
@test length(st.tree_map) == N + 1
for (scen, prob) in pairs(st.prob_map)
@test prob == p[PH.value(scen) + 1]
end
st = PH.two_stage_tree(N)
@test PH.last_stage(st) == PH.stid(2)
@test length(st.tree_map) == N + 1
for (scen, prob) in pairs(st.prob_map)
@test prob == 1.0 / 10.0
end
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 4739 | @testset "Struct accessors" begin
@test PH.value(PH.ScenarioID(1)) == 1
@test PH.value(PH.StageID(2)) == 2
@test PH.value(PH.Index(3)) == 3
@test PH.value(PH.NodeID(4)) == 4
end
@testset "Convenience constructors" begin
@test PH.scid(1) == PH.ScenarioID(1)
@test PH.stid(1) == PH.StageID(1)
@test PH.index(1) == PH.Index(1)
end
@testset "Struct less than operators" begin
@test PH.NodeID(3) < PH.NodeID(7)
@test PH.scid(0) < PH.scid(2)
@test PH.stid(1) < PH.stid(4)
@test PH._increment(PH.stid(1)) == PH.stid(2)
@test PH.index(10) < PH.index(16)
@test PH._increment(PH.index(15)) == PH.index(16)
uvid1 = PH.VariableID(PH.scid(4), PH.stid(1), PH.index(347))
uvid2 = PH.VariableID(PH.scid(0), PH.stid(2), PH.index(2))
uvid3 = PH.VariableID(PH.scid(1), PH.stid(2), PH.index(2))
uvid4 = PH.VariableID(PH.scid(1), PH.stid(2), PH.index(3))
@test uvid1 < uvid2
@test uvid2 < uvid3
@test uvid3 < uvid4
xhid1 = PH.XhatID(PH.NodeID(0), PH.Index(4))
xhid2 = PH.XhatID(PH.NodeID(1), PH.Index(2))
xhid3 = PH.XhatID(PH.NodeID(1), PH.Index(3))
@test xhid1 < xhid2
@test xhid2 < xhid3
end
@testset "Consensus variable functions" begin
tv = PH.HatVariable(true)
@test PH.is_integer(tv)
vid = PH.VariableID(PH.scid(3), PH.stid(2), PH.index(392))
PH.add_variable(tv, vid)
@test PH.variables(tv) == Set([vid])
rv = rand()
PH.set_value(tv, rv)
@test tv.value == rv
@test PH.value(tv) == rv
end
@testset "Convenience functions" begin
st = two_stage_tree(3)
@test length(st.tree_map) == 4
@test length(st.prob_map) == 3
@test isapprox(sum(values(st.prob_map)), 1.0)
p = [0.8, 0.2]
st = two_stage_tree(p)
@test st.prob_map[PH.scid(0)] == p[1]
@test st.prob_map[PH.scid(1)] == p[2]
end
nv1 = 3
nv2 = 4
phd = fake_phdata(nv1, nv2)
nscen = length(PH.scenarios(phd))
@testset "Accessor Utilities" begin
scid = PH.scid(0)
stid = PH.stid(1)
index = PH.index(2)
vid = PH.VariableID(scid, stid, index)
@test PH.name(phd, vid) == "a2"
val = convert(Float64, PH.value(index) - PH.value(scid))
@test PH.value(phd, vid) == val
@test PH.value(phd, scid, stid, index) == val
@test PH.branch_value(phd, vid) == val
@test PH.branch_value(phd, scid, stid, index) == val
scid = PH.scid(1)
stid = PH.stid(2)
index = PH.index(3)
vid = PH.VariableID(scid, stid, index)
@test PH.name(phd, vid) == "b4"
val = convert(Float64, nscen + (PH.value(index) + 1)*(PH.value(scid) + 1))
@test PH.value(phd, vid) == val
@test PH.value(phd, scid, stid, index) == val
@test PH.leaf_value(phd, vid) == val
@test PH.leaf_value(phd, scid, stid, index) == val
@test_throws ErrorException PH.name(phd, PH.VariableID(PH.scid(8303), stid, index))
@test scenario_tree(phd) === phd.scenario_tree
time_str_1 = @capture_out(print_timing(phd))
@test length(time_str_1) > 0
io = IOBuffer()
print_timing(io, phd)
time_str_2 = String(take!(io))
@test length(time_str_2) > 0
end
@testset "Conversion utilities" begin
# Branch variables
for i in 1:nv1
vid1 = PH.VariableID(PH.scid(0), PH.stid(1), PH.index(i))
vid2 = PH.VariableID(PH.scid(1), PH.stid(1), PH.index(i+1))
xhid = PH.convert_to_xhat_id(phd, vid1)
@test PH.convert_to_xhat_id(phd, vid2) == xhid
@test PH.convert_to_variable_ids(phd, xhid) == Set{PH.VariableID}([vid1, vid2])
end
# Leaf variables
for j in 1:nv2
vid1 = PH.VariableID(PH.scid(0), PH.stid(2), PH.index(j-1))
vid2 = PH.VariableID(PH.scid(1), PH.stid(2), PH.index(j-1))
@test PH.convert_to_variable_ids(phd, PH.convert_to_xhat_id(phd, vid1)) == Set{PH.VariableID}([vid1])
@test PH.convert_to_variable_ids(phd, PH.convert_to_xhat_id(phd, vid2)) == Set{PH.VariableID}([vid2])
@test PH.convert_to_xhat_id(phd, vid1) != PH.convert_to_xhat_id(phd, vid2)
end
end
@testset "PH variable accessors" begin
scid = PH.scid(0)
stid = PH.stid(1)
index = PH.index(1)
vid = PH.VariableID(scid, stid, index)
rval = rand()
phd.scenario_map[scid].w_vars[vid] = rval
@test PH.w_value(phd, vid) == rval
@test PH.w_value(phd, scid, stid, index) == rval
rval = rand()
xhid = PH.convert_to_xhat_id(phd, vid)
phd.xhat[xhid].value = rval
@test PH.xhat_value(phd, xhid) == rval
@test PH.xhat_value(phd, vid) == rval
@test PH.xhat_value(phd, scid, stid, index) == rval
@test PH.is_leaf(phd, xhid) == false
vid = PH.VariableID(PH.scid(0), PH.stid(2), PH.index(0))
xhid = PH.convert_to_xhat_id(phd, vid)
@test PH.is_leaf(phd, xhid) == true
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | code | 1029 |
ch_size = 10
@testset "Basics" begin
worker_inf = PH._launch_workers(ch_size, ch_size)
@test PH._number_workers(worker_inf) == 1
@test PH._is_running(worker_inf)
my_task = @async begin
PH._send_message(worker_inf, myid(), Ping())
PH._retrieve_message_type(worker_inf, Ping)
end
@test timeout_wait(my_task)
my_task = @async begin
PH._abort(worker_inf)
PH._wait_for_shutdown(worker_inf)
end
@test timeout_wait(my_task)
@test !PH._is_running(worker_inf)
@test PH._number_workers(worker_inf) == 0
end
@testset "Error Handling" begin
worker_inf = PH._launch_workers(ch_size, ch_size)
struct MakeWorkerError <: PH.Message end
PH._send_message(worker_inf, myid(), MakeWorkerError())
my_task = @async begin
PH._wait_for_shutdown(worker_inf)
end
if(timeout_wait(my_task))
@test istaskfailed(my_task)
@test typeof(my_task.exception) <: RemoteException
else
error("Test timed out")
end
end
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 1098 | [](https://github.com/NREL/ProgressiveHedging.jl/workflows/master-tests.yml)
[](https://codecov.io/gh/NREL/ProgressiveHedging.jl)
[](https://nrel.github.io/ProgressiveHedging.jl/dev)
ProgressiveHedging.jl is a basic implementation of the [Progressive Hedging algorithm](https://pdfs.semanticscholar.org/4ab8/028748c89b226fd46cf9f45de88218779572.pdf) which is used to solve stochastic programs.
ProgressiveHedging.jl makes use of the [JuMP](https://github.com/JuliaOpt/JuMP.jl) framework to build and solve the subproblems. It can be used with Julia's Distributed package to solve problems in parallel.
Users pass a function that builds a JuMP model along with a scenario tree and a dictionary identifying the variables in each stage.
Examples written in a Jupyter notebook may be found in the Examples directory.
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 1609 |
# ProgressiveHedging.jl
```@meta
CurrentModule = ProgressiveHedging
```
## Overview
ProgressiveHedging.jl is a [Julia](https://julialang.org/) implementation of the [Progressive Hedging](https://pubsonline.informs.org/doi/abs/10.1287/moor.16.1.119) algorithm of Rockafellar and Wets. It is capable of solving multi-stage stochastic programs:
``\min_X \sum_{s=1}^S p_s f_s(X)``
To solve this problem, ProgressiveHedging.jl makes use of [JuMP](https://github.com/JuliaOpt/JuMP.jl). Specifically, the user constructs a wrapped JuMP model for a single subproblem as well as a scenario tree which describes the structure of the stochastic program. For more details on the process see this [Basic Example](@ref). Through the use of Julia's [Distributed](https://docs.julialang.org/en/v1/stdlib/Distributed/) package, PH may be run in parallel either on a single multi-core platform or in a distributed fashion across multiple compute nodes. See the [Distributed Example](@ref) for more details.
In addition to providing an easily accessible solver for stochastic programs, ProgressiveHedging.jl is designed to be extensible to enable research on the PH algorithm itself. Abstract interfaces exist for the penalty parameter and subproblem types so that the user may implement their own penalty parameter selection method or use an Julia enabled algebraic modeling language.
------------
ProgressiveHedging has been developed as part of the Scalable Integrated Infrastructure Planning (SIIP) initiative at the U.S. Department of Energy's National Renewable Energy Laboratory ([NREL](https://www.nrel.gov/))
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 1007 | # Low-Level Functions
```@index
Pages = ["functions.md"]
```
## Callback Creation and Retrieval
```@docs
apply_to_subproblem
cb
get_callback
get_callback_ext
mean_deviation
spcb
variable_fixing
```
## ID Type Interactions
```@docs
convert_to_variable_ids
convert_to_xhat_id
index
scenario
scid
stage
stage_id
stid
value(::Index)
value(::NodeID)
value(::ScenarioID)
value(::StageID)
```
## Result Retrieval
```@docs
lower_bounds
print_timing
residuals
retrieve_soln
retrieve_aug_obj_value
retrieve_obj_value
retrieve_no_hats
retrieve_no_hat_history
retrieve_w
retrieve_w_history
retrieve_xhat_history
```
## Problem Accessors
```@docs
probability
scenario_tree
scenarios
```
## Scenario Tree
```@docs
add_node
add_leaf
root
two_stage_tree
```
## Variable Interactions
```@docs
branch_value
consensus_variables
is_integer
is_leaf
leaf_value
name
scenario_bundle
value(::HatVariable)
value(::PHData, ::VariableID)
value(::PHData, ::ScenarioID, ::StageID, ::Index)
variables
w_value
xhat_value
```
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 100 | # High-Level Functions
```@index
Pages = ["high-level.md"]
```
```@docs
solve
solve_extensive
```
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 773 | # Interfaces
```@index
Pages = ["interfaces.md"]
```
## Penalty Parameter
```@docs
AbstractPenaltyParameter
get_penalty_value
is_initial_value_dependent
is_subproblem_dependent
is_variable_dependent
penalty_map
process_penalty_initial_value
process_penalty_subproblem
```
## Subproblem
### Types
```@docs
AbstractSubproblem
VariableInfo
```
### Required Functions
```@docs
add_ph_objective_terms
objective_value
report_values
report_variable_info
solve_subproblem
update_ph_terms
```
### Optional Functions
```@docs
warm_start
```
### Extensive Form Functions
```@docs
ef_copy_model
ef_node_dict_constructor
```
### Penalty Parameter Functions
```@docs
report_penalty_info
```
### Lower Bound Functions
```@docs
add_lagrange_terms
update_lagrange_terms
```
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 544 | ```@meta
CurrentModule = ProgressiveHedging
```
# Types
Exported types in ProgressiveHedging.jl.
```@index
Pages = ["types.md"]
```
## Callbacks
```@docs
Callback
SubproblemCallback
```
## Exceptions
```@docs
UnimplementedError
```
## ID Types
```@docs
Index
NodeID
ScenarioID
StageID
VariableID
XhatID
```
## Penalty Parameters
```@docs
ProportionalPenaltyParameter
ScalarPenaltyParameter
SEPPenaltyParameter
```
## Subproblems
```@docs
JuMPSubproblem
```
## User Facing
```@docs
HatVariable
PHData
ScenarioNode
ScenarioTree
```
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 7349 | # Basic Example
## Problem
A basic example using ProgressiveHedging.jl to solve a stochastic program. This example is also available as the script basic_example.jl in the example directory.
Here we will use ProgressiveHedging.jl to solve the simple problem
``\min_x x + \sum_{s=0}^1 p_s c_s y_s``
subject to
``x \ge 0``
``y_s \ge 0, s \in {0,1}``
``x + y = b_s``
where
``
b_s = \begin{cases} 11, & s=0 \\ 4, & s=1 \end{cases},
``
``
c_s = \begin{cases} 0.5, & s=0 \\ 10, & s=1 \end{cases}
``
and for now we will take equally probable scenarios, that is, ``p_0 = p_1 = 0.5``.
## Setup
First we need to bring in the needed packages
```@example basic
using ProgressiveHedging
import JuMP
import Ipopt
```
We will need JuMP to build the model for each subproblem and we will use Ipopt to solve each subproblem.
!!! note
There are some functions that both JuMP and ProgressiveHedging export. To avoid confusion (and warnings) it is best to import one or both of these packages.
## Subproblem Creation Function
Next, we write a function that will generate the subproblems for each scenario. The following creates the subproblem for a simple two stage stochastic program.
```@example basic
function two_stage_model(scenario_id::ScenarioID)
model = JuMP.Model(()->Ipopt.Optimizer())
JuMP.set_optimizer_attribute(model, "print_level", 0)
JuMP.set_optimizer_attribute(model, "tol", 1e-12)
JuMP.set_optimizer_attribute(model, "acceptable_tol", 1e-12)
scen = value(scenario_id)
ref = JuMP.@variable(model, x >= 0.0)
stage1 = [ref]
ref = JuMP.@variable(model, y >= 0.0)
stage2 = [ref]
b_s = scen == 0 ? 11.0 : 4.0
c_s = scen == 0 ? 0.5 : 10.0
JuMP.@constraint(model, x + y == b_s)
JuMP.@objective(model, Min, 1.0*x + c_s*y)
return JuMPSubproblem(model,
scenario_id,
Dict(stid(1) => stage1,
stid(2) => stage2)
)
end
nothing # hide
```
There are a few things to note here:
* This function must take as an argument a [`ScenarioID`](@ref).
* The mathematical model is built using JuMP.
* The function returns a [`JuMPSubproblem`](@ref). This is an implementation of the [`AbstractSubproblem`](@ref) interface which uses JuMP as the algebraic modeling language.
* In addition to the model, the subproblem also requires the [`ScenarioID`](@ref) and a dictionary identifying which variables belong in which stage.
## Scenario Tree Construction
Second we need to construct a [`ScenarioTree`](@ref) that captures the structure of our stochastic program. We can do this using the [`ScenarioTree`](@ref) constructor and the function [`add_leaf`](@ref):
```@example basic
scen_tree = ScenarioTree()
scenario_id_0 = add_leaf(scen_tree, root(scen_tree), 0.5)
scenario_id_1 = add_leaf(scen_tree, root(scen_tree), 0.5)
nothing # hide
```
Here we created a scenario tree and added two leaf nodes each representing the two scenarios in our problem. We specified both occur with probability 0.5. The other thing to note is that [`add_leaf`](@ref) returns a [`ScenarioID`](@ref). This is a type-safe integer that PH uses to uniquely indentify the each scenario and subproblem. Note that the numbering starts at 0.
```@example basic
@show scenario_id_0
@show scenario_id_1
nothing # hide
```
The subproblem created by the subproblem creation function should correspond to the path in the scenario tree that leads to this leaf. In our case, we have a two-stage tree and it does not matter which scenario is identified as scenario 0 and scenario 1.
Since two-stage stochastic programs are extremely common, ProgressiveHedging.jl provides a convenience function to generate two-stage trees with arbitrarily many scenarios: [`two_stage_tree`](@ref). So we could have used
```@example
using ProgressiveHedging # hide
scen_tree = two_stage_tree(2)
nothing # hide
```
## Solution
We are now ready to solve the problem. To do so we just use the [`solve`](@ref) function and provide it with our scenario tree, the subproblem creation function and a penalty parameter.
```@setup basic
# Hack to avoid having the Ipopt inclusion message in the documentation...
(niter, abs_res, rel_res, obj, soln_df, phd) = solve(scen_tree,
two_stage_model,
ScalarPenaltyParameter(1.0)
)
```
```@example basic
(niter, abs_res, rel_res, obj, soln_df, phd) = solve(scen_tree,
two_stage_model,
ScalarPenaltyParameter(1.0)
)
@show niter
@show abs_res
@show rel_res
@show obj
@show soln_df
nothing # hide
```
The solve function returns the number of iteration, the absolute and relative residual, the objective value, a `DataFrame` containing the solution and, lastly, a [`PHData`](@ref) instance.
The [`PHData`](@ref) contains additional information like the dual (Lagrange multiplier) values for the nonanticipativity constraints
```@example basic
dual_df = retrieve_w(phd)
@show dual_df
nothing # hide
```
as well as the raw values of the consensus contributing variables
```@example basic
raw_values_df = retrieve_no_hats(phd)
@show raw_values_df
nothing # hide
```
## Determining the Consensus Variables
!!! note "Determining the Consensus Variables"
You may notice that we never specifically indicated which variables needed nonanticipativity constraints. ProgressiveHedging determines this automatically for us using the scenario tree we constructed, the stage the variable is in and the name the variable is given. When using the [`JuMPSubproblem`](@ref), the name of the variable is determined by calling the function `JuMP.name` on each `JuMP.VariableRef` object. The stage is given by the dictionary given to the [`JuMPSubproblem`](@ref) constructor as seen in the subproblem creation function above. This is possible because the combination of a [`ScenarioID`](@ref) and a [`StageID`](@ref) uniquely determine a node on the scenario tree. Any variables with the same names that belong to this node are assumed to require nonanticipativity constraints and so are identified as consensus variables.
## Extensive Solve
For smaller problems, it is also possible to solve the extensive form of the problem directly. ProgressiveHedging.jl is capable of building the extensive form from the previously defined function and scenario tree.
```@example basic
ef_model = solve_extensive(scen_tree,
two_stage_model,
()->Ipopt.Optimizer(),
opt_args=(print_level=0, tol=1e-12, acceptable_tol=1e-12)
)
nothing # hide
```
This function builds, optimizes and returns a JuMP model of the extensive form. As such, information is obtained from it as from any other JuMP model.
```@example basic
@show JuMP.termination_status(ef_model)
@show JuMP.objective_value(ef_model)
for v in JuMP.all_variables(ef_model)
println("$v = $(JuMP.value(v))")
end
nothing # hide
```
!!! note
The subscripts in the variable names are the scenarios to which the variable belongs.
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
|
[
"BSD-3-Clause"
] | 0.5.1 | e89f3d1830790439dcb1404bb99d017d8a986259 | docs | 3630 | # Callback Example
An example of creating and adding a callback to a ProgressiveHedging.jl run. This example is also available as the script callback_example.jl in the example directory.
In this example, we will use the same setup as in the [Basic Example](@ref).
```@example callback
using ProgressiveHedging
import JuMP
import Ipopt
function two_stage_model(scenario_id::ScenarioID)
model = JuMP.Model(()->Ipopt.Optimizer())
JuMP.set_optimizer_attribute(model, "print_level", 0)
JuMP.set_optimizer_attribute(model, "tol", 1e-12)
JuMP.set_optimizer_attribute(model, "acceptable_tol", 1e-12)
scen = value(scenario_id)
ref = JuMP.@variable(model, x >= 0.0)
stage1 = [ref]
ref = JuMP.@variable(model, y >= 0.0)
stage2 = [ref]
b_s = scen == 0 ? 11.0 : 4.0
c_s = scen == 0 ? 0.5 : 10.0
JuMP.@constraint(model, x + y == b_s)
JuMP.@objective(model, Min, 1.0*x + c_s*y)
return JuMPSubproblem(model,
scenario_id,
Dict(stid(1) => stage1,
stid(2) => stage2)
)
end
scen_tree = two_stage_tree(2)
nothing # hide
```
We now write a function to get called as PH executes and wrap it in the [`Callback`](@ref) type.
```@example callback
function my_callback(ext::Dict{Symbol,Any},
phd::PHData,
winf::ProgressiveHedging.WorkerInf,
niter::Int)
# The `ext` dictionary can be used to store things between PH iterations
if niter == 2
ext[:message] = "This is from iteration 2!"
elseif niter == 5
println("Iteration 5 found the message: " * ext[:message])
elseif niter == 10
println("This is iteration 10!")
# We can access the current consensus variable values
for (xhid, xhat) in pairs(consensus_variables(phd))
println("The value of $(name(phd,xhid)) is $(value(xhat)).")
end
end
# Returning false from the callback will terminate PH.
# Here we stop after 20 iterations.
return niter < 20
end
my_cb = Callback(my_callback)
nothing # hide
```
Several things are worth noting here:
* All callback functions must have the signature given here
* The `ext` dictionary is unique to each callback and can be used to pass information from one iteration to the next
* Returning false from the callback will terminate PH
Now we call the [`solve`](@ref) function as before but giving it the callback object we created.
```@example callback
(niter, abs_res, rel_res, obj, soln_df, phd) = solve(scen_tree,
two_stage_model,
ScalarPenaltyParameter(1.0),
callbacks=[my_cb]
)
@show niter
@show abs_res
@show rel_res
@show obj
@show soln_df
nothing # hide
```
The callbacks can be used to implement solution heuristics and alternative termination criteria. There are two callbacks are included with ProgressiveHedging.jl that do this. [`variable_fixing`](@ref) is a heuristic that fixes variables whose values remain (approximately) the same over a set number of iterations. It is hoped that this speeds the convergence of PH. [`mean_deviation`](@ref) is an alternative termination criteria. It is a form of mean relative absolute deviation from the consensus variable value. These are both implmentations of ideas found in [(Watson & Woodruff 2010)](https://link.springer.com/article/10.1007/s10287-010-0125-4).
| ProgressiveHedging | https://github.com/NREL/ProgressiveHedging.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.