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.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 19306 | """
Update order for a block-coordinate method.
A `BlockCoordinateUpdateOrder` must implement
```
select_update_indices(::BlockCoordinateUpdateOrder, s::CallbackState, dual_gaps)
```
"""
abstract type BlockCoordinateUpdateOrder end
"""
select_update_indices(::BlockCoordinateUpdateOrder, s::CallbackState, dual_gaps)
Returns a list of lists of the block indices.
Each sublist represents one round of updates in an iteration. The indices in a list show which blocks should be updated parallely in one round.
For example, a full update is given by `[1:l]` and a blockwise update by `[[i] for i=1:l]`, where `l` is the number of blocks.
"""
function select_update_indices end
"""
The full update initiates a parallel update of all blocks in one single round.
"""
struct FullUpdate <: BlockCoordinateUpdateOrder end
"""
The cyclic update initiates a sequence of update rounds.
In each round only one block is updated. The order of the blocks is determined by the given order of the LMOs.
"""
struct CyclicUpdate <: BlockCoordinateUpdateOrder
limit::Int
end
CyclicUpdate() = CyclicUpdate(-1)
"""
The stochastic update initiates a sequence of update rounds.
In each round only one block is updated. The order of the blocks is a random.
"""
struct StochasticUpdate <: BlockCoordinateUpdateOrder
limit::Int
end
StochasticUpdate() = StochasticUpdate(-1)
mutable struct DualGapOrder <: BlockCoordinateUpdateOrder
limit::Int
end
DualGapOrder() = DualGapOrder(-1)
mutable struct DualProgressOrder <: BlockCoordinateUpdateOrder
limit::Int
previous_dual_gaps::Vector{Float64}
dual_progress::Vector{Float64}
end
DualProgressOrder() = DualProgressOrder(-1, [], [])
DualProgressOrder(i::Int64) = DualProgressOrder(i, [], [])
function select_update_indices(::FullUpdate, s::CallbackState, _)
return [1:length(s.lmo.lmos)]
end
function select_update_indices(u::CyclicUpdate, s::CallbackState, _)
l = length(s.lmo.lmos)
@assert u.limit <= l
@assert u.limit > 0 || u.limit == -1
if u.limit in [-1, l]
return [[i] for i in 1:l]
end
start = (s.t*u.limit % l) + 1
if start + u.limit - 1 ≤ l
return [[i] for i in start:start + u.limit - 1]
else
a = [[i] for i in start:l]
append!(a, [[i] for i in 1:u.limit-length(a)])
return a
end
end
function select_update_indices(u::StochasticUpdate, s::CallbackState, _)
l = length(s.lmo.lmos)
@assert u.limit <= l
@assert u.limit > 0 || u.limit == -1
if u.limit == -1
return [[rand(1:l)] for i in 1:l]
end
return [[rand(1:l)] for i in 1:u.limit]
end
function select_update_indices(u::DualProgressOrder, s::CallbackState, dual_gaps)
l = length(s.lmo.lmos)
@assert u.limit <= l
@assert u.limit > 0 || u.limit == -1
# In the first iteration update every block so we get finite dual progress
if s.t < 2
u.previous_dual_gaps = copy(dual_gaps)
return [[i] for i=1:l]
end
if s.t == 1
u.dual_progress = dual_gaps - u.previous_dual_gaps
else
diff = dual_gaps - u.previous_dual_gaps
u.dual_progress = [d == 0 ? u.dual_progress[i] : d for (i, d) in enumerate(diff)]
end
u.previous_dual_gaps = copy(dual_gaps)
n = u.limit == -1 ? l : u.limit
return [[findfirst(cumsum(u.dual_progress/sum(u.dual_progress)) .> rand())] for _=1:n]
end
function select_update_indices(u::DualGapOrder, s::CallbackState, dual_gaps)
l = length(s.lmo.lmos)
@assert u.limit <= l
@assert u.limit > 0 || u.limit == -1
# In the first iteration update every block so we get finite dual gaps
if s.t < 1
return [[i] for i=1:l]
end
n = u.limit == -1 ? l : u.limit
return [[findfirst(cumsum(dual_gaps/sum(dual_gaps)) .> rand())] for _=1:n]
end
"""
Update step for block-coordinate Frank-Wolfe.
These are implementations of different FW-algorithms to be used in a blockwise manner.
Each update step must implement
```
update_iterate(
step::UpdateStep,
x,
lmo,
f,
gradient,
grad!,
dual_gap,
t,
line_search,
linesearch_workspace,
memory_mode,
epsilon,
)
```
"""
abstract type UpdateStep end
"""
update_iterate(
step::UpdateStep,
x,
lmo,
f,
gradient,
grad!,
dual_gap,
t,
line_search,
linesearch_workspace,
memory_mode,
epsilon,
)
Executes one iteration of the defined [`FrankWolfe.UpdateStep`](@ref) and updates the iterate `x` implicitly.
The function returns a tuple `(dual_gap, v, d, gamma, step_type)`:
- `dual_gap` is the updated FrankWolfe gap
- `v` is the used vertex
- `d` is the update direction
- `gamma` is the applied step-size
- `step_type` is the applied step-type
"""
function update_iterate end
"""
Implementation of the vanilla Frank-Wolfe algorithm as an update step for block-coordinate Frank-Wolfe.
"""
struct FrankWolfeStep <: UpdateStep end
"""
Implementation of the blended pairwise conditional gradient (BPCG) method as an update step for block-coordinate Frank-Wolfe.
"""
mutable struct BPCGStep <: UpdateStep
lazy::Bool
active_set::Union{FrankWolfe.AbstractActiveSet,Nothing}
renorm_interval::Int
lazy_tolerance::Float64
phi::Float64
end
function Base.copy(::FrankWolfeStep)
return FrankWolfeStep()
end
function Base.copy(obj::BPCGStep)
if obj.active_set === nothing
return BPCGStep(false, nothing, obj.renorm_interval, obj.lazy_tolerance, Inf)
else
return BPCGStep(obj.lazy, copy(obj.active_set), obj.renorm_interval, obj.lazy_tolerance, obj.phi)
end
end
BPCGStep() = BPCGStep(false, nothing, 1000, 2.0, Inf)
function update_iterate(
::FrankWolfeStep,
x,
lmo,
f,
gradient,
grad!,
dual_gap,
t,
line_search,
linesearch_workspace,
memory_mode,
epsilon,
)
d = similar(x)
v = compute_extreme_point(lmo, gradient)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
d = muladd_memory_mode(memory_mode, d, x, v)
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
1.0,
linesearch_workspace,
memory_mode,
)
x = muladd_memory_mode(memory_mode, x, gamma, d)
step_type = ST_REGULAR
return (dual_gap, v, d, gamma, step_type)
end
function update_iterate(
s::BPCGStep,
x,
lmo,
f,
gradient,
grad!,
dual_gap,
t,
line_search,
linesearch_workspace,
memory_mode,
epsilon,
)
d = zero(x)
step_type = ST_REGULAR
_, v_local, v_local_loc, _, a_lambda, a, a_loc, _, _ =
active_set_argminmax(s.active_set, gradient)
dot_forward_vertex = fast_dot(gradient, v_local)
dot_away_vertex = fast_dot(gradient, a)
local_gap = dot_away_vertex - dot_forward_vertex
if !s.lazy
v = compute_extreme_point(lmo, gradient)
dual_gap = fast_dot(gradient, x) - fast_dot(gradient, v)
s.phi = dual_gap
end
# minor modification from original paper for improved sparsity
# (proof follows with minor modification when estimating the step)
if local_gap > s.phi / s.lazy_tolerance
d = muladd_memory_mode(memory_mode, d, a, v_local)
vertex_taken = v_local
gamma_max = a_lambda
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
linesearch_workspace,
memory_mode,
)
gamma = min(gamma_max, gamma)
step_type = gamma ≈ gamma_max ? ST_DROP : ST_PAIRWISE
# reached maximum of lambda -> dropping away vertex
if gamma ≈ gamma_max
s.active_set.weights[v_local_loc] += gamma
deleteat!(s.active_set, a_loc)
else # transfer weight from away to local FW
s.active_set.weights[a_loc] -= gamma
s.active_set.weights[v_local_loc] += gamma
@assert active_set_validate(s.active_set)
end
active_set_update_iterate_pairwise!(s.active_set.x, gamma, v_local, a)
else # add to active set
if s.lazy
v = compute_extreme_point(lmo, gradient)
step_type = ST_REGULAR
end
vertex_taken = v
dual_gap = fast_dot(gradient, x) - fast_dot(gradient, v)
# if we are about to exit, compute dual_gap with the cleaned-up x
if dual_gap ≤ epsilon
active_set_renormalize!(s.active_set)
active_set_cleanup!(s.active_set)
compute_active_set_iterate!(s.active_set)
x = get_active_set_iterate(s.active_set)
grad!(gradient, x)
dual_gap = fast_dot(gradient, x) - fast_dot(gradient, v)
end
if !s.lazy || dual_gap ≥ s.phi / s.lazy_tolerance
d = muladd_memory_mode(memory_mode, d, x, v)
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
one(eltype(x)),
linesearch_workspace,
memory_mode,
)
# dropping active set and restarting from singleton
if gamma ≈ 1.0
active_set_initialize!(s.active_set, v)
else
renorm = mod(t, s.renorm_interval) == 0
active_set_update!(s.active_set, gamma, v, renorm, nothing)
end
else # dual step
if step_type != ST_LAZYSTORAGE
s.phi = dual_gap
@debug begin
@assert step_type == ST_REGULAR
v2 = compute_extreme_point(lmo, gradient)
g = dot(gradient, x - v2)
if abs(g - dual_gap) > 100 * sqrt(eps())
error("dual gap estimation error $g $dual_gap")
end
end
else
@info "useless step"
end
step_type = ST_DUALSTEP
gamma = 0.0
end
end
if mod(t, s.renorm_interval) == 0
active_set_renormalize!(s.active_set)
end
x = muladd_memory_mode(memory_mode, x, gamma, d)
return (dual_gap, vertex_taken, d, gamma, step_type)
end
"""
block_coordinate_frank_wolfe(f, grad!, lmo::ProductLMO{N}, x0; ...) where {N}
Block-coordinate version of the Frank-Wolfe algorithm.
Minimizes objective `f` over the product of feasible domains specified by the `lmo`.
The optional argument the `update_order` is of type [`FrankWolfe.BlockCoordinateUpdateOrder`](@ref) and controls the order in which the blocks are updated.
The argument `update_step` is a single instance or tuple of [`FrankWolfe.UpdateStep`](@ref) and defines which FW-algorithms to use to update the iterates in the different blocks.
The method returns a tuple `(x, v, primal, dual_gap, traj_data)` with:
- `x` cartesian product of final iterates
- `v` cartesian product of last vertices of the LMOs
- `primal` primal value `f(x)`
- `dual_gap` final Frank-Wolfe gap
- `traj_data` vector of trajectory information.
See [S. Lacoste-Julien, M. Jaggi, M. Schmidt, and P. Pletscher 2013](https://arxiv.org/abs/1207.4747)
and [A. Beck, E. Pauwels and S. Sabach 2015](https://arxiv.org/abs/1502.03716) for more details about Block-Coordinate Frank-Wolfe.
"""
function block_coordinate_frank_wolfe(
f,
grad!,
lmo::ProductLMO{N},
x0::BlockVector;
update_order::BlockCoordinateUpdateOrder=CyclicUpdate(),
line_search::LS=Adaptive(),
update_step::US=FrankWolfeStep(),
momentum=nothing,
epsilon=1e-7,
max_iteration=10000,
print_iter=1000,
trajectory=false,
verbose=false,
memory_mode=InplaceEmphasis(),
gradient=nothing,
callback=nothing,
traj_data=[],
timeout=Inf,
linesearch_workspace=nothing,
) where {
N,
US<:Union{UpdateStep,NTuple{N,UpdateStep}},
LS<:Union{LineSearchMethod,NTuple{N,LineSearchMethod}},
}
# header and format string for output of the algorithm
headers = ["Type", "Iteration", "Primal", "Dual", "Dual Gap", "Time", "It/sec"]
format_string = "%6s %13s %14e %14e %14e %14e %14e\n"
function format_state(state, args...)
rep = (
steptype_string[Symbol(state.step_type)],
string(state.t),
Float64(state.primal),
Float64(state.primal - state.dual_gap),
Float64(state.dual_gap),
state.time,
state.t / state.time,
)
return rep
end
#ndim = ndims(x0)
t = 0
dual_gap = Inf
dual_gaps = fill(Inf, N)
primal = Inf
x = copy(x0)
step_type = ST_REGULAR
if trajectory
callback = make_trajectory_callback(callback, traj_data)
end
if verbose
callback = make_print_callback(callback, print_iter, headers, format_string, format_state)
end
if update_step isa UpdateStep
update_step = [copy(update_step) for _ in 1:N]
end
for (i, s) in enumerate(update_step)
if s isa BPCGStep && s.active_set === nothing
s.active_set = ActiveSet([(1.0, copy(x0.blocks[i]))])
end
end
if line_search isa LineSearchMethod
line_search = [line_search for _ in 1:N]
end
gamma = nothing
v = similar(x)
time_start = time_ns()
if (momentum !== nothing && line_search isa Union{Shortstep,Adaptive,Backtracking})
@warn("Momentum-averaged gradients should usually be used with agnostic stepsize rules.",)
end
# instanciating container for gradient
if gradient === nothing
gradient = similar(x)
end
if verbose
println("\nBlock coordinate Frank-Wolfe (BCFW).")
num_type = eltype(x0[1])
line_search_type = [typeof(a) for a in line_search]
println(
"MEMORY_MODE: $memory_mode STEPSIZE: $line_search_type EPSILON: $epsilon MAXITERATION: $max_iteration TYPE: $num_type",
)
grad_type = typeof(gradient)
update_step_type = [typeof(s) for s in update_step]
println(
"MOMENTUM: $momentum GRADIENTTYPE: $grad_type UPDATE_ORDER: $update_order UPDATE_STEP: $update_step_type",
)
if memory_mode isa InplaceEmphasis
@info("In memory_mode memory iterates are written back into x0!")
end
end
first_iter = true
if linesearch_workspace === nothing
linesearch_workspace = [
build_linesearch_workspace(line_search[i], x.blocks[i], gradient.blocks[i]) for i in 1:N
] # TODO: might not be really needed - hence hack
end
# container for direction
d = similar(x)
gtemp = if momentum === nothing
d
else
similar(x)
end
# container for state
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
0.0,
x,
v,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
while t <= max_iteration && dual_gap >= max(epsilon, eps(float(typeof(dual_gap))))
#####################
# managing time and Ctrl-C
#####################
time_at_loop = time_ns()
if t == 0
time_start = time_at_loop
end
# time is measured at beginning of loop for consistency throughout all algorithms
tot_time = (time_at_loop - time_start) / 1e9
if timeout < Inf
if tot_time ≥ timeout
if verbose
@info "Time limit reached"
end
break
end
end
#####################
for update_indices in select_update_indices(update_order, state, dual_gaps)
# Update gradients
if momentum === nothing || first_iter
grad!(gradient, x)
if momentum !== nothing
gtemp .= gradient
end
else
grad!(gtemp, x)
@memory_mode(memory_mode, gradient = (momentum * gradient) + (1 - momentum) * gtemp)
end
first_iter = false
xold = copy(x)
Threads.@threads for i in update_indices
function extend(y)
bv = copy(xold)
bv.blocks[i] = y
return bv
end
function temp_grad!(storage, y, i)
z = extend(y)
big_storage = similar(z)
grad!(big_storage, z)
@. storage = big_storage.blocks[i]
end
dual_gaps[i], v.blocks[i], d.blocks[i], gamma, step_type = update_iterate(
update_step[i],
x.blocks[i],
lmo.lmos[i],
y -> f(extend(y)),
gradient.blocks[i],
(storage, y) -> temp_grad!(storage, y, i),
dual_gaps[i],
t,
line_search[i],
linesearch_workspace[i],
memory_mode,
epsilon,
)
end
dual_gap = sum(dual_gaps)
end
# go easy on the memory - only compute if really needed
if (
(mod(t, print_iter) == 0 && verbose) ||
callback !== nothing ||
line_search isa Shortstep
)
primal = f(x)
end
t = t + 1
if callback !== nothing || update_order isa CyclicUpdate
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
if callback !== nothing
# @show state
if callback(state, dual_gaps) === false
break
end
end
end
end
# recompute everything once for final verfication / do not record to trajectory though for now!
# this is important as some variants do not recompute f(x) and the dual_gap regularly but only when reporting
# hence the final computation.
step_type = ST_LAST
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient)
primal = f(x)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
tot_time = (time_ns() - time_start) / 1.0e9
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
callback(state, dual_gaps)
end
return x, v, primal, dual_gap, traj_data
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 9717 | """
BlockVector{T, MT <: AbstractArray{T}, ST <: Tuple} <: AbstractVector{T}
Represents a vector consisting of blocks. `T` is the element type of the vector, `MT` is the type of the underlying data array, and `ST` is the type of the tuple representing the sizes of each block.
Each block can be accessed with the `blocks` field, and the sizes of the blocks are stored in the `block_sizes` field.
"""
mutable struct BlockVector{T, MT <: AbstractArray{T}, ST <: Tuple} <: AbstractVector{T}
blocks::Vector{MT}
block_sizes::Vector{ST}
tot_size::Int
end
function BlockVector(arrays::AbstractVector{MT}) where {T, MT <: AbstractArray{T}}
block_sizes = size.(arrays)
tot_size = sum(prod, block_sizes)
return BlockVector(arrays, block_sizes, tot_size)
end
Base.size(arr::BlockVector) = (arr.tot_size, )
# returns the corresponding (block_index, index_in_block) for a given flattened index (for the whole block variable)
function _matching_index_index(arr::BlockVector, idx::Integer)
if idx < 1 || idx > length(arr)
throw(BoundsError(arr, idx))
end
first_idx = 1
for block_idx in eachindex(arr.block_sizes)
next_first = first_idx + prod(arr.block_sizes[block_idx])
if next_first <= idx
# continue to next block
first_idx = next_first
else
# index is here
index_in_block = idx - first_idx + 1
return (block_idx, index_in_block)
end
end
error("unreachable $idx")
end
function Base.getindex(arr::BlockVector, idx::Integer)
(midx, idx_inner) = _matching_index_index(arr, idx)
return arr.blocks[midx][idx_inner]
end
function Base.setindex!(arr::BlockVector, v, idx::Integer)
(midx, idx_inner) = _matching_index_index(arr, idx)
arr.blocks[midx][idx_inner] = v
return arr.blocks[midx][idx_inner]
end
function Base.copyto!(dest::BlockVector, src::BlockVector)
dest.tot_size = src.tot_size
for midx in eachindex(dest.blocks)
dest.blocks[midx] = copy(src.blocks[midx])
end
dest.block_sizes = copy(src.block_sizes)
return dest
end
function Base.similar(src::BlockVector{T1, MT}, ::Type{T}) where {T1, MT, T}
blocks = [similar(src.blocks[i], T) for i in eachindex(src.blocks)]
return BlockVector(
blocks,
src.block_sizes,
src.tot_size,
)
end
Base.similar(src::BlockVector{T, MT}) where {T, MT} = similar(src, T)
function Base.collect(::Type{T}, src::BlockVector{T1, MT}) where {T1, MT, T}
blocks = [collect(T, src.blocks[i]) for i in eachindex(src.blocks)]
return BlockVector(
blocks,
src.block_sizes,
src.tot_size,
)
end
Base.collect(src::BlockVector{T, MT}) where {T, MT} = collect(T, src)
function Base.zero(src::BlockVector)
blocks = [zero(b) for b in src.blocks]
return BlockVector(
blocks,
src.block_sizes,
src.tot_size,
)
end
function Base.convert(::Type{BlockVector{T, MT}}, bmv::BlockVector) where {T, MT}
cblocks = convert.(MT, bmv.blocks)
return BlockVector(
cblocks,
copy(bmv.block_sizes),
bmv.tot_size,
)
end
function Base.:+(v1::BlockVector, v2::BlockVector)
if size(v1) != size(v2) || length(v1.block_sizes) != length(v2.block_sizes)
throw(DimensionMismatch("$(length(v1)) != $(length(v2))"))
end
for i in eachindex(v1.block_sizes)
if v1.block_sizes[i] != v2.block_sizes[i]
throw(DimensionMismatch("$i-th block: $(v1.block_sizes[i]) != $(v2.block_sizes[i])"))
end
end
return BlockVector(
v1.blocks .+ v2.blocks,
copy(v1.block_sizes),
v1.tot_size,
)
end
Base.:-(v::BlockVector) = BlockVector(
[-b for b in v.blocks],
v.block_sizes,
v.tot_size,
)
function Base.:-(v1::BlockVector, v2::BlockVector)
return v1 + (-v2)
end
function Base.:*(s::Number, v::BlockVector)
return BlockVector(
s .* v.blocks,
copy(v.block_sizes),
v.tot_size,
)
end
Base.:*(v::BlockVector, s::Number) = s * v
function Base.:/(v::BlockVector, s::Number)
return BlockVector(
v.blocks ./ s,
copy(v.block_sizes),
v.tot_size,
)
end
function LinearAlgebra.dot(v1::BlockVector{T1}, v2::BlockVector{T2}) where {T1, T2}
if size(v1) != size(v2) || length(v1.block_sizes) != length(v2.block_sizes)
throw(DimensionMismatch("$(length(v1)) != $(length(v2))"))
end
T = promote_type(T1, T2)
d = zero(T)
@inbounds for i in eachindex(v1.block_sizes)
if v1.block_sizes[i] != v2.block_sizes[i]
throw(DimensionMismatch("$i-th block: $(v1.block_sizes[i]) != $(v2.block_sizes[i])"))
end
d += dot(v1.blocks[i], v2.blocks[i])
end
return d
end
LinearAlgebra.norm(v::BlockVector) = sqrt(dot(v, v))
function Base.isequal(v1::BlockVector, v2::BlockVector)
if v1 === v2
return true
end
if v1.tot_size != v2.tot_size || v1.block_sizes != v2.block_sizes
return false
end
for bidx in eachindex(v1.blocks)
if !isequal(v1.blocks[bidx], v2.blocks[bidx])
return false
end
end
return true
end
"""
ProductLMO(lmos)
Linear minimization oracle over the Cartesian product of multiple LMOs.
"""
struct ProductLMO{N, LT <: Union{NTuple{N, FrankWolfe.LinearMinimizationOracle}, AbstractVector{<: FrankWolfe.LinearMinimizationOracle}}} <: FrankWolfe.LinearMinimizationOracle
lmos::LT
end
function ProductLMO(lmos::Vector{LMO}) where {LMO <: FrankWolfe.LinearMinimizationOracle}
return ProductLMO{1, Vector{LMO}}(lmos)
end
function ProductLMO(lmos::NT) where {N, LMO <: FrankWolfe.LinearMinimizationOracle, NT <: NTuple{N, LMO}}
return ProductLMO{N, NT}(lmos)
end
function ProductLMO{N}(lmos::TL) where {N,TL<:NTuple{N,LinearMinimizationOracle}}
return ProductLMO{N,TL}(lmos)
end
function ProductLMO(lmos::Vararg{LinearMinimizationOracle,N}) where {N}
return ProductLMO{N}(lmos)
end
function FrankWolfe.compute_extreme_point(lmo::ProductLMO, direction::BlockVector; v=nothing, kwargs...)
@assert length(direction.blocks) == length(lmo.lmos)
blocks = [FrankWolfe.compute_extreme_point(lmo.lmos[idx], direction.blocks[idx]; kwargs...) for idx in eachindex(lmo.lmos)]
v = BlockVector(blocks, direction.block_sizes, direction.tot_size)
return v
end
"""
compute_extreme_point(lmo::ProductLMO, direction::Tuple; kwargs...)
Extreme point computation on Cartesian product, with a direction `(d1, d2, ...)` given as a tuple of directions.
All keyword arguments are passed to all LMOs.
"""
function compute_extreme_point(lmo::ProductLMO, direction::Tuple; kwargs...)
return compute_extreme_point.(lmo.lmos, direction; kwargs...)
end
"""
compute_extreme_point(lmo::ProductLMO, direction::AbstractArray; direction_indices, storage=similar(direction))
Extreme point computation, with a direction array and `direction_indices` provided such that:
`direction[direction_indices[i]]` is passed to the i-th LMO.
If no `direction_indices` are provided, the direction array is sliced along the last dimension and such that:
`direction[:, ... ,:, i]` is passed to the i-th LMO.
The result is stored in the optional `storage` container.
All keyword arguments are passed to all LMOs.
"""
function compute_extreme_point(
lmo::ProductLMO{N},
direction::AbstractArray;
storage=similar(direction),
direction_indices=nothing,
kwargs...,
) where {N}
if direction_indices !== nothing
for idx in 1:N
storage[direction_indices[idx]] .=
compute_extreme_point(lmo.lmos[idx], direction[direction_indices[idx]]; kwargs...)
end
else
ndim = ndims(direction)
direction_array = [direction[[idx < ndim ? Colon() : i for idx in 1:ndim]...] for i in 1:N]
storage = cat(compute_extreme_point.(lmo.lmos, direction_array)..., dims=ndim)
end
return storage
end
"""
MathOptInterface LMO but returns a vertex respecting the block structure
"""
function FrankWolfe.compute_extreme_point(lmo::FrankWolfe.MathOptLMO, direction::BlockVector)
xs = MOI.get(lmo.o, MOI.ListOfVariableIndices())
terms = [MOI.ScalarAffineTerm(direction[idx], xs[idx]) for idx in eachindex(xs)]
vec_v = FrankWolfe.compute_extreme_point(lmo::FrankWolfe.MathOptLMO, terms)
v = similar(direction)
copyto!(v, vec_v)
return v
end
function FrankWolfe.muladd_memory_mode(mem::FrankWolfe.InplaceEmphasis, storage::BlockVector, x::BlockVector, gamma::Real, d::BlockVector)
@inbounds for i in eachindex(x.blocks)
FrankWolfe.muladd_memory_mode(mem, storage.blocks[i], x.blocks[i], gamma, d.blocks[i])
end
return storage
end
function FrankWolfe.muladd_memory_mode(mem::FrankWolfe.InplaceEmphasis, x::BlockVector, gamma::Real, d::BlockVector)
@inbounds for i in eachindex(x.blocks)
FrankWolfe.muladd_memory_mode(mem, x.blocks[i], gamma, d.blocks[i])
end
return x
end
function FrankWolfe.muladd_memory_mode(mem::FrankWolfe.InplaceEmphasis, d::BlockVector, x::BlockVector, v::BlockVector)
@inbounds for i in eachindex(d.blocks)
FrankWolfe.muladd_memory_mode(mem, d.blocks[i], x.blocks[i], v.blocks[i])
end
return d
end
function FrankWolfe.compute_active_set_iterate!(active_set::FrankWolfe.ActiveSet{<:BlockVector})
@inbounds for i in eachindex(active_set.x.blocks)
@. active_set.x.blocks[i] .= 0
end
for (λi, ai) in active_set
for i in eachindex(active_set.x.blocks)
FrankWolfe.muladd_memory_mode(FrankWolfe.InplaceEmphasis(), active_set.x.blocks[i], -λi, ai.blocks[i])
end
end
return active_set.x
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 5689 | """
compute_line_length(format_string)
Calculates the line length for the table format of a print callback.
"""
function compute_line_length(format_string)
temp = strip(format_string, ['\n'])
temp = replace(temp, "%" => "")
temp = replace(temp, "e" => "")
temp = replace(temp, "i" => "")
temp = replace(temp, "s" => "")
temp = split(temp, " ")
len = sum(parse(Int, i) for i in temp)
return len + 2 + length(temp) - 1
end
"""
print_callback(state,storage)
Handles formating of the callback state into a table format with consistent length independent of state values.
"""
function print_callback(data, format_string; print_header=false, print_footer=false)
print_formatted(fmt, args...) = @eval @printf($fmt, $(args...))
if print_header || print_footer
lenHeaderFooter = compute_line_length(format_string)
end
if print_footer
line = "-"^lenHeaderFooter
@printf("%s\e[s\n", line) # \e[s stores the cursor position at the end of the line
elseif print_header
line = "-"^lenHeaderFooter
@printf("\n%s\n", line)
s_format_string = replace(format_string, "e" => "s")
s_format_string = replace(s_format_string, "i" => "s")
print_formatted(s_format_string, data...)
@printf("%s\e[s\n", line) # \e[s stores the cursor position at the end of the line
else
print_formatted(format_string, data...)
end
end
"""
make_print_callback(callback, print_iter, headers, format_string, format_state)
Default verbose callback for fw_algorithms, that wraps around previous callback.
Prints the state to the console after print_iter iterations.
If the callback to be wrapped is of type nothing, always return true to enforce boolean output for non-nothing callbacks.
"""
function make_print_callback(callback, print_iter, headers, format_string, format_state)
return function callback_with_prints(state, args...)
if (state.step_type == ST_POSTPROCESS || state.step_type == ST_LAST)
if state.t == 0 && state.step_type == ST_LAST
print_callback(headers, format_string, print_header=true)
end
rep = format_state(state, args...)
print_callback(rep, format_string)
print_callback(nothing, format_string, print_footer=true)
flush(stdout)
elseif state.t == 1 ||
mod(state.t, print_iter) == 0 ||
state.step_type == ST_DUALSTEP ||
state.step_type == ST_LAST
if state.t == 1
state = @set state.step_type = ST_INITIAL
print_callback(headers, format_string, print_header=true)
end
rep = format_state(state, args...)
extended_format_string = format_string[1:end-1] * "\e[s" * format_string[end] # Add escape code for storing cursor position before newline
print_callback(rep, extended_format_string)
flush(stdout)
end
if callback === nothing
return true
end
return callback(state, args...)
end
end
function make_print_callback_extension(callback, print_iter, headers, format_string, format_state)
return function callback_with_prints(state, args...)
if (state.step_type == ST_POSTPROCESS || state.step_type == ST_LAST)
if state.t == 0 && state.step_type == ST_LAST
print_callback(headers, format_string, print_header=true)
end
rep = format_state(state, args...)
print("\e[u\e[1A\e[2D") # Move to end of "last"-row
print_callback(rep, format_string)
print("\e[u\e[2D") # Move to end of horizontal line
print_callback(nothing, format_string, print_footer=true)
flush(stdout)
elseif state.t == 1 ||
mod(state.t, print_iter) == 0 ||
state.step_type == ST_DUALSTEP ||
state.step_type == ST_LAST
if state.t == 1
print("\e[u\e[3A") # Move to end of upper horizontal line
line = "-"^compute_line_length(format_string)
@printf("%s\n", line)
print("\e[u\e[2A") # Move to end of the header row
s_format_string = replace(format_string, "e" => "s")
s_format_string = replace(s_format_string, "i" => "s")
@eval @printf($s_format_string, $(headers...))
print("\e[u\e[1A") # Move to end of lower horizontal line
@printf("%s\n\n", line)
end
rep = format_state(state, args...)
print("\e[u") # Move to end of table row
print_callback(rep, format_string)
flush(stdout)
end
if callback === nothing
return true
end
return callback(state, args...)
end
end
"""
make_trajectory_callback(callback, traj_data)
Default trajectory logging callback for fw_algorithms, that wraps around previous callback.
Adds the state to the storage variable.
The state data is only the 5 first fields, usually:
`(t, primal, dual, dual_gap, time)`
If the callback to be wrapped is of type nothing, always return true to enforce boolean output for non-nothing callbacks.
"""
function make_trajectory_callback(callback, traj_data::Vector)
return function callback_with_trajectory(state, args...)
if state.step_type !== ST_LAST || state.step_type !== ST_POSTPROCESS
push!(traj_data, callback_state(state))
end
if callback === nothing
return true
end
return callback(state, args...)
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 1270 |
"""
Emphasis given to the algorithm for memory-saving or not.
The default memory-saving mode may be slower than
OutplaceEmphasis mode for small dimensions.
"""
abstract type MemoryEmphasis end
struct InplaceEmphasis <: MemoryEmphasis end
struct OutplaceEmphasis <: MemoryEmphasis end
@enum StepType begin
ST_INITIAL = 1
ST_REGULAR = 2
ST_LAZY = 3
ST_LAZYSTORAGE = 4
ST_DUALSTEP = 5
ST_AWAY = 6
ST_PAIRWISE = 7
ST_DROP = 8
ST_SIMPLEXDESCENT = 101
ST_LAST = 1000
ST_POSTPROCESS = 1001
end
const steptype_string = (
ST_INITIAL="I",
ST_REGULAR="FW",
ST_LAZY="L",
ST_LAZYSTORAGE="LL",
ST_DUALSTEP="LD",
ST_AWAY="A",
ST_PAIRWISE="P",
ST_DROP="D",
ST_SIMPLEXDESCENT="SD",
ST_LAST="Last",
ST_POSTPROCESS="PP",
)
"""
Main structure created before and passed to the callback in first position.
"""
struct CallbackState{TP,TDV,TDG,XT,VT,DT,TG,FT,GFT,LMO,GT}
t::Int
primal::TP
dual::TDV
dual_gap::TDG
time::Float64
x::XT
v::VT
d::DT
gamma::TG
f::FT
grad!::GFT
lmo::LMO
gradient::GT
step_type::StepType
end
function callback_state(state::CallbackState)
return (state.t, state.primal, state.dual, state.dual_gap, state.time)
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 4162 |
"""
ObjectiveFunction
Represents an objective function optimized by algorithms.
Subtypes of `ObjectiveFunction` must implement at least
* `compute_value(::ObjectiveFunction, x)` for primal value evaluation
* `compute_gradient(::ObjectiveFunction, x)` for gradient evaluation.
and optionally `compute_value_gradient(::ObjectiveFunction, x)` returning the (primal, gradient) pair.
`compute_gradient` may always use the same storage and return a reference to it.
"""
abstract type ObjectiveFunction end
"""
compute_value(f::ObjectiveFunction, x; [kwargs...])
Computes the objective `f` at `x`.
"""
function compute_value end
"""
compute_gradient(f::ObjectiveFunction, x; [kwargs...])
Computes the gradient of `f` at `x`. May return a reference to an internal storage.
"""
function compute_gradient end
"""
compute_value_gradient(f::ObjectiveFunction, x; [kwargs...])
Computes in one call the pair `(value, gradient)` evaluated at `x`.
By default, calls `compute_value` and `compute_gradient` with keywords `kwargs`
passed down to both.
"""
compute_value_gradient(f::ObjectiveFunction, x; kwargs...) =
(compute_value(f, x; kwargs...), compute_gradient(f, x; kwargs...))
"""
SimpleFunctionObjective{F,G,S}
An objective function built from separate primal objective `f(x)` and
in-place gradient function `grad!(storage, x)`.
It keeps an internal storage of type `s` used to evaluate the gradient in-place.
"""
struct SimpleFunctionObjective{F,G,S} <: ObjectiveFunction
f::F
grad!::G
storage::S
end
compute_value(f::SimpleFunctionObjective, x) = f.f(x)
function compute_gradient(f::SimpleFunctionObjective, x)
f.grad!(f.storage, x)
return f.storage
end
"""
StochasticObjective{F, G, XT, S}(f::F, grad!::G, xs::XT, storage::S)
Represents a composite function evaluated with stochastic gradient.
`f(θ, x)` evaluates the loss for a single data point `x` and parameter `θ`.
`grad!(storage, θ, x)` adds to storage the partial gradient with respect to data point `x` at parameter `θ`.
`xs` must be an indexable iterable (`Vector{Vector{Float64}}` for instance).
Functions using a `StochasticObjective` have optional keyword arguments `rng`, `batch_size`
and `full_evaluation` controlling whether the function should be evaluated over all data points.
Note: `grad!` must **not** reset the storage to 0 before adding to it.
"""
struct StochasticObjective{F,G,XT,S} <: ObjectiveFunction
f::F
grad!::G
xs::XT
storage::S
end
function compute_value(
f::StochasticObjective,
θ;
batch_size::Integer=length(f.xs),
rng=Random.GLOBAL_RNG,
full_evaluation=false,
)
(batch_size, rand_indices) = if full_evaluation
(length(f.xs), eachindex(f.xs))
else
(batch_size, rand(rng, eachindex(f.xs), batch_size))
end
return sum(f.f(θ, f.xs[idx]) for idx in rand_indices) / batch_size
end
function compute_gradient(
f::StochasticObjective,
θ;
batch_size::Integer=length(f.xs) ÷ 10 + 1,
rng=Random.GLOBAL_RNG,
full_evaluation=false,
)
(batch_size, rand_indices) = _random_indices(f, batch_size, full_evaluation; rng=rng)
f.storage .= 0
for idx in rand_indices
f.grad!(f.storage, θ, f.xs[idx])
end
f.storage ./= batch_size
return f.storage
end
function compute_value_gradient(
f::StochasticObjective,
θ;
batch_size::Integer=length(f.xs) ÷ 10 + 1,
rng=Random.GLOBAL_RNG,
full_evaluation=false,
)
(batch_size, rand_indices) = _random_indices(f, batch_size, full_evaluation; rng=rng)
# map operation, for each index, computes value and gradient
f_val = zero(eltype(θ))
f.storage .= 0
for idx in rand_indices
@inbounds x = f.xs[idx]
f_val += f.f(θ, x)
f.grad!(f.storage, θ, x)
end
f.storage ./= batch_size
f_val /= batch_size
return (f_val, f.storage)
end
function _random_indices(
f::StochasticObjective,
batch_size::Integer,
full_evaluation::Bool;
rng=Random.GLOBAL_RNG,
)
if full_evaluation
return (length(f.xs), eachindex(f.xs))
end
return (batch_size, rand(rng, eachindex(f.xs), batch_size))
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 21336 |
"""
frank_wolfe(f, grad!, lmo, x0; ...)
Simplest form of the Frank-Wolfe algorithm.
Returns a tuple `(x, v, primal, dual_gap, traj_data)` with:
- `x` final iterate
- `v` last vertex from the LMO
- `primal` primal value `f(x)`
- `dual_gap` final Frank-Wolfe gap
- `traj_data` vector of trajectory information.
"""
function frank_wolfe(
f,
grad!,
lmo,
x0;
line_search::LineSearchMethod=Adaptive(),
momentum=nothing,
epsilon=1e-7,
max_iteration=10000,
print_iter=1000,
trajectory=false,
verbose=false,
memory_mode::MemoryEmphasis=InplaceEmphasis(),
gradient=nothing,
callback=nothing,
traj_data=[],
timeout=Inf,
linesearch_workspace=nothing,
dual_gap_compute_frequency=1,
)
# header and format string for output of the algorithm
headers = ["Type", "Iteration", "Primal", "Dual", "Dual Gap", "Time", "It/sec"]
format_string = "%6s %13s %14e %14e %14e %14e %14e\n"
function format_state(state)
rep = (
steptype_string[Symbol(state.step_type)],
string(state.t),
Float64(state.primal),
Float64(state.primal - state.dual_gap),
Float64(state.dual_gap),
state.time,
state.t / state.time,
)
return rep
end
t = 0
dual_gap = Inf
primal = Inf
v = []
x = x0
step_type = ST_REGULAR
if trajectory
callback = make_trajectory_callback(callback, traj_data)
end
if verbose
callback = make_print_callback(callback, print_iter, headers, format_string, format_state)
end
time_start = time_ns()
if (momentum !== nothing && line_search isa Union{Shortstep,Adaptive,Backtracking})
@warn("Momentum-averaged gradients should usually be used with agnostic stepsize rules.",)
end
if verbose
println("\nVanilla Frank-Wolfe Algorithm.")
NumType = eltype(x0)
println(
"MEMORY_MODE: $memory_mode STEPSIZE: $line_search EPSILON: $epsilon MAXITERATION: $max_iteration TYPE: $NumType",
)
grad_type = typeof(gradient)
println("MOMENTUM: $momentum GRADIENTTYPE: $grad_type")
println("LMO: $(typeof(lmo))")
if memory_mode isa InplaceEmphasis
@info("In memory_mode memory iterates are written back into x0!")
end
end
if memory_mode isa InplaceEmphasis && !isa(x, Union{Array,SparseArrays.AbstractSparseArray})
# if integer, convert element type to most appropriate float
if eltype(x) <: Integer
x = copyto!(similar(x, float(eltype(x))), x)
else
x = copyto!(similar(x), x)
end
end
# instanciating container for gradient
if gradient === nothing
gradient = collect(x)
end
first_iter = true
if linesearch_workspace === nothing
linesearch_workspace = build_linesearch_workspace(line_search, x, gradient)
end
# container for direction
d = similar(x)
gtemp = momentum === nothing ? d : similar(x)
while t <= max_iteration && dual_gap >= max(epsilon, eps(float(typeof(dual_gap))))
#####################
# managing time and Ctrl-C
#####################
time_at_loop = time_ns()
if t == 0
time_start = time_at_loop
end
# time is measured at beginning of loop for consistency throughout all algorithms
tot_time = (time_at_loop - time_start) / 1e9
if timeout < Inf
if tot_time ≥ timeout
if verbose
@info "Time limit reached"
end
break
end
end
#####################
if momentum === nothing || first_iter
grad!(gradient, x)
if momentum !== nothing
gtemp .= gradient
end
else
grad!(gtemp, x)
@memory_mode(memory_mode, gradient = (momentum * gradient) + (1 - momentum) * gtemp)
end
v = if first_iter
compute_extreme_point(lmo, gradient)
else
compute_extreme_point(lmo, gradient, v=v)
end
first_iter = false
# go easy on runtime - only compute primal and dual if needed
compute_iter = (
(mod(t, print_iter) == 0 && verbose) ||
callback !== nothing ||
line_search isa Shortstep
)
if compute_iter
primal = f(x)
end
if t % dual_gap_compute_frequency == 0 || compute_iter
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
end
d = muladd_memory_mode(memory_mode, d, x, v)
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
1.0,
linesearch_workspace,
memory_mode,
)
t = t + 1
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
if callback(state) === false
break
end
end
x = muladd_memory_mode(memory_mode, x, gamma, d)
end
# recompute everything once for final verfication / do not record to trajectory though for now!
# this is important as some variants do not recompute f(x) and the dual_gap regularly but only when reporting
# hence the final computation.
step_type = ST_LAST
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient, v=v)
primal = f(x)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
tot_time = (time_ns() - time_start) / 1.0e9
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
1.0,
linesearch_workspace,
memory_mode,
)
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
callback(state)
end
return (x=x, v=v, primal=primal, dual_gap=dual_gap, traj_data=traj_data)
end
"""
lazified_conditional_gradient(f, grad!, lmo_base, x0; ...)
Similar to [`FrankWolfe.frank_wolfe`](@ref) but lazyfying the LMO:
each call is stored in a cache, which is looked up first for a good-enough direction.
The cache used is a [`FrankWolfe.MultiCacheLMO`](@ref) or a [`FrankWolfe.VectorCacheLMO`](@ref)
depending on whether the provided `cache_size` option is finite.
"""
function lazified_conditional_gradient(
f,
grad!,
lmo_base,
x0;
line_search::LineSearchMethod=Adaptive(),
lazy_tolerance=2.0,
cache_size=Inf,
greedy_lazy=false,
epsilon=1e-7,
max_iteration=10000,
print_iter=1000,
trajectory=false,
verbose=false,
memory_mode::MemoryEmphasis=InplaceEmphasis(),
gradient=nothing,
callback=nothing,
traj_data=[],
VType=typeof(x0),
timeout=Inf,
linesearch_workspace=nothing,
)
# format string for output of the algorithm
format_string = "%6s %13s %14e %14e %14e %14e %14e %14i\n"
headers = ["Type", "Iteration", "Primal", "Dual", "Dual Gap", "Time", "It/sec", "Cache Size"]
function format_state(state, args...)
rep = (
steptype_string[Symbol(state.step_type)],
string(state.t),
Float64(state.primal),
Float64(state.primal - state.dual_gap),
Float64(state.dual_gap),
state.time,
state.t / state.time,
length(state.lmo),
)
return rep
end
lmo = VectorCacheLMO{typeof(lmo_base),VType}(lmo_base)
if isfinite(cache_size)
Base.sizehint!(lmo.vertices, cache_size)
end
t = 0
dual_gap = Inf
primal = Inf
v = []
x = x0
phi = Inf
step_type = ST_REGULAR
if trajectory
callback = make_trajectory_callback(callback, traj_data)
end
if verbose
callback = make_print_callback(callback, print_iter, headers, format_string, format_state)
end
time_start = time_ns()
if line_search isa Agnostic || line_search isa Nonconvex
@warn("Lazification is not known to converge with open-loop step size strategies.")
end
if gradient === nothing
gradient = collect(x)
end
if verbose
println("\nLazified Conditional Gradient (Frank-Wolfe + Lazification).")
NumType = eltype(x0)
println(
"MEMORY_MODE: $memory_mode STEPSIZE: $line_search EPSILON: $epsilon MAXITERATION: $max_iteration lazy_tolerance: $lazy_tolerance TYPE: $NumType",
)
grad_type = typeof(gradient)
println("GRADIENTTYPE: $grad_type CACHESIZE $cache_size GREEDYCACHE: $greedy_lazy")
println("LMO: $(typeof(lmo))")
if memory_mode isa InplaceEmphasis
@info("In memory_mode memory iterates are written back into x0!")
end
end
if memory_mode isa InplaceEmphasis && !isa(x, Union{Array,SparseArrays.AbstractSparseArray})
if eltype(x) <: Integer
x = copyto!(similar(x, float(eltype(x))), x)
else
x = copyto!(similar(x), x)
end
end
# container for direction
d = similar(x)
if linesearch_workspace === nothing
linesearch_workspace = build_linesearch_workspace(line_search, x, gradient)
end
while t <= max_iteration && dual_gap >= max(epsilon, eps(float(eltype(x))))
#####################
# managing time and Ctrl-C
#####################
time_at_loop = time_ns()
if t == 0
time_start = time_at_loop
end
# time is measured at beginning of loop for consistency throughout all algorithms
tot_time = (time_at_loop - time_start) / 1e9
if timeout < Inf
if tot_time ≥ timeout
if verbose
@info "Time limit reached"
end
break
end
end
#####################
grad!(gradient, x)
threshold = fast_dot(x, gradient) - phi / lazy_tolerance
# go easy on the memory - only compute if really needed
if ((mod(t, print_iter) == 0 && verbose) || callback !== nothing)
primal = f(x)
end
v = compute_extreme_point(lmo, gradient, threshold=threshold, greedy=greedy_lazy)
step_type = ST_LAZY
if fast_dot(v, gradient) > threshold
step_type = ST_DUALSTEP
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
phi = min(dual_gap, phi / 2)
end
d = muladd_memory_mode(memory_mode, d, x, v)
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
1.0,
linesearch_workspace,
memory_mode,
)
t += 1
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
if callback(state) === false
break
end
end
x = muladd_memory_mode(memory_mode, x, gamma, d)
end
# recompute everything once for final verfication / do not record to trajectory though for now!
# this is important as some variants do not recompute f(x) and the dual_gap regularly but only when reporting
# hence the final computation.
step_type = ST_LAST
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient)
primal = f(x)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
tot_time = (time_ns() - time_start) / 1.0e9
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
1.0,
linesearch_workspace,
memory_mode,
)
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
callback(state)
end
return (x=x, v=v, primal=primal, dual_gap=dual_gap, traj_data=traj_data)
end
"""
stochastic_frank_wolfe(f::StochasticObjective, lmo, x0; ...)
Stochastic version of Frank-Wolfe, evaluates the objective and gradient stochastically,
implemented through the [`FrankWolfe.StochasticObjective`](@ref) interface.
Keyword arguments include `batch_size` to pass a fixed `batch_size`
or a `batch_iterator` implementing
`batch_size = FrankWolfe.batchsize_iterate(batch_iterator)` for algorithms like
Variance-reduced and projection-free stochastic optimization, E Hazan, H Luo, 2016.
Similarly, a constant `momentum` can be passed or replaced by a `momentum_iterator`
implementing `momentum = FrankWolfe.momentum_iterate(momentum_iterator)`.
"""
function stochastic_frank_wolfe(
f::StochasticObjective,
lmo,
x0;
line_search::LineSearchMethod=Nonconvex(),
momentum_iterator=nothing,
momentum=nothing,
epsilon=1e-7,
max_iteration=10000,
print_iter=1000,
trajectory=false,
verbose=false,
memory_mode::MemoryEmphasis=InplaceEmphasis(),
rng=Random.GLOBAL_RNG,
batch_size=length(f.xs) ÷ 10 + 1,
batch_iterator=nothing,
full_evaluation=false,
callback=nothing,
traj_data=[],
timeout=Inf,
linesearch_workspace=nothing,
)
# format string for output of the algorithm
format_string = "%6s %13s %14e %14e %14e %14e %14e %6i\n"
headers = ("Type", "Iteration", "Primal", "Dual", "Dual Gap", "Time", "It/sec", "Batch")
function format_state(state, batch_size)
rep = (
steptype_string[Symbol(state.step_type)],
string(state.t),
Float64(state.primal),
Float64(state.primal - state.dual_gap),
Float64(state.dual_gap),
state.time,
state.t / state.time,
batch_size,
)
return rep
end
t = 0
dual_gap = Inf
primal = Inf
v = []
x = x0
d = similar(x)
step_type = ST_REGULAR
if trajectory
callback = make_trajectory_callback(callback, traj_data)
end
if verbose
callback = make_print_callback(callback, print_iter, headers, format_string, format_state)
end
time_start = time_ns()
if line_search == Shortstep && L == Inf
println("FATAL: Lipschitz constant not set. Prepare to blow up spectacularly.")
end
if line_search == FixedStep && gamma0 == 0
println("FATAL: gamma0 not set. We are not going to move a single bit.")
end
if momentum_iterator === nothing && momentum !== nothing
momentum_iterator = ConstantMomentumIterator(momentum)
end
if batch_iterator === nothing
batch_iterator = ConstantBatchIterator(batch_size)
end
if verbose
println("\nStochastic Frank-Wolfe Algorithm.")
NumType = eltype(x0)
println(
"MEMORY_MODE: $memory_mode STEPSIZE: $line_search EPSILON: $epsilon max_iteration: $max_iteration TYPE: $NumType",
)
println(
"GRADIENTTYPE: $(typeof(f.storage)) MOMENTUM: $(momentum_iterator !== nothing) batch policy: $(typeof(batch_iterator)) ",
)
println("LMO: $(typeof(lmo))")
if memory_mode isa InplaceEmphasis
@info("In memory_mode memory iterates are written back into x0!")
end
end
if memory_mode isa InplaceEmphasis && !isa(x, Union{Array,SparseArrays.AbstractSparseArray})
if eltype(x) <: Integer
x = copyto!(similar(x, float(eltype(x))), x)
else
x = copyto!(similar(x), x)
end
end
first_iter = true
gradient = 0
if linesearch_workspace === nothing
linesearch_workspace = build_linesearch_workspace(line_search, x, gradient)
end
while t <= max_iteration && dual_gap >= max(epsilon, eps(float(typeof(dual_gap))))
#####################
# managing time and Ctrl-C
#####################
time_at_loop = time_ns()
if t == 0
time_start = time_at_loop
end
# time is measured at beginning of loop for consistency throughout all algorithms
tot_time = (time_at_loop - time_start) / 1e9
if timeout < Inf
if tot_time ≥ timeout
if verbose
@info "Time limit reached"
end
break
end
end
#####################
batch_size = batchsize_iterate(batch_iterator)
if momentum_iterator === nothing
gradient = compute_gradient(
f,
x,
rng=rng,
batch_size=batch_size,
full_evaluation=full_evaluation,
)
elseif first_iter
gradient = copy(
compute_gradient(
f,
x,
rng=rng,
batch_size=batch_size,
full_evaluation=full_evaluation,
),
)
else
momentum = momentum_iterate(momentum_iterator)
compute_gradient(f, x, rng=rng, batch_size=batch_size, full_evaluation=full_evaluation)
# gradient = momentum * gradient + (1 - momentum) * f.storage
LinearAlgebra.mul!(gradient, LinearAlgebra.I, f.storage, 1 - momentum, momentum)
end
first_iter = false
v = compute_extreme_point(lmo, gradient)
# go easy on the memory - only compute if really needed
if (mod(t, print_iter) == 0 && verbose) ||
callback !== nothing ||
!(line_search isa Agnostic || line_search isa Nonconvex || line_search isa FixedStep)
primal = compute_value(f, x, full_evaluation=true)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
end
d = muladd_memory_mode(memory_mode, d, x, v)
# note: only linesearch methods that do not require full evaluations are supported
# so nothing is passed as function
gamma = perform_line_search(
line_search,
t,
nothing,
nothing,
gradient,
x,
d,
1.0,
linesearch_workspace,
memory_mode,
)
t += 1
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
d,
gamma,
f,
nothing,
lmo,
gradient,
step_type,
)
if callback(state, batch_size) === false
break
end
end
x = muladd_memory_mode(memory_mode, x, gamma, d)
end
# recompute everything once for final verfication / no additional callback call
# this is important as some variants do not recompute f(x) and the dual_gap regularly but only when reporting
# hence the final computation.
# last computation done with full evaluation for exact gradient
(primal, gradient) = compute_value_gradient(f, x, full_evaluation=true)
v = compute_extreme_point(lmo, gradient)
# @show (gradient, primal)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
step_type = ST_LAST
d = muladd_memory_mode(memory_mode, d, x, v)
gamma = perform_line_search(
line_search,
t,
nothing,
nothing,
gradient,
x,
d,
1.0,
linesearch_workspace,
memory_mode,
)
tot_time = (time_ns() - time_start) / 1e9
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
(time_ns() - time_start) / 1e9,
x,
v,
d,
gamma,
f,
nothing,
lmo,
gradient,
step_type,
)
callback(state, batch_size)
end
return (x=x, v=v, primal=primal, dual_gap=dual_gap, traj_data=traj_data)
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 26772 |
"""
Line search method to apply once the direction is computed.
A `LineSearchMethod` must implement
```
perform_line_search(ls::LineSearchMethod, t, f, grad!, gradient, x, d, gamma_max, workspace)
```
with `d = x - v`.
It may also implement `build_linesearch_workspace(x, gradient)` which creates a
workspace structure that is passed as last argument to `perform_line_search`.
"""
abstract type LineSearchMethod end
# default printing for LineSearchMethod is just showing the type
Base.print(io::IO, ls::LineSearchMethod) = print(io, split(string(typeof(ls)), ".")[end])
"""
perform_line_search(ls::LineSearchMethod, t, f, grad!, gradient, x, d, gamma_max, workspace)
Returns the step size `gamma` for step size strategy `ls`.
"""
function perform_line_search end
build_linesearch_workspace(::LineSearchMethod, x, gradient) = nothing
"""
Computes step size: `l/(l + t)` at iteration `t`, given `l > 0`.
Using `l > 2` leads to faster convergence rates than l = 2 over strongly and some uniformly convex set.
> Accelerated Affine-Invariant Convergence Rates of the Frank-Wolfe Algorithm with Open-Loop Step-Sizes, Wirth, Peña, Pokutta (2023), https://arxiv.org/abs/2310.04096
See also the paper that introduced the study of open-loop step-sizes with l > 2:
> Acceleration of Frank-Wolfe Algorithms with Open-Loop Step-Sizes, Wirth, Kerdreux, Pokutta, (2023), https://arxiv.org/abs/2205.12838
Fixing l = -1, results in the step size gamma_t = (2 + log(t+1)) / (t + 2 + log(t+1))
# S. Pokutta "The Frank-Wolfe algorith: a short introduction" (2023), https://arxiv.org/abs/2311.05313
"""
struct Agnostic{T<:Real} <: LineSearchMethod
l::Int
end
Agnostic() = Agnostic{Float64}(2)
Agnostic(l::Int) = Agnostic{Float64}(l)
Agnostic{T}() where {T} = Agnostic{T}(2)
perform_line_search(
ls::Agnostic{<:Rational},
t,
f,
g!,
gradient,
x,
d,
gamma_max,
workspace,
memory_mode::MemoryEmphasis,
) = ls.l // (t + ls.l)
function perform_line_search(
ls::Agnostic{T},
t,
f,
g!,
gradient,
x,
d,
gamma_max,
workspace,
memory_mode::MemoryEmphasis,
) where {T}
return if ls.l == -1
T((2 + log(t + 1)) / (t + 2 + log(t + 1)))
else
T(ls.l / (t + ls.l))
end
end
Base.print(io::IO, ls::Agnostic) = print(io, "Agnostic($(ls.l))")
"""
Computes step size: `g(t)/(t + g(t))` at iteration `t`, given `g: R_{>= 0} -> R_{>= 0}`.
Defaults to the best open-loop step-size gamma_t = (2 + log(t+1)) / (t + 2 + log(t+1))
> S. Pokutta "The Frank-Wolfe algorith: a short introduction" (2023), https://arxiv.org/abs/2311.05313
This step-size is as fast as the step-size gamma_t = 2 / (t + 2) up to polylogarithmic factors. Further, over strongly convex and some uniformly convex sets, it is faster than any traditional step-size gamma_t = l / (t + l) for any l in N.
"""
struct GeneralizedAgnostic{T<:Real,F<:Function} <: LineSearchMethod
g::F
end
function GeneralizedAgnostic()
g(x) = 2 + log(x + 1)
return GeneralizedAgnostic{Float64,typeof(g)}(g)
end
GeneralizedAgnostic(g) = GeneralizedAgnostic{Float64,typeof(g)}(g)
function perform_line_search(
ls::GeneralizedAgnostic{T,F},
t,
f,
g!,
gradient,
x,
d,
gamma_max,
workspace,
memory_mode::MemoryEmphasis,
) where {T,F}
gamma = T(ls.g(t) / (t + ls.g(t)))
return gamma
end
Base.print(io::IO, ls::GeneralizedAgnostic) = print(io, "GeneralizedAgnostic($(ls.g))")
"""
Computes step size: `1/sqrt(t + 1)`.
"""
struct Nonconvex{T} <: LineSearchMethod end
Nonconvex() = Nonconvex{Float64}()
perform_line_search(
::Nonconvex{T},
t,
f,
g!,
gradient,
x,
d,
gamma_max,
workspace,
memory_mode,
) where {T} = T(1 / sqrt(t + 1))
Base.print(io::IO, ::Nonconvex) = print(io, "Nonconvex")
"""
Computes the 'Short step' step size:
`dual_gap / (L * norm(x - v)^2)`,
where `L` is the Lipschitz constant of the gradient, `x` is the
current iterate, and `v` is the current Frank-Wolfe vertex.
"""
struct Shortstep{T} <: LineSearchMethod
L::T
function Shortstep(L::T) where {T}
if !isfinite(L)
@warn("Shortstep with non-finite Lipschitz constant will not move")
end
return new{T}(L)
end
end
function perform_line_search(
line_search::Shortstep,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
workspace,
memory_mode,
)
dd = fast_dot(d, d)
if dd <= eps(float(dd))
return dd
end
return min(max(fast_dot(gradient, d) * inv(line_search.L * dd), 0), gamma_max)
end
Base.print(io::IO, ::Shortstep) = print(io, "Shortstep")
"""
Fixed step size strategy. The step size can still be truncated by the `gamma_max` argument.
"""
struct FixedStep{T} <: LineSearchMethod
gamma0::T
end
function perform_line_search(
line_search::FixedStep,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
workspace,
memory_mode,
)
return min(line_search.gamma0, gamma_max)
end
Base.print(io::IO, ::FixedStep) = print(io, "FixedStep")
"""
Goldenratio
Simple golden-ratio based line search
[Golden Section Search](https://en.wikipedia.org/wiki/Golden-section_search),
based on [Combettes, Pokutta (2020)](http://proceedings.mlr.press/v119/combettes20a/combettes20a.pdf)
code and adapted.
"""
struct Goldenratio{T} <: LineSearchMethod
tol::T
end
Goldenratio() = Goldenratio(1e-7)
struct GoldenratioWorkspace{XT,GT}
y::XT
left::XT
right::XT
new_vec::XT
probe::XT
gradient::GT
end
function build_linesearch_workspace(::Goldenratio, x::XT, gradient::GT) where {XT,GT}
return GoldenratioWorkspace{XT,GT}(
similar(x),
similar(x),
similar(x),
similar(x),
similar(x),
similar(gradient),
)
end
function perform_line_search(
line_search::Goldenratio,
_,
f,
grad!,
gradient,
x,
d,
gamma_max,
workspace::GoldenratioWorkspace,
memory_mode,
)
# restrict segment of search to [x, y]
@. workspace.y = x - gamma_max * d
@. workspace.left = x
@. workspace.right = workspace.y
dgx = fast_dot(d, gradient)
grad!(workspace.gradient, workspace.y)
dgy = fast_dot(d, workspace.gradient)
# if the minimum is at an endpoint
if dgx * dgy >= 0
if f(workspace.y) <= f(x)
return gamma_max
else
return zero(eltype(d))
end
end
# apply golden-section method to segment
gold = (1 + sqrt(5)) / 2
improv = Inf
while improv > line_search.tol
f_old_left = f(workspace.left)
f_old_right = f(workspace.right)
@. workspace.new_vec = workspace.left + (workspace.right - workspace.left) / (1 + gold)
@. workspace.probe = workspace.new_vec + (workspace.right - workspace.new_vec) / 2
if f(workspace.probe) <= f(workspace.new_vec)
workspace.left .= workspace.new_vec
# right unchanged
else
workspace.right .= workspace.probe
# left unchanged
end
improv = norm(f(workspace.right) - f_old_right) + norm(f(workspace.left) - f_old_left)
end
# compute step size gamma
gamma = zero(eltype(d))
for i in eachindex(d)
if d[i] != 0
x_min = (workspace.left[i] + workspace.right[i]) / 2
gamma = (x[i] - x_min) / d[i]
break
end
end
return gamma
end
Base.print(io::IO, ::Goldenratio) = print(io, "Goldenratio")
"""
Backtracking(limit_num_steps, tol, tau)
Backtracking line search strategy, see
[Pedregosa, Negiar, Askari, Jaggi (2018)](https://arxiv.org/pdf/1806.05123).
"""
struct Backtracking{T} <: LineSearchMethod
limit_num_steps::Int
tol::T
tau::T
end
build_linesearch_workspace(::Backtracking, x, gradient) = similar(x)
function Backtracking(; limit_num_steps=20, tol=1e-10, tau=0.5)
return Backtracking(limit_num_steps, tol, tau)
end
function perform_line_search(
line_search::Backtracking,
_,
f,
grad!,
gradient,
x,
d,
gamma_max,
storage,
memory_mode,
)
gamma = gamma_max * one(line_search.tau)
i = 0
dot_gdir = fast_dot(gradient, d)
if dot_gdir ≤ 0
@warn "Non-improving"
return zero(gamma)
end
old_val = f(x)
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
new_val = f(storage)
while new_val - old_val > -line_search.tol * gamma * dot_gdir
if i > line_search.limit_num_steps
if old_val - new_val >= 0
return gamma
else
return zero(gamma)
end
end
gamma *= line_search.tau
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
new_val = f(storage)
i += 1
end
return gamma
end
Base.print(io::IO, ::Backtracking) = print(io, "Backtracking")
"""
Secant(limit_num_steps, tol, domain_oracle)
Secant line search strategy, which iteratively refines the step size using the secant method.
This method is geared towards problems with self-concordant functions (but might require extra structure)
and potentially faster than the backtracking line search.
The order of convergence is superlinear with exponent 1.618 (Golden Ratio) but not quite quadratic.
Convergence is not guaranteed in general.
# Arguments
- `limit_num_steps::Int`: Maximum number of iterations for the secant method. (default 40)
- `tol::Float64`: Tolerance for convergence. (default 1e-8)
- `domain_oracle::Function`, returns true if the argument x is in the domain of the objective function f.
# References
- [Secant Method](https://en.wikipedia.org/wiki/Secant_method)
"""
struct Secant{F,LSM<:LineSearchMethod} <: LineSearchMethod
inner_ls::LSM
limit_num_steps::Int
tol::Float64
domain_oracle::F
end
function Secant(limit_num_steps, tol)
return Secant(Backtracking(), limit_num_steps, tol, x -> true)
end
function Secant(;inner_ls=Backtracking(), limit_num_steps=40, tol=1e-8, domain_oracle=(x -> true))
return Secant(inner_ls, limit_num_steps, tol, domain_oracle)
end
mutable struct SecantWorkspace{XT,GT, IWS}
inner_ws::IWS
x::XT
gradient::GT
last_gamma::Float64
end
function build_linesearch_workspace(ls::Secant, x, gradient)
inner_ws = build_linesearch_workspace(ls.inner_ls, x, gradient)
return SecantWorkspace(inner_ws, similar(x), similar(gradient), 1.0) # Initialize last_gamma to 1.0
end
function perform_line_search(
line_search::Secant,
_,
f,
grad!,
gradient,
x,
d,
gamma_max,
workspace::SecantWorkspace,
memory_mode,
)
dot_gdir = dot(gradient, d)
gamma = min(workspace.last_gamma, gamma_max) # Start from last gamma, but don't exceed gamma_max
storage, grad_storage = workspace.x, workspace.gradient
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
while !line_search.domain_oracle(storage)
gamma_max /= 2
gamma = min(gamma, gamma_max)
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
end
new_val = f(storage)
best_gamma = gamma
best_val = new_val
i = 1
gamma_prev = zero(best_gamma)
while abs(dot_gdir) > line_search.tol
if i > line_search.limit_num_steps
workspace.last_gamma = best_gamma # Update last_gamma before returning
return best_gamma
end
grad!(grad_storage, storage)
dot_gdir_new = fast_dot(grad_storage, d)
if dot_gdir_new ≈ dot_gdir
workspace.last_gamma = best_gamma # Update last_gamma before returning
return best_gamma
end
gamma_new = gamma - dot_gdir_new * (gamma - gamma_prev) / (dot_gdir_new - dot_gdir)
gamma_prev = gamma
gamma = clamp(gamma_new, 0, gamma_max) # Ensure gamma stays in [0, gamma_max]
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
new_val = f(storage)
if new_val < best_val
best_val = new_val
best_gamma = gamma
end
dot_gdir = dot_gdir_new
i += 1
end
if abs(dot_gdir) > line_search.tol
gamma = perform_line_search(
line_search.inner_ls,
0,
f,
grad!,
gradient,
x,
d,
gamma_max,
workspace.inner_ws,
memory_mode,
)
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
new_val = f(storage)
@assert new_val <= best_val
best_gamma = gamma
end
workspace.last_gamma = best_gamma # Update last_gamma before returning
return best_gamma
end
Base.print(io::IO, ::Secant) = print(io, "Secant")
"""
Slight modification of the
Adaptive Step Size strategy from [Pedregosa, Negiar, Askari, Jaggi (2018)](https://arxiv.org/abs/1806.05123)
```math
f(x_t + \\gamma_t (x_t - v_t)) - f(x_t) \\leq - \\alpha \\gamma_t \\langle \\nabla f(x_t), x_t - v_t \\rangle + \\alpha^2 \\frac{\\gamma_t^2 \\|x_t - v_t\\|^2}{2} M ~.
```
The parameter `alpha ∈ (0,1]` relaxes the original smoothness condition to mitigate issues with nummerical errors. Its default value is `0.5`.
The `Adaptive` struct keeps track of the Lipschitz constant estimate `L_est`.
The keyword argument `relaxed_smoothness` allows testing with an alternative smoothness condition,
```math
\\langle \\nabla f(x_t + \\gamma_t (x_t - v_t) ) - \\nabla f(x_t), x_t - v_t \\rangle \\leq \\gamma_t M \\|x_t - v_t\\|^2 ~.
```
This condition yields potentially smaller and more stable estimations of the Lipschitz constant
while being more computationally expensive due to the additional gradient computation.
It is also the fallback when the Lipschitz constant estimation fails due to numerical errors.
`perform_line_search` also has a `should_upgrade` keyword argument on
whether there should be a temporary upgrade to `BigFloat` for extended precision.
"""
mutable struct AdaptiveZerothOrder{T,TT} <: LineSearchMethod
eta::T
tau::TT
L_est::T
max_estimate::T
alpha::T
verbose::Bool
relaxed_smoothness::Bool
end
AdaptiveZerothOrder(eta::T, tau::TT) where {T,TT} =
AdaptiveZerothOrder{T,TT}(eta, tau, T(Inf), T(1e10), T(0.5), true, false)
AdaptiveZerothOrder(;
eta=0.9,
tau=2,
L_est=Inf,
max_estimate=1e10,
alpha=0.5,
verbose=true,
relaxed_smoothness=false,
) = AdaptiveZerothOrder(eta, tau, L_est, max_estimate, alpha, verbose, relaxed_smoothness)
struct AdaptiveZerothOrderWorkspace{XT,BT}
x::XT
xbig::BT
end
build_linesearch_workspace(::AdaptiveZerothOrder, x, gradient) =
AdaptiveZerothOrderWorkspace(similar(x), big.(x))
function perform_line_search(
line_search::AdaptiveZerothOrder,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
storage::AdaptiveZerothOrderWorkspace,
memory_mode::MemoryEmphasis;
should_upgrade::Val=Val{false}(),
)
if norm(d) ≤ length(d) * eps(float(eltype(d)))
if should_upgrade isa Val{true}
return big(zero(promote_type(eltype(d), eltype(gradient))))
else
return zero(promote_type(eltype(d), eltype(gradient)))
end
end
x_storage = storage.x
if !isfinite(line_search.L_est)
epsilon_step = min(1e-3, gamma_max)
gradient_stepsize_estimation = similar(gradient)
x_storage = muladd_memory_mode(memory_mode, x_storage, x, epsilon_step, d)
grad!(gradient_stepsize_estimation, x_storage)
line_search.L_est = norm(gradient - gradient_stepsize_estimation) / (epsilon_step * norm(d))
end
M = line_search.eta * line_search.L_est
(dot_dir, ndir2, x_storage) = _upgrade_accuracy_adaptive(gradient, d, storage, should_upgrade)
γ = min(max(dot_dir / (M * ndir2), 0), gamma_max)
x_storage = muladd_memory_mode(memory_mode, x_storage, x, γ, d)
niter = 0
α = line_search.alpha
clipping = false
gradient_storage = similar(gradient)
while f(x_storage) - f(x) > -γ * α * dot_dir + α^2 * γ^2 * ndir2 * M / 2 + eps(float(γ)) &&
γ ≥ 100 * eps(float(γ))
# Additional smoothness condition
if line_search.relaxed_smoothness
grad!(gradient_storage, x_storage)
if fast_dot(gradient, d) - fast_dot(gradient_storage, d) <=
γ * M * ndir2 + eps(float(γ))
break
end
end
M *= line_search.tau
γ = min(max(dot_dir / (M * ndir2), 0), gamma_max)
x_storage = muladd_memory_mode(memory_mode, x_storage, x, γ, d)
niter += 1
if M > line_search.max_estimate
# if this occurs, we hit numerical troubles
# if we were not using the relaxed smoothness, we try it first as a stable fallback
# note that the smoothness estimate is not updated at this iteration.
if !line_search.relaxed_smoothness
linesearch_fallback = deepcopy(line_search)
linesearch_fallback.relaxed_smoothness = true
return perform_line_search(
linesearch_fallback,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
storage,
memory_mode;
should_upgrade=should_upgrade,
)
end
# if we are already in relaxed smoothness, produce a warning:
# one might see negative progess, cycling, or stalling.
# Potentially upgrade accuracy or use an alternative line search strategy
if line_search.verbose
@warn "Smoothness estimate run away -> hard clipping. Convergence might be not guaranteed."
end
clipping = true
break
end
end
if !clipping
line_search.L_est = M
end
γ = min(max(dot_dir / (line_search.L_est * ndir2), 0), gamma_max)
return γ
end
Base.print(io::IO, ::AdaptiveZerothOrder) = print(io, "AdaptiveZerothOrder")
function _upgrade_accuracy_adaptive(gradient, direction, storage, ::Val{true})
direction_big = big.(direction)
dot_dir = fast_dot(big.(gradient), direction_big)
ndir2 = norm(direction_big)^2
return (dot_dir, ndir2, storage.xbig)
end
function _upgrade_accuracy_adaptive(gradient, direction, storage, ::Val{false})
dot_dir = fast_dot(gradient, direction)
ndir2 = norm(direction)^2
return (dot_dir, ndir2, storage.x)
end
"""
Modified adaptive line search test from:
> S. Pokutta "The Frank-Wolfe algorith: a short introduction" (2023), preprint, https://arxiv.org/abs/2311.05313
It replaces the original test implemented in the AdaptiveZerothOrder line search based on:
> Pedregosa, F., Negiar, G., Askari, A., and Jaggi, M. (2020). "Linearly convergent Frank–Wolfe with backtracking line-search", Proceedings of AISTATS.
"""
mutable struct Adaptive{T,TT} <: LineSearchMethod
eta::T
tau::TT
L_est::T
max_estimate::T
verbose::Bool
relaxed_smoothness::Bool
end
Adaptive(eta::T, tau::TT) where {T,TT} =
Adaptive{T,TT}(eta, tau, T(Inf), T(1e10), T(0.5), true, false)
Adaptive(; eta=0.9, tau=2, L_est=Inf, max_estimate=1e10, verbose=true, relaxed_smoothness=false) =
Adaptive(eta, tau, L_est, max_estimate, verbose, relaxed_smoothness)
struct AdaptiveWorkspace{XT,BT}
x::XT
xbig::BT
gradient_storage::XT
end
build_linesearch_workspace(::Adaptive, x, gradient) =
AdaptiveWorkspace(similar(x), big.(x), similar(x))
function perform_line_search(
line_search::Adaptive,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
storage::AdaptiveWorkspace,
memory_mode::MemoryEmphasis;
should_upgrade::Val=Val{false}(),
)
if norm(d) ≤ length(d) * eps(float(real(eltype(d))))
if should_upgrade isa Val{true}
return big(zero(promote_type(eltype(d), eltype(gradient))))
else
return zero(promote_type(eltype(d), eltype(gradient)))
end
end
x_storage = storage.x
if !isfinite(line_search.L_est)
epsilon_step = min(1e-3, gamma_max)
gradient_stepsize_estimation = storage.gradient_storage
x_storage = muladd_memory_mode(memory_mode, x_storage, x, epsilon_step, d)
grad!(gradient_stepsize_estimation, x_storage)
line_search.L_est = norm(gradient - gradient_stepsize_estimation) / (epsilon_step * norm(d))
end
M = line_search.eta * line_search.L_est
(dot_dir, ndir2, x_storage) = _upgrade_accuracy_adaptive(gradient, d, storage, should_upgrade)
γ = min(max(dot_dir / (M * ndir2), 0), gamma_max)
x_storage = muladd_memory_mode(memory_mode, x_storage, x, γ, d)
niter = 0
clipping = false
gradient_storage = storage.gradient_storage
grad!(gradient_storage, x_storage)
while 0 > fast_dot(gradient_storage, d) && γ ≥ 100 * eps(float(γ))
M *= line_search.tau
γ = min(max(dot_dir / (M * ndir2), 0), gamma_max)
x_storage = muladd_memory_mode(memory_mode, x_storage, x, γ, d)
grad!(gradient_storage, x_storage)
niter += 1
if M > line_search.max_estimate
# if this occurs, we hit numerical troubles
# if we were not using the relaxed smoothness, we try it first as a stable fallback
# note that the smoothness estimate is not updated at this iteration.
if !line_search.relaxed_smoothness
linesearch_fallback = deepcopy(line_search)
linesearch_fallback.relaxed_smoothness = true
return perform_line_search(
linesearch_fallback,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
storage,
memory_mode;
should_upgrade=should_upgrade,
)
end
# if we are already in relaxed smoothness, produce a warning:
# one might see negative progess, cycling, or stalling.
# Potentially upgrade accuracy or use an alternative line search strategy
if line_search.verbose
@warn "Smoothness estimate run away -> hard clipping. Convergence might be not guaranteed."
end
clipping = true
break
end
end
if !clipping
line_search.L_est = M
end
γ = min(max(dot_dir / (line_search.L_est * ndir2), 0), gamma_max)
return γ
end
"""
MonotonicStepSize{F}
Represents a monotonic open-loop step size.
Contains a halving factor `N` increased at each iteration until there is primal progress
`gamma = 2 / (t + 2) * 2^(-N)`.
"""
mutable struct MonotonicStepSize{F} <: LineSearchMethod
domain_oracle::F
factor::Int
end
MonotonicStepSize(f::F) where {F<:Function} = MonotonicStepSize{F}(f, 0)
MonotonicStepSize() = MonotonicStepSize(x -> true, 0)
@deprecate MonotonousStepSize(args...) MonotonicStepSize(args...) false
Base.print(io::IO, ::MonotonicStepSize) = print(io, "MonotonicStepSize")
function perform_line_search(
line_search::MonotonicStepSize,
t,
f,
g!,
gradient,
x,
d,
gamma_max,
storage,
memory_mode,
)
gamma = 2.0^(1 - line_search.factor) / (2 + t)
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
f0 = f(x)
while !line_search.domain_oracle(storage) || f(storage) > f0
line_search.factor += 1
gamma = 2.0^(1 - line_search.factor) / (2 + t)
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
end
return gamma
end
"""
MonotonicNonConvexStepSize{F}
Represents a monotonic open-loop non-convex step size.
Contains a halving factor `N` increased at each iteration until there is primal progress
`gamma = 1 / sqrt(t + 1) * 2^(-N)`.
"""
mutable struct MonotonicNonConvexStepSize{F} <: LineSearchMethod
domain_oracle::F
factor::Int
end
MonotonicNonConvexStepSize(f::F) where {F<:Function} = MonotonicNonConvexStepSize{F}(f, 0)
MonotonicNonConvexStepSize() = MonotonicNonConvexStepSize(x -> true, 0)
@deprecate MonotonousNonConvexStepSize(args...) MonotonicNonConvexStepSize(args...) false
Base.print(io::IO, ::MonotonicNonConvexStepSize) = print(io, "MonotonicNonConvexStepSize")
function build_linesearch_workspace(
::Union{MonotonicStepSize,MonotonicNonConvexStepSize},
x,
gradient,
)
return similar(x)
end
function perform_line_search(
line_search::MonotonicNonConvexStepSize,
t,
f,
g!,
gradient,
x,
d,
gamma_max,
storage,
memory_mode,
)
gamma = 2.0^(-line_search.factor) / sqrt(1 + t)
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
f0 = f(x)
while !line_search.domain_oracle(storage) || f(storage) > f0
line_search.factor += 1
gamma = 2.0^(-line_search.factor) / sqrt(1 + t)
storage = muladd_memory_mode(memory_mode, storage, x, gamma, d)
end
return gamma
end
struct MonotonicGenericStepsize{LS<:LineSearchMethod,F<:Function} <: LineSearchMethod
linesearch::LS
domain_oracle::F
end
MonotonicGenericStepsize(linesearch::LS) where {LS<:LineSearchMethod} =
MonotonicGenericStepsize(linesearch, x -> true)
Base.print(io::IO, ::MonotonicGenericStepsize) = print(io, "MonotonicGenericStepsize")
struct MonotonicWorkspace{XT,WS}
x::XT
inner_workspace::WS
end
function build_linesearch_workspace(ls::MonotonicGenericStepsize, x, gradient)
return MonotonicWorkspace(similar(x), build_linesearch_workspace(ls.linesearch, x, gradient))
end
function perform_line_search(
line_search::MonotonicGenericStepsize,
t,
f,
g!,
gradient,
x,
d,
gamma_max,
storage::MonotonicWorkspace,
memory_mode,
)
f0 = f(x)
gamma = perform_line_search(
line_search.linesearch,
t,
f,
g!,
gradient,
x,
d,
gamma_max,
storage.inner_workspace,
memory_mode,
)
gamma = min(gamma, gamma_max)
T = typeof(gamma)
xst = storage.x
xst = muladd_memory_mode(memory_mode, xst, x, gamma, d)
factor = 0
while !line_search.domain_oracle(xst) || f(xst) > f0
factor += 1
gamma *= T(2)^(-factor)
xst = muladd_memory_mode(memory_mode, xst, x, gamma, d)
if T(2)^(-factor) ≤ 10 * eps(gamma)
@error("numerical limit for gamma $gamma, invalid direction?")
break
end
end
return gamma
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 4736 |
"""
MathOptLMO{OT <: MOI.Optimizer} <: LinearMinimizationOracle
Linear minimization oracle with feasible space defined through a MathOptInterface.Optimizer.
The oracle call sets the direction and reruns the optimizer.
The `direction` vector has to be set in the same order of variables as the `MOI.ListOfVariableIndices()` getter.
The Boolean `use_modify` determines if the objective in`compute_extreme_point` is updated with
`MOI.modify(o, ::MOI.ObjectiveFunction, ::MOI.ScalarCoefficientChange)` or with `MOI.set(o, ::MOI.ObjectiveFunction, f)`.
`use_modify = true` decreases the runtime and memory allocation for models created as an optimizer object and defined directly
with MathOptInterface. `use_modify = false` should be used for CachingOptimizers.
"""
struct MathOptLMO{OT<:MOI.AbstractOptimizer} <: LinearMinimizationOracle
o::OT
use_modify::Bool
function MathOptLMO(o, use_modify=true)
MOI.set(o, MOI.ObjectiveSense(), MOI.MIN_SENSE)
return new{typeof(o)}(o, use_modify)
end
end
function compute_extreme_point(
lmo::MathOptLMO{OT},
direction::AbstractVector{T};
kwargs...,
) where {OT,T<:Real}
variables = MOI.get(lmo.o, MOI.ListOfVariableIndices())
if lmo.use_modify
for i in eachindex(variables)
MOI.modify(
lmo.o,
MOI.ObjectiveFunction{MOI.ScalarAffineFunction{T}}(),
MOI.ScalarCoefficientChange(variables[i], direction[i]),
)
end
else
terms = [MOI.ScalarAffineTerm(d, v) for (d, v) in zip(direction, variables)]
obj = MOI.ScalarAffineFunction(terms, zero(T))
MOI.set(lmo.o, MOI.ObjectiveFunction{typeof(obj)}(), obj)
end
return _optimize_and_return(lmo, variables)
end
function compute_extreme_point(
lmo::MathOptLMO{OT},
direction::AbstractMatrix{T};
kwargs...,
) where {OT,T<:Real}
n = size(direction, 1)
v = compute_extreme_point(lmo, vec(direction))
return reshape(v, n, n)
end
function Base.copy(lmo::MathOptLMO{OT}; ensure_identity=true) where {OT}
opt = OT() # creates the empty optimizer
index_map = MOI.copy_to(opt, lmo.o)
if ensure_identity
for (src_idx, des_idx) in index_map.var_map
if src_idx != des_idx
error("Mapping of variables is not identity")
end
end
end
return MathOptLMO(opt)
end
function Base.copy(
lmo::MathOptLMO{OT};
ensure_identity=true,
) where {OTI,OT<:MOIU.CachingOptimizer{OTI}}
opt = MOIU.CachingOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
OTI(),
)
index_map = MOI.copy_to(opt, lmo.o)
if ensure_identity
for (src_idx, des_idx) in index_map.var_map
if src_idx != des_idx
error("Mapping of variables is not identity")
end
end
end
return MathOptLMO(opt)
end
function compute_extreme_point(
lmo::MathOptLMO{OT},
direction::AbstractVector{MOI.ScalarAffineTerm{T}};
kwargs...,
) where {OT,T}
if lmo.use_modify
for d in direction
MOI.modify(
lmo.o,
MOI.ObjectiveFunction{MOI.ScalarAffineFunction{T}}(),
MOI.ScalarCoefficientChange(d.variable, d.coefficient),
)
end
variables = MOI.get(lmo.o, MOI.ListOfVariableIndices())
variables_to_zero = setdiff(variables, [dir.variable for dir in direction])
terms = [
MOI.ScalarAffineTerm(d, v) for
(d, v) in zip(zeros(length(variables_to_zero)), variables_to_zero)
]
for t in terms
MOI.modify(
lmo.o,
MOI.ObjectiveFunction{MOI.ScalarAffineFunction{T}}(),
MOI.ScalarCoefficientChange(t.variable, t.coefficient),
)
end
else
variables = [d.variable for d in direction]
obj = MOI.ScalarAffineFunction(direction, zero(T))
MOI.set(lmo.o, MOI.ObjectiveFunction{typeof(obj)}(), obj)
end
return _optimize_and_return(lmo, variables)
end
function _optimize_and_return(lmo, variables)
MOI.optimize!(lmo.o)
term_st = MOI.get(lmo.o, MOI.TerminationStatus())
if term_st ∉ (MOI.OPTIMAL, MOI.ALMOST_OPTIMAL, MOI.SLOW_PROGRESS)
@error "Unexpected termination: $term_st"
return MOI.get.(lmo.o, MOI.VariablePrimal(), variables)
end
return MOI.get.(lmo.o, MOI.VariablePrimal(), variables)
end
"""
convert_mathopt(lmo::LMO, optimizer::OT; kwargs...) -> MathOptLMO{OT}
Converts the given LMO to its equivalent MathOptInterface representation using `optimizer`.
Must be implemented by LMOs.
"""
function convert_mathopt end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 11918 | import Arpack
"""
LpNormLMO{T, p}(right_hand_side)
LMO with feasible set being an L-p norm ball:
```
C = {x ∈ R^n, norm(x, p) ≤ right_hand_side}
```
"""
struct LpNormLMO{T,p} <: LinearMinimizationOracle
right_hand_side::T
end
LpNormLMO{p}(right_hand_side::T) where {T,p} = LpNormLMO{T,p}(right_hand_side)
function compute_extreme_point(
lmo::LpNormLMO{T,2},
direction;
v=similar(direction),
kwargs...,
) where {T}
dir_norm = norm(direction, 2)
n = length(direction)
# if direction numerically 0
if dir_norm <= 10eps(float(eltype(direction)))
@. v = lmo.right_hand_side / sqrt(n)
else
@. v = -lmo.right_hand_side * direction / dir_norm
end
return v
end
function compute_extreme_point(
lmo::LpNormLMO{T,Inf},
direction;
v=similar(direction),
kwargs...,
) where {T}
for idx in eachindex(direction)
v[idx] = -lmo.right_hand_side * (1 - 2signbit(direction[idx]))
end
return v
end
function compute_extreme_point(lmo::LpNormLMO{T,1}, direction; v=nothing, kwargs...) where {T}
idx = 0
v = -one(eltype(direction))
for i in eachindex(direction)
if abs(direction[i]) > v
v = abs(direction[i])
idx = i
end
end
sign_coeff = sign(direction[idx])
if sign_coeff == 0.0
sign_coeff -= 1
end
return ScaledHotVector(-lmo.right_hand_side * sign_coeff, idx, length(direction))
end
function compute_extreme_point(
lmo::LpNormLMO{T,p},
direction;
v=similar(direction),
kwargs...,
) where {T,p}
# covers the case where the Inf or 1 is of another type
if p == Inf
v = compute_extreme_point(LpNormLMO{T,Inf}(lmo.right_hand_side), direction, v=v)
return v
elseif p == 1
v = compute_extreme_point(LpNormLMO{T,1}(lmo.right_hand_side), direction)
return v
end
q = p / (p - 1)
pow_ratio = q / p
q_norm = norm(direction, q)^(pow_ratio)
# handle zero_direction first
# assuming the direction is a vector of 1
if q_norm < eps(float(T))
one_vec = trues(length(direction))
@. v = -lmo.right_hand_side * one_vec^(pow_ratio) / oftype(q_norm, 1)
return v
end
@. v = -lmo.right_hand_side * sign(direction) * abs(direction)^(pow_ratio) / q_norm
return v
end
"""
KNormBallLMO{T}(K::Int, right_hand_side::T)
LMO with feasible set being the K-norm ball in the sense of
[2010.07243](https://arxiv.org/abs/2010.07243),
i.e., the convex hull over the union of an
L_1-ball with radius τ and an L_∞-ball with radius τ/K:
```
C_{K,τ} = conv { B_1(τ) ∪ B_∞(τ / K) }
```
with `τ` the `right_hand_side` parameter. The K-norm is defined as
the sum of the largest `K` absolute entries in a vector.
"""
struct KNormBallLMO{T} <: LinearMinimizationOracle
K::Int
right_hand_side::T
end
function compute_extreme_point(
lmo::KNormBallLMO{T},
direction;
v=similar(direction),
kwargs...,
) where {T}
K = max(min(lmo.K, length(direction)), 1)
oinf = zero(eltype(direction))
idx_l1 = 0
val_l1 = -one(eltype(direction))
@inbounds for (i, dir_val) in enumerate(direction)
temp = -lmo.right_hand_side / K * sign(dir_val)
v[i] = temp
oinf += dir_val * temp
abs_v = abs(dir_val)
if abs_v > val_l1
idx_l1 = i
val_l1 = abs_v
end
end
v1 = ScaledHotVector(-lmo.right_hand_side * sign(direction[idx_l1]), idx_l1, length(direction))
o1 = dot(v1, direction)
if o1 < oinf
@. v = v1
end
return v
end
"""
NuclearNormLMO{T}(radius)
LMO over matrices that have a nuclear norm less than `radius`.
The LMO returns the best rank-one approximation matrix with singular value `radius`, computed with Arpack.
"""
struct NuclearNormLMO{T} <: LinearMinimizationOracle
radius::T
end
NuclearNormLMO{T}() where {T} = NuclearNormLMO{T}(one(T))
NuclearNormLMO() = NuclearNormLMO(1.0)
function compute_extreme_point(
lmo::NuclearNormLMO{TL},
direction::AbstractMatrix{TD};
tol=1e-8,
kwargs...,
) where {TL,TD}
T = promote_type(TD, TL)
Z = Arpack.svds(direction, nsv=1, tol=tol)[1]
u = -lmo.radius * view(Z.U, :)
return RankOneMatrix(u::Vector{T}, Z.V[:]::Vector{T})
end
function convert_mathopt(
lmo::NuclearNormLMO,
optimizer::OT;
row_dimension::Integer,
col_dimension::Integer,
use_modify=true::Bool,
kwargs...,
) where {OT}
MOI.empty!(optimizer)
x = MOI.add_variables(optimizer, row_dimension * col_dimension)
(t, _) = MOI.add_constrained_variable(optimizer, MOI.LessThan(lmo.radius))
MOI.add_constraint(optimizer, [t; x], MOI.NormNuclearCone(row_dimension, col_dimension))
return MathOptLMO(optimizer, use_modify)
end
"""
SpectraplexLMO{T,M}(radius::T,gradient_container::M,ensure_symmetry::Bool=true)
Feasible set
```
{X ∈ 𝕊_n^+, trace(X) == radius}
```
`gradient_container` is used to store the symmetrized negative direction.
`ensure_symmetry` indicates whether the linear function is made symmetric before computing the eigenvector.
"""
struct SpectraplexLMO{T,M} <: LinearMinimizationOracle
radius::T
gradient_container::M
ensure_symmetry::Bool
maxiters::Int
end
function SpectraplexLMO(
radius::T,
side_dimension::Int,
ensure_symmetry::Bool=true,
maxiters::Int=500,
) where {T}
return SpectraplexLMO(
radius,
Matrix{T}(undef, side_dimension, side_dimension),
ensure_symmetry,
maxiters,
)
end
function SpectraplexLMO(
radius::Integer,
side_dimension::Int,
ensure_symmetry::Bool=true,
maxiters::Int=500,
)
return SpectraplexLMO(float(radius), side_dimension, ensure_symmetry, maxiters)
end
function compute_extreme_point(
lmo::SpectraplexLMO{T},
direction::M;
v=nothing,
kwargs...,
) where {T,M<:AbstractMatrix}
lmo.gradient_container .= direction
if !(M <: Union{LinearAlgebra.Symmetric,LinearAlgebra.Diagonal,LinearAlgebra.UniformScaling}) &&
lmo.ensure_symmetry
# make gradient symmetric
@. lmo.gradient_container += direction'
end
lmo.gradient_container .*= -1
_, evec = Arpack.eigs(lmo.gradient_container; nev=1, which=:LR, maxiter=lmo.maxiters)
# type annotation because of Arpack instability
unit_vec::Vector{T} = vec(evec)
# scaling by sqrt(radius) so that x x^T has spectral norm radius while using a single vector
unit_vec .*= sqrt(lmo.radius)
return FrankWolfe.RankOneMatrix(unit_vec, unit_vec)
end
"""
UnitSpectrahedronLMO{T,M}(radius::T, gradient_container::M)
Feasible set of PSD matrices with bounded trace:
```
{X ∈ 𝕊_n^+, trace(X) ≤ radius}
```
`gradient_container` is used to store the symmetrized negative direction.
`ensure_symmetry` indicates whether the linear function is made symmetric before computing the eigenvector.
"""
struct UnitSpectrahedronLMO{T,M} <: LinearMinimizationOracle
radius::T
gradient_container::M
ensure_symmetry::Bool
end
function UnitSpectrahedronLMO(radius::T, side_dimension::Int, ensure_symmetry::Bool=true) where {T}
return UnitSpectrahedronLMO(
radius,
Matrix{T}(undef, side_dimension, side_dimension),
ensure_symmetry,
)
end
UnitSpectrahedronLMO(radius::Integer, side_dimension::Int) =
UnitSpectrahedronLMO(float(radius), side_dimension)
function compute_extreme_point(
lmo::UnitSpectrahedronLMO{T},
direction::M;
v=nothing,
maxiters=500,
kwargs...,
) where {T,M<:AbstractMatrix}
lmo.gradient_container .= direction
if !(M <: Union{LinearAlgebra.Symmetric,LinearAlgebra.Diagonal,LinearAlgebra.UniformScaling}) &&
lmo.ensure_symmetry
# make gradient symmetric
@. lmo.gradient_container += direction'
end
lmo.gradient_container .*= -1
e_val::Vector{T}, evec::Matrix{T} =
Arpack.eigs(lmo.gradient_container; nev=1, which=:LR, maxiter=maxiters)
# type annotation because of Arpack instability
unit_vec::Vector{T} = vec(evec)
if e_val[1] < 0
# return a zero rank-one matrix
unit_vec .*= 0
else
# scaling by sqrt(radius) so that x x^T has spectral norm radius while using a single vector
unit_vec .*= sqrt(lmo.radius)
end
return FrankWolfe.RankOneMatrix(unit_vec, unit_vec)
end
function convert_mathopt(
lmo::Union{SpectraplexLMO{T},UnitSpectrahedronLMO{T}},
optimizer::OT;
side_dimension::Integer,
use_modify::Bool=true,
kwargs...,
) where {T,OT}
MOI.empty!(optimizer)
X = MOI.add_variables(optimizer, side_dimension * side_dimension)
MOI.add_constraint(optimizer, X, MOI.PositiveSemidefiniteConeSquare(side_dimension))
sum_diag_terms = MOI.ScalarAffineFunction{T}([], zero(T))
# collect diagonal terms of the matrix
for i in 1:side_dimension
push!(sum_diag_terms.terms, MOI.ScalarAffineTerm(one(T), X[i+side_dimension*(i-1)]))
end
constraint_set = if lmo isa SpectraplexLMO
MOI.EqualTo(lmo.radius)
else
MOI.LessThan(lmo.radius)
end
MOI.add_constraint(optimizer, sum_diag_terms, constraint_set)
return MathOptLMO(optimizer, use_modify)
end
"""
EllipsoidLMO(A, c, r)
Linear minimization over an ellipsoid centered at `c` of radius `r`:
```
x: (x - c)^T A (x - c) ≤ r
```
The LMO stores the factorization `F` of A that is used to solve linear systems `A⁻¹ x`.
The result of the linear system solve is stored in `buffer`.
The ellipsoid is assumed to be full-dimensional -> A is positive definite.
"""
struct EllipsoidLMO{AT,FT,CT,T,BT} <: LinearMinimizationOracle
A::AT
F::FT
center::CT
radius::T
buffer::BT
end
function EllipsoidLMO(A, center, radius)
F = cholesky(A)
buffer = radius * similar(center)
return EllipsoidLMO(A, F, center, radius, buffer)
end
EllipsoidLMO(A) = EllipsoidLMO(A, zeros(size(A, 1)), true)
function compute_extreme_point(lmo::EllipsoidLMO, direction; v=nothing, kwargs...)
if v === nothing
# used for type promotion
v = lmo.center + false * lmo.radius * direction
else
copyto!(v, lmo.center)
end
# buffer = A⁻¹ direction
ldiv!(lmo.buffer, lmo.F, direction)
scaling = sqrt(lmo.radius) / sqrt(dot(direction, lmo.buffer))
# v = v - I * buffer * scaling
mul!(v, I, lmo.buffer, -scaling, true)
return v
end
"""
OrderWeightNormLMO(weights,radius)
LMO with feasible set being the atomic ordered weighted l1 norm: https://arxiv.org/pdf/1409.4271
```
C = {x ∈ R^n, Ω_w(x) ≤ R}
```
The weights are assumed to be positive.
"""
struct OrderWeightNormLMO{R,B,D} <: LinearMinimizationOracle
radius::R
mat_B::B
direction_abs::D
end
function OrderWeightNormLMO(weights, radius)
N = length(weights)
s = zero(eltype(weights))
B = zeros(float(typeof(s)),N)
w_sort = sort(weights,rev=true)
for i in 1:N
s += w_sort[i]
B[i] = 1/s
end
w_sort = similar(weights)
return OrderWeightNormLMO(radius,B,w_sort)
end
function compute_extreme_point(
lmo::OrderWeightNormLMO,
direction::M;
v=nothing,
kwargs...,
) where {M}
for i in eachindex(direction)
lmo.direction_abs[i] = abs(direction[i])
end
perm_grad = sortperm(lmo.direction_abs, rev=true)
scal_max = 0
ind_max = 1
N = length(lmo.mat_B)
for i in 1:N
scal = zero(eltype(lmo.direction_abs[1]))
for k in 1:i
scal += lmo.mat_B[i] * lmo.direction_abs[perm_grad][k]
end
if scal > scal_max
scal_max = scal
ind_max = i
end
end
v = lmo.radius .* (2 * signbit.(direction) .- 1)
unsort_perm = sortperm(perm_grad)
for i in 1:N
if unsort_perm[i] <= ind_max
v[i] *= lmo.mat_B[ind_max]
else
v[i] = 0
end
end
return v
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 14565 |
"""
pairwise_frank_wolfe(f, grad!, lmo, x0; ...)
Frank-Wolfe with pairwise steps.
The algorithm maintains the current iterate as a convex combination of vertices in the
[`FrankWolfe.ActiveSet`](@ref) data structure.
See [M. Besançon, A. Carderera and S. Pokutta 2021](https://arxiv.org/abs/2104.06675) for illustrations of away steps.
Unlike away-step, it transfers weight from an away vertex to another vertex.
"""
function pairwise_frank_wolfe(
f,
grad!,
lmo,
x0;
line_search::LineSearchMethod=Adaptive(),
lazy_tolerance=2.0,
epsilon=1e-7,
lazy=false,
momentum=nothing,
max_iteration=10000,
print_iter=1000,
trajectory=false,
verbose=false,
memory_mode::MemoryEmphasis=InplaceEmphasis(),
gradient=nothing,
renorm_interval=1000,
callback=nothing,
traj_data=[],
timeout=Inf,
weight_purge_threshold=weight_purge_threshold_default(eltype(x0)),
extra_vertex_storage=nothing,
add_dropped_vertices=false,
use_extra_vertex_storage=false,
linesearch_workspace=nothing,
recompute_last_vertex=true,
)
# add the first vertex to active set from initialization
active_set = ActiveSet([(1.0, x0)])
# Call the method using an ActiveSet as input
return pairwise_frank_wolfe(
f,
grad!,
lmo,
active_set,
line_search=line_search,
lazy_tolerance=lazy_tolerance,
epsilon=epsilon,
lazy=lazy,
momentum=momentum,
max_iteration=max_iteration,
print_iter=print_iter,
trajectory=trajectory,
verbose=verbose,
memory_mode=memory_mode,
gradient=gradient,
renorm_interval=renorm_interval,
callback=callback,
traj_data=traj_data,
timeout=timeout,
weight_purge_threshold=weight_purge_threshold,
extra_vertex_storage=extra_vertex_storage,
add_dropped_vertices=add_dropped_vertices,
use_extra_vertex_storage=use_extra_vertex_storage,
linesearch_workspace=linesearch_workspace,
recompute_last_vertex=recompute_last_vertex,
)
end
# pairwise FrankWolfe with the active set given as parameter
# note: in this case I don't need x0 as it is given by the active set and might otherwise lead to confusion
function pairwise_frank_wolfe(
f,
grad!,
lmo,
active_set::AbstractActiveSet{AT,R};
line_search::LineSearchMethod=Adaptive(),
lazy_tolerance=2.0,
epsilon=1e-7,
lazy=false,
momentum=nothing,
max_iteration=10000,
print_iter=1000,
trajectory=false,
verbose=false,
memory_mode::MemoryEmphasis=InplaceEmphasis(),
gradient=nothing,
renorm_interval=1000,
callback=nothing,
traj_data=[],
timeout=Inf,
weight_purge_threshold=weight_purge_threshold_default(R),
extra_vertex_storage=nothing,
add_dropped_vertices=false,
use_extra_vertex_storage=false,
linesearch_workspace=nothing,
recompute_last_vertex=true,
) where {AT,R}
# format string for output of the algorithm
format_string = "%6s %13s %14e %14e %14e %14e %14e %14i\n"
headers = ("Type", "Iteration", "Primal", "Dual", "Dual Gap", "Time", "It/sec", "#ActiveSet")
function format_state(state, active_set)
rep = (
steptype_string[Symbol(state.step_type)],
string(state.t),
Float64(state.primal),
Float64(state.primal - state.dual_gap),
Float64(state.dual_gap),
state.time,
state.t / state.time,
length(active_set),
)
return rep
end
if isempty(active_set)
throw(ArgumentError("Empty active set"))
end
t = 0
dual_gap = Inf
primal = Inf
x = get_active_set_iterate(active_set)
step_type = ST_REGULAR
if trajectory
callback = make_trajectory_callback(callback, traj_data)
end
if verbose
callback = make_print_callback(callback, print_iter, headers, format_string, format_state)
end
time_start = time_ns()
d = similar(x)
if gradient === nothing
gradient = collect(x)
end
gtemp = if momentum !== nothing
similar(gradient)
else
nothing
end
if verbose
println("\nPairwise Frank-Wolfe Algorithm.")
NumType = eltype(x)
println(
"MEMORY_MODE: $memory_mode STEPSIZE: $line_search EPSILON: $epsilon MAXITERATION: $max_iteration TYPE: $NumType",
)
grad_type = typeof(gradient)
println(
"GRADIENTTYPE: $grad_type LAZY: $lazy lazy_tolerance: $lazy_tolerance MOMENTUM: $momentum",
)
println("LMO: $(typeof(lmo))")
if (use_extra_vertex_storage || add_dropped_vertices) && extra_vertex_storage === nothing
@warn(
"use_extra_vertex_storage and add_dropped_vertices options are only usable with a extra_vertex_storage storage"
)
end
end
x = get_active_set_iterate(active_set)
primal = f(x)
v = active_set.atoms[1]
phi_value = convert(eltype(x), Inf)
gamma = one(phi_value)
if linesearch_workspace === nothing
linesearch_workspace = build_linesearch_workspace(line_search, x, gradient)
end
if extra_vertex_storage === nothing
use_extra_vertex_storage = add_dropped_vertices = false
end
while t <= max_iteration && phi_value >= max(eps(float(typeof(phi_value))), epsilon)
#####################
# managing time and Ctrl-C
#####################
time_at_loop = time_ns()
if t == 0
time_start = time_at_loop
end
# time is measured at beginning of loop for consistency throughout all algorithms
tot_time = (time_at_loop - time_start) / 1e9
if timeout < Inf
if tot_time ≥ timeout
if verbose
@info "Time limit reached"
end
break
end
end
#####################
t += 1
# compute current iterate from active set
x = get_active_set_iterate(active_set)
if isnothing(momentum)
grad!(gradient, x)
else
grad!(gtemp, x)
@memory_mode(memory_mode, gradient = (momentum * gradient) + (1 - momentum) * gtemp)
end
if lazy
d, fw_vertex, fw_index, away_vertex, away_index, gamma_max, phi_value, step_type =
lazy_pfw_step(
x,
gradient,
lmo,
active_set,
phi_value,
epsilon,
d;
use_extra_vertex_storage=use_extra_vertex_storage,
extra_vertex_storage=extra_vertex_storage,
lazy_tolerance=lazy_tolerance,
memory_mode=memory_mode,
)
else
d, fw_vertex, fw_index, away_vertex, away_index, gamma_max, phi_value, step_type =
pfw_step(x, gradient, lmo, active_set, epsilon, d, memory_mode=memory_mode)
end
if fw_index === nothing
fw_index = find_atom(active_set, fw_vertex)
end
if gamma ≈ gamma_max && fw_index === -1
step_type = ST_DUALSTEP
end
gamma = 0.0
if step_type != ST_DUALSTEP
gamma = perform_line_search(
line_search,
t,
f,
grad!,
gradient,
x,
d,
gamma_max,
linesearch_workspace,
memory_mode,
)
gamma = min(gamma_max, gamma)
# cleanup and renormalize every x iterations. Only for the fw steps.
renorm = mod(t, renorm_interval) == 0
# away update
active_set_update!(
active_set,
-gamma,
away_vertex,
true,
away_index,
add_dropped_vertices=use_extra_vertex_storage,
vertex_storage=extra_vertex_storage,
)
if add_dropped_vertices && gamma == gamma_max
for vtx in active_set.atoms
if vtx != v
push!(extra_vertex_storage, vtx)
end
end
end
# fw update
active_set_update!(active_set, gamma, fw_vertex, renorm, fw_index)
end
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
fw_vertex,
d,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
if callback(state, active_set) === false
break
end
end
if mod(t, renorm_interval) == 0
active_set_renormalize!(active_set)
x = compute_active_set_iterate!(active_set)
end
if (
(mod(t, print_iter) == 0 && verbose) ||
callback !== nothing ||
!(line_search isa Agnostic || line_search isa Nonconvex || line_search isa FixedStep)
)
primal = f(x)
dual_gap = phi_value
end
end
# recompute everything once more for final verfication / do not record to trajectory though for now!
# this is important as some variants do not recompute f(x) and the dual_gap regularly but only when reporting
# hence the final computation.
# do also cleanup of active_set due to many operations on the same set
x = get_active_set_iterate(active_set)
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient)
primal = f(x)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
dual_gap = min(phi_value, dual_gap)
step_type = ST_LAST
tot_time = (time_ns() - time_start) / 1e9
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
nothing,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
callback(state, active_set)
end
active_set_renormalize!(active_set)
active_set_cleanup!(
active_set;
weight_purge_threshold=weight_purge_threshold,
add_dropped_vertices=use_extra_vertex_storage,
vertex_storage=extra_vertex_storage,
)
x = get_active_set_iterate(active_set)
grad!(gradient, x)
if recompute_last_vertex
v = compute_extreme_point(lmo, gradient)
primal = f(x)
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
end
step_type = ST_POSTPROCESS
tot_time = (time_ns() - time_start) / 1e9
if callback !== nothing
state = CallbackState(
t,
primal,
primal - dual_gap,
dual_gap,
tot_time,
x,
v,
nothing,
gamma,
f,
grad!,
lmo,
gradient,
step_type,
)
callback(state, active_set)
end
return (x=x, v=v, primal=primal, dual_gap=dual_gap, traj_data=traj_data, active_set=active_set)
end
function lazy_pfw_step(
x,
gradient,
lmo,
active_set,
phi,
epsilon,
d;
use_extra_vertex_storage=false,
extra_vertex_storage=nothing,
lazy_tolerance=2.0,
memory_mode::MemoryEmphasis=InplaceEmphasis(),
)
_, v_local, v_local_loc, _, a_lambda, a_local, a_local_loc, _, _ =
active_set_argminmax(active_set, gradient)
# We will always have an away vertex determining the steplength.
gamma_max = a_lambda
away_index = a_local_loc
fw_index = nothing
grad_dot_x = fast_dot(x, gradient)
grad_dot_a_local = fast_dot(a_local, gradient)
# Do lazy pairwise step
grad_dot_lazy_fw_vertex = fast_dot(v_local, gradient)
if grad_dot_a_local - grad_dot_lazy_fw_vertex >= phi / lazy_tolerance &&
grad_dot_a_local - grad_dot_lazy_fw_vertex >= epsilon
step_type = ST_LAZY
v = v_local
d = muladd_memory_mode(memory_mode, d, a_local, v)
fw_index = v_local_loc
else
# optionally: try vertex storage
if use_extra_vertex_storage
lazy_threshold = fast_dot(gradient, a_local) - phi / lazy_tolerance
(found_better_vertex, new_forward_vertex) =
storage_find_argmin_vertex(extra_vertex_storage, gradient, lazy_threshold)
if found_better_vertex
@debug("Found acceptable lazy vertex in storage")
v = new_forward_vertex
step_type = ST_LAZYSTORAGE
else
v = compute_extreme_point(lmo, gradient)
step_type = ST_PAIRWISE
end
else
v = compute_extreme_point(lmo, gradient)
step_type = ST_PAIRWISE
end
# Real dual gap promises enough progress.
grad_dot_fw_vertex = fast_dot(v, gradient)
dual_gap = grad_dot_x - grad_dot_fw_vertex
if dual_gap >= phi / lazy_tolerance
d = muladd_memory_mode(memory_mode, d, a_local, v)
#Lower our expectation for progress.
else
step_type = ST_DUALSTEP
phi = min(dual_gap, phi / 2.0)
end
end
return d, v, fw_index, a_local, away_index, gamma_max, phi, step_type
end
function pfw_step(
x,
gradient,
lmo,
active_set,
epsilon,
d;
memory_mode::MemoryEmphasis=InplaceEmphasis(),
)
step_type = ST_PAIRWISE
_, _, _, _, a_lambda, a_local, a_local_loc = active_set_argminmax(active_set, gradient)
away_vertex = a_local
away_index = a_local_loc
# We will always have a away vertex determining the steplength.
gamma_max = a_lambda
v = compute_extreme_point(lmo, gradient)
fw_vertex = v
fw_index = nothing
grad_dot_x = fast_dot(x, gradient)
dual_gap = grad_dot_x - fast_dot(v, gradient)
d = muladd_memory_mode(memory_mode, d, a_local, v)
return d, fw_vertex, fw_index, away_vertex, away_index, gamma_max, dual_gap, step_type
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 7452 |
"""
KSparseLMO{T}(K::Int, right_hand_side::T)
LMO for the K-sparse polytope:
```
C = B_1(τK) ∩ B_∞(τ)
```
with `τ` the `right_hand_side` parameter.
The LMO results in a vector with the K largest absolute values
of direction, taking values `-τ sign(x_i)`.
"""
struct KSparseLMO{T} <: LinearMinimizationOracle
K::Int
right_hand_side::T
end
function compute_extreme_point(lmo::KSparseLMO{T}, direction; v=nothing, kwargs...) where {T}
K = min(lmo.K, length(direction))
K_indices = sortperm(direction[1:K], by=abs, rev=true)
K_values = direction[K_indices]
for idx in K+1:length(direction)
new_val = direction[idx]
# new greater value: shift everything right
if abs(new_val) > abs(K_values[1])
K_values[2:end] .= K_values[1:end-1]
K_indices[2:end] .= K_indices[1:end-1]
K_indices[1] = idx
K_values[1] = new_val
# new value in the interior
elseif abs(new_val) > abs(K_values[K])
# NOTE: not out of bound since unreachable with K=1
j = K - 1
while abs(new_val) > abs(K_values[j])
j -= 1
end
K_values[j+1:end] .= K_values[j:end-1]
K_indices[j+1:end] .= K_indices[j:end-1]
K_values[j+1] = new_val
K_indices[j+1] = idx
end
end
v = spzeros(T, length(direction))
for (idx, val) in zip(K_indices, K_values)
# signbit to avoid zeros, ensuring we have a true extreme point
# equivalent to sign(val) but without any zero
s = 1 - 2 * signbit(val)
v[idx] = -lmo.right_hand_side * s
end
return v
end
function convert_mathopt(
lmo::KSparseLMO{T},
optimizer::OT;
dimension::Integer,
use_modify::Bool=true,
kwargs...,
) where {T,OT}
τ = lmo.right_hand_side
n = dimension
K = min(lmo.K, n)
MOI.empty!(optimizer)
x = MOI.add_variables(optimizer, n)
tinf = MOI.add_variable(optimizer)
MOI.add_constraint(optimizer, MOI.VectorOfVariables([tinf; x]), MOI.NormInfinityCone(n + 1))
MOI.add_constraint(optimizer, tinf, MOI.LessThan(τ))
t1 = MOI.add_variable(optimizer)
MOI.add_constraint(optimizer, MOI.VectorOfVariables([t1; x]), MOI.NormOneCone(n + 1))
MOI.add_constraint(optimizer, t1, MOI.LessThan(τ * K))
return MathOptLMO(optimizer, use_modify)
end
"""
BirkhoffPolytopeLMO
The Birkhoff polytope encodes doubly stochastic matrices.
Its extreme vertices are all permutation matrices of side-dimension `dimension`.
"""
struct BirkhoffPolytopeLMO <: LinearMinimizationOracle end
function compute_extreme_point(
::BirkhoffPolytopeLMO,
direction::AbstractMatrix{T};
v=nothing,
kwargs...,
) where {T}
n = size(direction, 1)
n == size(direction, 2) ||
DimensionMismatch("direction should be square and matching BirkhoffPolytopeLMO dimension")
m = spzeros(Bool, n, n)
res_mat = Hungarian.munkres(direction)
(rows, cols, vals) = SparseArrays.findnz(res_mat)
@inbounds for i in eachindex(cols)
m[rows[i], cols[i]] = vals[i] == 2
end
m = convert(SparseArrays.SparseMatrixCSC{Float64,Int64}, m)
return m
end
function compute_extreme_point(
lmo::BirkhoffPolytopeLMO,
direction::AbstractVector{T};
v=nothing,
kwargs...,
) where {T}
nsq = length(direction)
n = isqrt(nsq)
return compute_extreme_point(lmo, reshape(direction, n, n); kwargs...)[:]
end
function convert_mathopt(
::BirkhoffPolytopeLMO,
optimizer::OT;
dimension::Integer,
use_modify::Bool=true,
kwargs...,
) where {OT}
n = dimension
MOI.empty!(optimizer)
(x, _) = MOI.add_constrained_variables(optimizer, fill(MOI.Interval(0.0, 1.0), n * n))
xmat = reshape(x, n, n)
for idx in 1:n
# column constraint
MOI.add_constraint(
optimizer,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), xmat[:, idx]), 0.0),
MOI.EqualTo(1.0),
)
# row constraint
MOI.add_constraint(
optimizer,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), xmat[idx, :]), 0.0),
MOI.EqualTo(1.0),
)
end
return MathOptLMO(optimizer, use_modify)
end
"""
ScaledBoundLInfNormBall(lower_bounds, upper_bounds)
Polytope similar to a L-inf-ball with shifted bounds or general box constraints.
Lower- and upper-bounds are passed on as abstract vectors, possibly of different types.
For the standard L-inf ball, all lower- and upper-bounds would be -1 and 1.
"""
struct ScaledBoundLInfNormBall{T,N,VT1<:AbstractArray{T,N},VT2<:AbstractArray{T,N}} <:
LinearMinimizationOracle
lower_bounds::VT1
upper_bounds::VT2
end
function compute_extreme_point(
lmo::ScaledBoundLInfNormBall,
direction;
v=similar(lmo.lower_bounds),
kwargs...,
)
copyto!(v, lmo.lower_bounds)
for i in eachindex(direction)
if direction[i] * lmo.upper_bounds[i] < direction[i] * lmo.lower_bounds[i]
v[i] = lmo.upper_bounds[i]
end
end
return v
end
"""
ScaledBoundL1NormBall(lower_bounds, upper_bounds)
Polytope similar to a L1-ball with shifted bounds.
It is the convex hull of two scaled and shifted unit vectors for each axis (shifted to the center of the polytope, i.e., the elementwise midpoint of the bounds).
Lower and upper bounds are passed on as abstract vectors, possibly of different types.
For the standard L1-ball, all lower and upper bounds would be -1 and 1.
"""
struct ScaledBoundL1NormBall{T,N,VT1<:AbstractArray{T,N},VT2<:AbstractArray{T,N}} <:
LinearMinimizationOracle
lower_bounds::VT1
upper_bounds::VT2
end
function compute_extreme_point(
lmo::ScaledBoundL1NormBall,
direction;
v=similar(lmo.lower_bounds),
kwargs...,
)
@inbounds for i in eachindex(lmo.lower_bounds)
v[i] = (lmo.lower_bounds[i] + lmo.upper_bounds[i]) / 2
end
idx = 0
lower = false
val = zero(eltype(direction))
if length(direction) != length(lmo.upper_bounds)
throw(DimensionMismatch())
end
@inbounds for i in eachindex(direction)
scale_factor = lmo.upper_bounds[i] - lmo.lower_bounds[i]
scaled_dir = direction[i] * scale_factor
if scaled_dir > val
val = scaled_dir
idx = i
lower = true
elseif -scaled_dir > val
val = -scaled_dir
idx = i
lower = false
end
end
# compute midpoint for all coordinates, replace with extreme coordinate on one
# TODO use smarter array type if bounds are FillArrays
# handle zero direction
idx = max(idx, 1)
v[idx] = ifelse(lower, lmo.lower_bounds[idx], lmo.upper_bounds[idx])
return v
end
"""
ConvexHullOracle{AT,VT}
Convex hull of a finite number of vertices of type `AT`, stored in a vector of type `VT`.
"""
struct ConvexHullOracle{AT, VT <: AbstractVector{AT}} <: LinearMinimizationOracle
vertices::VT
end
function compute_extreme_point(lmo::ConvexHullOracle{AT}, direction; v=nothing, kwargs...) where {AT}
T = promote_type(eltype(direction), eltype(AT))
best_val = T(Inf)
best_vertex = first(lmo.vertices)
for vertex in lmo.vertices
val = dot(vertex, direction)
if val < best_val
best_val = val
best_vertex = vertex
end
end
return best_vertex
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 38990 | Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Shortstep{Float64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.31842098
Base.precompile(Tuple{Type{Shortstep},Float64}) # time: 0.010073511
Base.precompile(
Tuple{
Core.kwftype(typeof(print_callback)),
NamedTuple{(:print_header,),Tuple{Bool}},
typeof(print_callback),
Vector{String},
String,
},
) # time: 0.001591955
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.061905436
Base.precompile(Tuple{Type{Adaptive}}) # time: 0.003947135
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Agnostic{Float64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.06750039
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :verbose, :memory_mode),
Tuple{Int64,Agnostic{Float64},Float64,Bool,OutplaceEmphasis},
},
typeof(frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Rational{BigInt}},
ScaledHotVector{Rational{BigInt}},
},
) # time: 0.2661169
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Float64,Any,Float64,Float64,Float64},String},
) # time: 0.004444123
Base.precompile(
Tuple{typeof(dot),ScaledHotVector{Rational{BigInt}},ScaledHotVector{Rational{BigInt}}},
) # time: 0.001534546
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose),
Tuple{Float64,Agnostic{Float64},Float64,InplaceEmphasis,Bool},
},
typeof(frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Rational{BigInt}},
ScaledHotVector{Rational{BigInt}},
},
) # time: 0.43984142
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:epsilon,
:trajectory,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Float64,Bool},
},
typeof(frank_wolfe),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.26637408
Base.precompile(
Tuple{Core.kwftype(typeof(Type)),NamedTuple{(:L_est,),Tuple{Float64}},Type{Adaptive}},
) # time: 0.00490745
Base.precompile(
Tuple{
Core.kwftype(typeof(print_callback)),
NamedTuple{(:print_header,),Tuple{Bool}},
typeof(print_callback),
NTuple{9,String},
String,
},
) # time: 0.005392282
Base.precompile(
Tuple{
Core.kwftype(typeof(lp_separation_oracle)),
NamedTuple{(:inplace_loop, :force_fw_step),Tuple{Bool,Bool}},
typeof(lp_separation_oracle),
BirkhoffPolytopeLMO,
ActiveSet{
SparseArrays.SparseMatrixCSC{Float64,Int64},
Float64,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
SparseArrays.SparseMatrixCSC{Float64,Int64},
Float64,
Float64,
},
) # time: 0.001709011
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_conditional_gradient)),
NamedTuple{
(
:epsilon,
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:trajectory,
:lazy_tolerance,
:weight_purge_threshold,
),
Tuple{
Float64,
Int64,
Adaptive{Float64,Int64},
Float64,
InplaceEmphasis,
Bool,
Bool,
Float64,
Float64,
},
},
typeof(blended_conditional_gradient),
Function,
Function,
ProbabilitySimplexOracle{Float64},
ScaledHotVector{Float64},
},
) # time: 0.5107306
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_conditional_gradient)),
NamedTuple{
(
:epsilon,
:max_iteration,
:line_search,
:print_iter,
:hessian,
:memory_mode,
:accelerated,
:verbose,
:trajectory,
:lazy_tolerance,
:weight_purge_threshold,
),
Tuple{
Float64,
Int64,
Adaptive{Float64,Int64},
Float64,
Matrix{Float64},
InplaceEmphasis,
Bool,
Bool,
Bool,
Float64,
Float64,
},
},
typeof(blended_conditional_gradient),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.44398972
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_conditional_gradient)),
NamedTuple{
(
:epsilon,
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:trajectory,
:lazy_tolerance,
:weight_purge_threshold,
),
Tuple{
Float64,
Int64,
Adaptive{Float64,Int64},
Float64,
InplaceEmphasis,
Bool,
Bool,
Float64,
Float64,
},
},
typeof(blended_conditional_gradient),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.38173005
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_pairwise_conditional_gradient)),
NamedTuple{
(
:epsilon,
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:trajectory,
),
Tuple{Float64,Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(blended_pairwise_conditional_gradient),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.18068784
Base.precompile(
Tuple{
Core.kwftype(typeof(print_callback)),
NamedTuple{(:print_header,),Tuple{Bool}},
typeof(print_callback),
NTuple{8,String},
String,
},
) # time: 0.005311987
Base.precompile(
Tuple{
typeof(active_set_update!),
ActiveSet{SparseVector{Float64,Int64},Float64,SparseVector{Float64,Int64}},
Float64,
SparseVector{Float64,Int64},
Bool,
Nothing,
},
) # time: 0.3297556
Base.precompile(
Tuple{
typeof(perform_line_search),
Adaptive{Float64,Int64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
SparseVector{Float64,Int64},
Vector{Float64},
Float64,
SparseVector{Float64,Int64},
},
) # time: 0.0803171
Base.precompile(Tuple{Type{ActiveSet},Vector{Tuple{Float64,SparseVector{Float64,Int64}}}}) # time: 0.06371654
Base.precompile(
Tuple{
Core.kwftype(typeof(lazy_afw_step)),
NamedTuple{(:lazy_tolerance,),Tuple{Float64}},
typeof(lazy_afw_step),
SparseVector{Float64,Int64},
SparseVector{Float64,Int64},
KSparseLMO{Float64},
ActiveSet{SparseVector{Float64,Int64},Float64,SparseVector{Float64,Int64}},
Float64,
SparseVector{Float64,Int64},
},
) # time: 0.032522447
Base.precompile(
Tuple{
typeof(perform_line_search),
Adaptive{Float64,Int64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
SparseVector{Float64,Int64},
SparseVector{Float64,Int64},
Float64,
SparseVector{Float64,Int64},
},
) # time: 0.007260863
Base.precompile(
Tuple{
typeof(active_set_update!),
ActiveSet{SparseVector{Float64,Int64},Float64,SparseVector{Float64,Int64}},
Float64,
SparseVector{Float64,Int64},
Bool,
Int64,
},
) # time: 0.007143604
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Any,Any,Float64,Float64,Float64,Int64},String},
) # time: 0.003918484
Base.precompile(
Tuple{
typeof(afw_step),
SparseVector{Float64,Int64},
SparseVector{Float64,Int64},
KSparseLMO{Float64},
ActiveSet{SparseVector{Float64,Int64},Float64,SparseVector{Float64,Int64}},
SparseVector{Float64,Int64},
},
) # time: 0.002095744
Base.precompile(
Tuple{
typeof(active_set_update_iterate_pairwise!),
SparseVector{Float64,Int64},
Float64,
SparseVector{Float64,Int64},
SparseVector{Float64,Int64},
},
) # time: 0.22706518
Base.precompile(
Tuple{
typeof(active_set_initialize!),
ActiveSet{SparseVector{Float64,Int64},Float64,SparseVector{Float64,Int64}},
SparseVector{Float64,Int64},
},
) # time: 0.07041422
Base.precompile(
Tuple{
typeof(deleteat!),
ActiveSet{SparseVector{Float64,Int64},Float64,SparseVector{Float64,Int64}},
Int64,
},
) # time: 0.001469705
Base.precompile(
Tuple{
Core.kwftype(typeof(away_frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:epsilon,
:memory_mode,
:verbose,
:trajectory,
:lazy,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,Float64,InplaceEmphasis,Bool,Bool,Bool},
},
typeof(away_frank_wolfe),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 1.2606552
Base.precompile(
Tuple{
Core.kwftype(typeof(away_frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:epsilon,
:memory_mode,
:verbose,
:away_steps,
:trajectory,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,Float64,InplaceEmphasis,Bool,Bool,Bool},
},
typeof(away_frank_wolfe),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.025728334
Base.precompile(
Tuple{
Core.kwftype(typeof(away_frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:epsilon,
:trajectory,
:away_steps,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Float64,Bool,Bool},
},
typeof(away_frank_wolfe),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.042767525
Base.precompile(
Tuple{
Core.kwftype(typeof(lazified_conditional_gradient)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose),
Tuple{Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool},
},
typeof(lazified_conditional_gradient),
Function,
Function,
KSparseLMO{Float64},
SparseVector{Float64,Int64},
},
) # time: 0.71887785
Base.precompile(
Tuple{Type{MultiCacheLMO{_A,KSparseLMO{Float64},_B}} where {_A,_B},KSparseLMO{Float64}},
) # time: 0.007678914
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Float64,Any,Any,Float64,Float64,Any},String},
) # time: 0.007181576
Base.precompile(Tuple{Type{VectorCacheLMO{KSparseLMO{Float64},_A}} where _A,KSparseLMO{Float64}}) # time: 0.005332965
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:epsilon,
:memory_mode,
:trajectory,
:verbose,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
BirkhoffPolytopeLMO,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.77472156
Base.precompile(
Tuple{
Core.kwftype(typeof(lazified_conditional_gradient)),
NamedTuple{
(
:max_iteration,
:epsilon,
:line_search,
:print_iter,
:memory_mode,
:trajectory,
:verbose,
),
Tuple{Int64,Float64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(lazified_conditional_gradient),
Function,
Function,
BirkhoffPolytopeLMO,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.326898
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Any,Any,Any,Float64,Float64,Any},String},
) # time: 0.010050932
Base.precompile(
Tuple{Type{MultiCacheLMO{_A,BirkhoffPolytopeLMO,_B}} where {_A,_B},BirkhoffPolytopeLMO},
) # time: 0.007305136
Base.precompile(Tuple{Type{VectorCacheLMO{BirkhoffPolytopeLMO,_A}} where _A,BirkhoffPolytopeLMO}) # time: 0.005527968
Base.precompile(
Tuple{
Core.kwftype(typeof(lazified_conditional_gradient)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:epsilon,
:memory_mode,
:trajectory,
:cache_size,
:verbose,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,Float64,InplaceEmphasis,Bool,Int64,Bool},
},
typeof(lazified_conditional_gradient),
Function,
Function,
BirkhoffPolytopeLMO,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.15854251
Base.precompile(
Tuple{
Core.kwftype(typeof(compute_extreme_point)),
NamedTuple{(:threshold, :greedy),Tuple{Float64,Bool}},
typeof(compute_extreme_point),
MultiCacheLMO{_A,BirkhoffPolytopeLMO} where _A,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.031452376
Base.precompile(Tuple{typeof(length),MultiCacheLMO{_A,BirkhoffPolytopeLMO} where _A}) # time: 0.01073467
Base.precompile(
Tuple{
Core.kwftype(typeof(compute_extreme_point)),
NamedTuple{(:threshold, :greedy),_A} where _A<:Tuple{Any,Bool},
typeof(compute_extreme_point),
MultiCacheLMO{_A,BirkhoffPolytopeLMO} where _A,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.010322329
Base.precompile(
Tuple{
Core.kwftype(typeof(compute_extreme_point)),
NamedTuple{(:threshold, :greedy),Tuple{Float64,Bool}},
typeof(compute_extreme_point),
MultiCacheLMO{500,BirkhoffPolytopeLMO,SparseArrays.SparseMatrixCSC{Float64,Int64}},
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.003286707
Base.precompile(
Tuple{
Core.kwftype(typeof(away_frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:epsilon,
:memory_mode,
:lazy,
:trajectory,
:verbose,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,Float64,InplaceEmphasis,Bool,Bool,Bool},
},
typeof(away_frank_wolfe),
Function,
Function,
BirkhoffPolytopeLMO,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 1.1986277
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_conditional_gradient)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:epsilon,
:memory_mode,
:trajectory,
:verbose,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,Float64,InplaceEmphasis,Bool,Bool},
},
typeof(blended_conditional_gradient),
Function,
Function,
BirkhoffPolytopeLMO,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 1.7452017
Base.precompile(
Tuple{
Core.kwftype(typeof(print_callback)),
NamedTuple{(:print_footer,),Tuple{Bool}},
typeof(print_callback),
Nothing,
String,
},
) # time: 0.007996668
Base.precompile(
Tuple{
typeof(perform_line_search),
Nonconvex{Float64},
Int64,
Nothing,
Nothing,
Vector{Float64},
Vector{Float64},
Vector{Float64},
Float64,
Nothing,
},
) # time: 0.002293631
Base.precompile(Tuple{typeof(fast_dot),Vector{Float64},Int64}) # time: 0.004132393
Base.precompile(Tuple{typeof(compute_extreme_point),LpNormLMO{Float64,2},Int64}) # time: 0.001986683
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:verbose, :line_search, :max_iteration, :print_iter, :trajectory),
Tuple{Bool,Adaptive{Float64,Int64},Int64,Float64,Bool},
},
typeof(frank_wolfe),
Function,
Function,
LpNormLMO{Float64,2},
Vector{Float64},
},
) # time: 0.23070359
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:epsilon,
:trajectory,
),
Tuple{Int64,Agnostic{Float64},Float64,InplaceEmphasis,Bool,Float64,Bool},
},
typeof(frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Float64},
ScaledHotVector{Float64},
},
) # time: 0.7329921
Base.precompile(
Tuple{
Core.kwftype(typeof(away_frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:epsilon,
:trajectory,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Float64,Bool},
},
typeof(away_frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Float64},
ScaledHotVector{Float64},
},
) # time: 0.746063
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_conditional_gradient)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:epsilon,
:trajectory,
),
Tuple{Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Float64,Bool},
},
typeof(blended_conditional_gradient),
Function,
Function,
ProbabilitySimplexOracle{Float64},
ScaledHotVector{Float64},
},
) # time: 1.6212598
Base.precompile(
Tuple{
Core.kwftype(typeof(lp_separation_oracle)),
NamedTuple{(:inplace_loop, :force_fw_step),Tuple{Bool,Bool}},
typeof(lp_separation_oracle),
ProbabilitySimplexOracle{Float64},
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
SparseVector{Float64,Int64},
Float64,
Float64,
},
) # time: 0.001872497
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Shortstep{Float64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Float64},
Vector{Float64},
},
) # time: 0.19531982
Base.precompile(
Tuple{
typeof(perform_line_search),
Shortstep{Float64},
Int64,
Function,
Function,
Vector{Float64},
Vector{Float64},
Vector{Float64},
Float64,
Nothing,
},
) # time: 0.001291007
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Float64,Any,Any,Float64,Float64},String},
) # time: 0.00497477
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Any,Any,Any,Float64,Float64},String},
) # time: 0.003270714
Base.precompile(Tuple{typeof(fast_dot),AbstractVector,Vector{Float64}}) # time: 0.002228764
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Shortstep{Float64},Float64,OutplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Float64},
ScaledHotVector{Float64},
},
) # time: 0.14588983
Base.precompile(Tuple{typeof(-),ScaledHotVector{Float64},ScaledHotVector}) # time: 0.04572138
Base.precompile(
Tuple{
typeof(perform_line_search),
Shortstep{Float64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
ScaledHotVector{Float64},
Any,
Float64,
Nothing,
},
) # time: 0.036659826
Base.precompile(
Tuple{
typeof(perform_line_search),
Shortstep{Float64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
Any,
Any,
Float64,
Nothing,
},
) # time: 0.005265721
Base.precompile(Tuple{typeof(fast_dot),Any,SparseVector{Float64,Int64}}) # time: 0.001681489
Base.precompile(
Tuple{
typeof(perform_line_search),
Shortstep{Float64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
ScaledHotVector{Float64},
Vector{Float64},
Float64,
Nothing,
},
) # time: 0.001473502
Base.precompile(
Tuple{
typeof(perform_line_search),
Shortstep{Float64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
Vector{Float64},
Vector{Float64},
Float64,
Nothing,
},
) # time: 0.001434466
Base.precompile(Tuple{typeof(fast_dot),AbstractVector,SparseVector{Float64,Int64}}) # time: 0.001320551
Base.precompile(
Tuple{
typeof(perform_line_search),
Adaptive{Float64,Int64},
Int64,
Function,
Function,
SparseArrays.SparseMatrixCSC{Float64,Int64},
Matrix{Float64},
Matrix{Float64},
Float64,
Matrix{Float64},
},
) # time: 0.024287857
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Any,Any,Float64,Float64,Float64},String},
) # time: 0.001288076
Base.precompile(
Tuple{
Core.kwftype(typeof(compute_extreme_point)),
NamedTuple{(:threshold, :greedy),Tuple{Float64,Bool}},
typeof(compute_extreme_point),
MultiCacheLMO{
_A,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
} where _A,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.029216602
Base.precompile(
Tuple{
Core.kwftype(typeof(compute_extreme_point)),
NamedTuple{(:threshold, :greedy),_A} where _A<:Tuple{Any,Bool},
typeof(compute_extreme_point),
VectorCacheLMO{
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.010391894
Base.precompile(
Tuple{
Core.kwftype(typeof(compute_extreme_point)),
NamedTuple{(:threshold, :greedy),_A} where _A<:Tuple{Any,Bool},
typeof(compute_extreme_point),
MultiCacheLMO{
_A,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
} where _A,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.005250637
Base.precompile(
Tuple{
typeof(length),
MultiCacheLMO{
_A,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
} where _A,
},
) # time: 0.004705316
Base.precompile(
Tuple{typeof(print_callback),Tuple{String,String,Any,Any,Any,Float64,Float64,Int64},String},
) # time: 0.00435821
Base.precompile(
Tuple{Type{MultiCacheLMO{_A,NuclearNormLMO{Float64},_B}} where {_A,_B},NuclearNormLMO{Float64}},
) # time: 0.00359918
Base.precompile(
Tuple{
Type{
MultiCacheLMO{
_A,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
} where _A,
NuclearNormLMO{Float64},
},
) # time: 0.003546448
Base.precompile(
Tuple{Type{VectorCacheLMO{NuclearNormLMO{Float64},_A}} where _A,NuclearNormLMO{Float64}},
) # time: 0.003143188
Base.precompile(
Tuple{
Core.kwftype(typeof(compute_extreme_point)),
NamedTuple{(:threshold, :greedy),Tuple{Float64,Bool}},
typeof(compute_extreme_point),
VectorCacheLMO{
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
) # time: 0.002158991
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :verbose),
Tuple{Float64,Nonconvex{Float64},Float64,Bool},
},
typeof(frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Float64},
Vector{Float64},
},
) # time: 0.2234393
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(
:epsilon,
:max_iteration,
:print_iter,
:trajectory,
:verbose,
:line_search,
:memory_mode,
:gradient,
),
Tuple{
Float64,
Int64,
Float64,
Bool,
Bool,
Adaptive{Float64,Int64},
InplaceEmphasis,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
},
typeof(frank_wolfe),
Function,
Function,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
) # time: 0.6235743
Base.precompile(
Tuple{
Core.kwftype(typeof(lazified_conditional_gradient)),
NamedTuple{
(
:epsilon,
:max_iteration,
:print_iter,
:trajectory,
:verbose,
:line_search,
:memory_mode,
:gradient,
),
Tuple{
Float64,
Int64,
Float64,
Bool,
Bool,
Adaptive{Float64,Int64},
InplaceEmphasis,
SparseArrays.SparseMatrixCSC{Float64,Int64},
},
},
typeof(lazified_conditional_gradient),
Function,
Function,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
) # time: 0.36729497
Base.precompile(
Tuple{
Core.kwftype(typeof(away_frank_wolfe)),
NamedTuple{
(
:epsilon,
:max_iteration,
:print_iter,
:trajectory,
:verbose,
:lazy,
:line_search,
:memory_mode,
),
Tuple{Float64,Int64,Float64,Bool,Bool,Bool,Adaptive{Float64,Int64},InplaceEmphasis},
},
typeof(away_frank_wolfe),
Function,
Function,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
) # time: 0.828201
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_conditional_gradient)),
NamedTuple{
(
:epsilon,
:max_iteration,
:print_iter,
:trajectory,
:verbose,
:line_search,
:memory_mode,
),
Tuple{Float64,Int64,Float64,Bool,Bool,Adaptive{Float64,Int64},InplaceEmphasis},
},
typeof(blended_conditional_gradient),
Function,
Function,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
) # time: 1.6012237
Base.precompile(
Tuple{
Core.kwftype(typeof(lp_separation_oracle)),
NamedTuple{(:inplace_loop, :force_fw_step),Tuple{Bool,Bool}},
typeof(lp_separation_oracle),
NuclearNormLMO{Float64},
ActiveSet{RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},Float64,Matrix{Float64}},
Matrix{Float64},
Float64,
Float64,
},
) # time: 0.001352328
Base.precompile(
Tuple{
Core.kwftype(typeof(blended_pairwise_conditional_gradient)),
NamedTuple{
(
:epsilon,
:max_iteration,
:print_iter,
:trajectory,
:verbose,
:line_search,
:memory_mode,
),
Tuple{Float64,Int64,Float64,Bool,Bool,Adaptive{Float64,Int64},InplaceEmphasis},
},
typeof(blended_pairwise_conditional_gradient),
Function,
Function,
NuclearNormLMO{Float64},
RankOneMatrix{Float64,Vector{Float64},Vector{Float64}},
},
) # time: 0.34339795
Base.precompile(
Tuple{
typeof(active_set_update!),
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
Float64,
ScaledHotVector{Float64},
Bool,
Nothing,
},
) # time: 0.114226826
Base.precompile(Tuple{Type{ActiveSet},Vector{Tuple{Float64,ScaledHotVector{Float64}}}}) # time: 0.047632866
Base.precompile(
Tuple{
typeof(perform_line_search),
Adaptive{Float64,Int64},
Int64,
Function,
Function,
Vector{Float64},
Vector{Float64},
Vector{Float64},
Float64,
Vector{Float64},
},
) # time: 0.02716949
Base.precompile(
Tuple{
Core.kwftype(typeof(lazy_afw_step)),
NamedTuple{(:lazy_tolerance,),Tuple{Float64}},
typeof(lazy_afw_step),
Vector{Float64},
Vector{Float64},
LpNormLMO{Float64,1},
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
Float64,
Vector{Float64},
},
) # time: 0.009450513
Base.precompile(
Tuple{
typeof(active_set_update!),
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
Float64,
ScaledHotVector{Float64},
Bool,
Int64,
},
) # time: 0.003349358
Base.precompile(
Tuple{
typeof(afw_step),
Vector{Float64},
Vector{Float64},
LpNormLMO{Float64,1},
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
Vector{Float64},
},
) # time: 0.001109981
Base.precompile(
Tuple{
Core.kwftype(typeof(lp_separation_oracle)),
NamedTuple{(:inplace_loop, :force_fw_step),Tuple{Bool,Bool}},
typeof(lp_separation_oracle),
LpNormLMO{Float64,1},
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
SparseVector{Float64,Int64},
Float64,
Float64,
},
) # time: 0.13437502
Base.precompile(
Tuple{
Core.kwftype(typeof(perform_line_search)),
NamedTuple{(:should_upgrade,),Tuple{Val{true}}},
typeof(perform_line_search),
Adaptive{Float64,Int64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
Vector{Float64},
Vector{Float64},
Float64,
Vector{Float64},
},
) # time: 0.10003789
Base.precompile(
Tuple{
typeof(active_set_initialize!),
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
ScaledHotVector{Float64},
},
) # time: 0.02555044
Base.precompile(
Tuple{
typeof(perform_line_search),
Adaptive{Float64,Int64},
Int64,
Function,
Function,
SparseVector{Float64,Int64},
Vector{Float64},
Vector{Float64},
Float64,
Vector{Float64},
},
) # time: 0.009839748
Base.precompile(Tuple{typeof(fast_dot),Vector{BigFloat},Vector{BigFloat}}) # time: 0.003462153
Base.precompile(
Tuple{typeof(compute_extreme_point),LpNormLMO{Float64,1},SparseVector{Float64,Int64}},
) # time: 0.00309479
Base.precompile(
Tuple{
Core.kwftype(typeof(active_set_cleanup!)),
NamedTuple{(:weight_purge_threshold,),Tuple{Float64}},
typeof(active_set_cleanup!),
ActiveSet{ScaledHotVector{Float64},Float64,Vector{Float64}},
},
) # time: 0.001547255
Base.precompile(
Tuple{
typeof(print_callback),
Tuple{String,String,Any,Any,Float64,Float64,Float64,Int64,Int64},
String,
},
) # time: 0.001473014
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :verbose, :memory_mode),
Tuple{Int64,Shortstep{Rational{Int64}},Float64,Bool,OutplaceEmphasis},
},
typeof(frank_wolfe),
Function,
Function,
ProbabilitySimplexOracle{Rational{BigInt}},
ScaledHotVector{Rational{BigInt}},
},
) # time: 0.141858
Base.precompile(Tuple{Type{Shortstep},Rational{Int64}}) # time: 0.00955542
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Shortstep{Float64},Int64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
ScaledBoundL1NormBall{Float64,1,Vector{Float64},Vector{Float64}},
Vector{Float64},
},
) # time: 0.19644113
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Shortstep{Float64},Int64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
ScaledBoundLInfNormBall{Float64,1,Vector{Float64},Vector{Float64}},
Vector{Float64},
},
) # time: 0.046453062
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Shortstep{Float64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
LpNormLMO{Float64,1},
SparseVector{Float64,Int64},
},
) # time: 0.5265395
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(
:max_iteration,
:line_search,
:print_iter,
:memory_mode,
:verbose,
:trajectory,
:momentum,
),
Tuple{Int64,Shortstep{Float64},Float64,OutplaceEmphasis,Bool,Bool,Float64},
},
typeof(frank_wolfe),
Function,
Function,
LpNormLMO{Float64,1},
SparseVector{Float64,Int64},
},
) # time: 0.10808421
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Adaptive{Float64,Int64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
LpNormLMO{Float64,1},
SparseVector{Float64,Int64},
},
) # time: 0.053366497
Base.precompile(
Tuple{
Core.kwftype(typeof(frank_wolfe)),
NamedTuple{
(:max_iteration, :line_search, :print_iter, :memory_mode, :verbose, :trajectory),
Tuple{Int64,Agnostic{Float64},Float64,InplaceEmphasis,Bool,Bool},
},
typeof(frank_wolfe),
Function,
Function,
LpNormLMO{Float64,1},
SparseVector{Float64,Int64},
},
) # time: 0.06719333
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 6506 |
"""
UnitSimplexOracle(right_side)
Represents the scaled unit simplex:
```
C = {x ∈ R^n_+, ∑x ≤ right_side}
```
"""
struct UnitSimplexOracle{T} <: LinearMinimizationOracle
right_side::T
end
UnitSimplexOracle{T}() where {T} = UnitSimplexOracle{T}(one(T))
UnitSimplexOracle(rhs::Integer) = UnitSimplexOracle{Rational{BigInt}}(rhs)
"""
LMO for scaled unit simplex:
`∑ x_i = τ`
Returns either vector of zeros or vector with one active value equal to RHS if
there exists an improving direction.
"""
function compute_extreme_point(lmo::UnitSimplexOracle{T}, direction; v=nothing, kwargs...) where {T}
idx = argmin_(direction)
if direction[idx] < 0
return ScaledHotVector(lmo.right_side, idx, length(direction))
end
return ScaledHotVector(zero(T), idx, length(direction))
end
function convert_mathopt(
lmo::UnitSimplexOracle{T},
optimizer::OT;
dimension::Integer,
use_modify::Bool=true,
kwargs...,
) where {T,OT}
MOI.empty!(optimizer)
τ = lmo.right_side
n = dimension
(x, _) = MOI.add_constrained_variables(optimizer, [MOI.Interval(0.0, 1.0) for _ in 1:n])
MOI.add_constraint(
optimizer,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), x), 0.0),
MOI.LessThan(τ),
)
return MathOptLMO(optimizer, use_modify)
end
"""
Dual costs for a given primal solution to form a primal dual pair
for scaled unit simplex.
Returns two vectors. The first one is the dual costs associated with the constraints
and the second is the reduced costs for the variables.
"""
function compute_dual_solution(::UnitSimplexOracle{T}, direction, primalSolution) where {T}
idx = argmax(primalSolution)
critical = min(direction[idx], 0)
lambda = [critical]
mu = direction .- lambda
return lambda, mu
end
"""
ProbabilitySimplexOracle(right_side)
Represents the scaled probability simplex:
```
C = {x ∈ R^n_+, ∑x = right_side}
```
"""
struct ProbabilitySimplexOracle{T} <: LinearMinimizationOracle
right_side::T
end
ProbabilitySimplexOracle{T}() where {T} = ProbabilitySimplexOracle{T}(one(T))
ProbabilitySimplexOracle(rhs::Integer) = ProbabilitySimplexOracle{Float64}(rhs)
"""
LMO for scaled probability simplex.
Returns a vector with one active value equal to RHS in the
most improving (or least degrading) direction.
"""
function compute_extreme_point(
lmo::ProbabilitySimplexOracle{T},
direction;
v=nothing,
kwargs...,
) where {T}
idx = argmin_(direction)
if idx === nothing
@show direction
end
return ScaledHotVector(lmo.right_side, idx, length(direction))
end
function convert_mathopt(
lmo::ProbabilitySimplexOracle{T},
optimizer::OT;
dimension::Integer,
use_modify=true::Bool,
kwargs...,
) where {T,OT}
MOI.empty!(optimizer)
τ = lmo.right_side
n = dimension
(x, _) = MOI.add_constrained_variables(optimizer, [MOI.Interval(0.0, 1.0) for _ in 1:n])
MOI.add_constraint(
optimizer,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), x), 0.0),
MOI.EqualTo(τ),
)
return MathOptLMO(optimizer, use_modify)
end
"""
Dual costs for a given primal solution to form a primal dual pair
for scaled probability simplex.
Returns two vectors. The first one is the dual costs associated with the constraints
and the second is the reduced costs for the variables.
"""
function compute_dual_solution(
::ProbabilitySimplexOracle{T},
direction,
primal_solution;
kwargs...,
) where {T}
idx = argmax(primal_solution)
lambda = [direction[idx]]
mu = direction .- lambda
return lambda, mu
end
"""
UnitHyperSimplexOracle(radius)
Represents the scaled unit hypersimplex of radius τ, the convex hull of vectors `v` such that:
- v_i ∈ {0, τ}
- ||v||_0 ≤ k
Equivalently, this is the intersection of the K-sparse polytope and the nonnegative orthant.
"""
struct UnitHyperSimplexOracle{T} <: LinearMinimizationOracle
K::Int
radius::T
end
UnitHyperSimplexOracle{T}(K::Integer) where {T} = UnitHyperSimplexOracle{T}(K, one(T))
UnitHyperSimplexOracle(K::Integer, radius::Integer) = UnitHyperSimplexOracle{Rational{BigInt}}(radius)
function compute_extreme_point(
lmo::UnitHyperSimplexOracle{TL},
direction;
v=nothing,
kwargs...,
) where {TL}
T = promote_type(TL, eltype(direction))
n = length(direction)
K = min(lmo.K, n, sum(<(0), direction))
K_indices = sortperm(direction)[1:K]
v = spzeros(T, n)
for idx in 1:K
v[K_indices[idx]] = lmo.radius
end
return v
end
function convert_mathopt(
lmo::UnitHyperSimplexOracle{T},
optimizer::OT;
dimension::Integer,
use_modify::Bool=true,
kwargs...,
) where {T,OT}
MOI.empty!(optimizer)
τ = lmo.radius
n = dimension
(x, _) = MOI.add_constrained_variables(optimizer, [MOI.Interval(0.0, τ) for _ in 1:n])
MOI.add_constraint(
optimizer,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), x), 0.0),
MOI.LessThan(lmo.K * τ),
)
return MathOptLMO(optimizer, use_modify)
end
"""
HyperSimplexOracle(radius)
Represents the scaled hypersimplex of radius τ, the convex hull of vectors `v` such that:
- v_i ∈ {0, τ}
- ||v||_0 = k
Equivalently, this is the convex hull of the vertices of the K-sparse polytope lying in the nonnegative orthant.
"""
struct HyperSimplexOracle{T} <: LinearMinimizationOracle
K::Int
radius::T
end
HyperSimplexOracle{T}(K::Integer) where {T} = HyperSimplexOracle{T}(K, one(T))
HyperSimplexOracle(K::Integer, radius::Integer) = HyperSimplexOracle{Rational{BigInt}}(K, radius)
function compute_extreme_point(
lmo::HyperSimplexOracle{TL},
direction;
v=nothing,
kwargs...,
) where {TL}
T = promote_type(TL, eltype(direction))
n = length(direction)
K = min(lmo.K, n)
K_indices = sortperm(direction)[1:K]
v = spzeros(T, n)
for idx in 1:K
v[K_indices[idx]] = lmo.radius
end
return v
end
function convert_mathopt(
lmo::HyperSimplexOracle{T},
optimizer::OT;
dimension::Integer,
use_modify::Bool=true,
kwargs...,
) where {T,OT}
MOI.empty!(optimizer)
τ = lmo.radius
n = dimension
(x, _) = MOI.add_constrained_variables(optimizer, [MOI.Interval(0.0, τ) for _ in 1:n])
MOI.add_constraint(
optimizer,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), x), 0.0),
MOI.EqualTo(lmo.K * τ),
)
return MathOptLMO(optimizer, use_modify)
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 1297 | """
A function acting like the normal `grad!`
but tracking the number of calls.
"""
mutable struct TrackingGradient{G} <: Function
grad!::G
counter::Int
end
TrackingGradient(grad!) = TrackingGradient(grad!, 0)
function (tg::TrackingGradient)(storage, x)
tg.counter += 1
return tg.grad!(storage, x)
end
"""
A function acting like the normal objective `f`
but tracking the number of calls.
"""
mutable struct TrackingObjective{F} <: Function
f::F
counter::Int
end
TrackingObjective(f) = TrackingObjective(f, 0)
function (tf::TrackingObjective)(x)
tf.counter += 1
return tf.f(x)
end
function wrap_objective(to::TrackingObjective)
function f(x)
to.counter += 1
return to.f(x)
end
function grad!(storage, x)
to.counter += 1
return to.g(storage, x)
end
return (f, grad!)
end
"""
TrackingLMO{LMO}(lmo)
An LMO wrapping another one and tracking the number of calls.
"""
mutable struct TrackingLMO{LMO} <: LinearMinimizationOracle
lmo::LMO
counter::Int
end
function compute_extreme_point(lmo::TrackingLMO, x; kwargs...)
lmo.counter += 1
return compute_extreme_point(lmo.lmo, x)
end
is_tracking_lmo(lmo) = false
is_tracking_lmo(lmo::TrackingLMO) = true
TrackingLMO(lmo) = TrackingLMO(lmo, 0)
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 10424 |
"""
ScaledHotVector{T}
Represents a vector of at most one value different from 0.
"""
struct ScaledHotVector{T} <: AbstractVector{T}
active_val::T
val_idx::Int
len::Int
end
Base.size(v::ScaledHotVector) = (v.len,)
@inline function Base.getindex(v::ScaledHotVector{T}, idx::Integer) where {T}
@boundscheck if !(1 ≤ idx ≤ length(v))
throw(BoundsError(v, idx))
end
if v.val_idx != idx
return zero(T)
end
return v.active_val
end
Base.sum(v::ScaledHotVector) = v.active_val
function LinearAlgebra.dot(v1::ScaledHotVector{<:Number}, v2::AbstractVector{<:Number})
return conj(v1.active_val) * v2[v1.val_idx]
end
function LinearAlgebra.dot(v1::ScaledHotVector{<:Number}, v2::SparseArrays.SparseVector{<:Number})
return conj(v1.active_val) * v2[v1.val_idx]
end
LinearAlgebra.dot(v1::AbstractVector{<:Number}, v2::ScaledHotVector{<:Number}) = conj(dot(v2, v1))
LinearAlgebra.dot(v1::SparseArrays.SparseVector{<:Number}, v2::ScaledHotVector{<:Number}) =
conj(dot(v2, v1))
function LinearAlgebra.dot(v1::ScaledHotVector{<:Number}, v2::ScaledHotVector{<:Number})
if length(v1) != length(v2)
throw(DimensionMismatch("v1 and v2 do not have matching sizes"))
end
return conj(v1.active_val) * v2.active_val * (v1.val_idx == v2.val_idx)
end
LinearAlgebra.norm(v::ScaledHotVector) = abs(v.active_val)
function Base.:*(v::ScaledHotVector, x::Number)
return ScaledHotVector(v.active_val * x, v.val_idx, v.len)
end
Base.:*(x::Number, v::ScaledHotVector) = v * x
function Base.:+(x::ScaledHotVector, y::AbstractVector)
if length(x) != length(y)
throw(DimensionMismatch())
end
yc = Base.copymutable(y)
@inbounds yc[x.val_idx] += x.active_val
return yc
end
Base.:+(y::AbstractVector, x::ScaledHotVector) = x + y
function Base.:+(x::ScaledHotVector{T1}, y::ScaledHotVector{T2}) where {T1,T2}
n = length(x)
T = promote_type(T1, T2)
if n != length(y)
throw(DimensionMismatch())
end
res = spzeros(T, n)
@inbounds res[x.val_idx] = x.active_val
@inbounds res[y.val_idx] += y.active_val
return res
end
Base.:-(x::ScaledHotVector{T}) where {T} = ScaledHotVector{T}(-x.active_val, x.val_idx, x.len)
Base.:-(x::AbstractVector, y::ScaledHotVector) = +(x, -y)
Base.:-(x::ScaledHotVector, y::AbstractVector) = +(x, -y)
Base.:-(x::ScaledHotVector, y::ScaledHotVector) = +(x, -y)
Base.similar(v::ScaledHotVector{T}) where {T} = spzeros(T, length(v))
function Base.convert(::Type{Vector{T}}, v::ScaledHotVector) where {T}
vc = zeros(T, v.len)
vc[v.val_idx] = v.active_val
return vc
end
function Base.isequal(a::ScaledHotVector, b::ScaledHotVector)
return a.len == b.len && a.val_idx == b.val_idx && isequal(a.active_val, b.active_val)
end
function Base.copyto!(dst::SparseArrays.SparseVector, src::ScaledHotVector)
for idx in eachindex(src)
dst[idx] = 0
end
SparseArrays.dropzeros!(dst)
dst[src.val_idx] = src.active_val
return dst
end
function active_set_update_scale!(x::IT, lambda, atom::ScaledHotVector) where {IT}
x .*= (1 - lambda)
x[atom.val_idx] += lambda * atom.active_val
return x
end
"""
RankOneMatrix{T, UT, VT}
Represents a rank-one matrix `R = u * vt'`.
Composes like a charm.
"""
struct RankOneMatrix{T,UT<:AbstractVector,VT<:AbstractVector} <: AbstractMatrix{T}
u::UT
v::VT
end
function RankOneMatrix(u::UT, v::VT) where {UT,VT}
T = promote_type(eltype(u), eltype(v))
return RankOneMatrix{T,UT,VT}(u, v)
end
# not checking indices
Base.@propagate_inbounds function Base.getindex(R::RankOneMatrix, i, j)
@boundscheck (checkbounds(R.u, i); checkbounds(R.v, j))
@inbounds R.u[i] * R.v[j]
end
Base.size(R::RankOneMatrix) = (length(R.u), length(R.v))
function Base.:*(R::RankOneMatrix, v::AbstractVector)
temp = fast_dot(R.v, v)
return R.u * temp
end
function Base.:*(R::RankOneMatrix, M::AbstractMatrix)
temp = R.v' * M
return RankOneMatrix(R.u, temp')
end
function Base.:*(R1::RankOneMatrix, R2::RankOneMatrix)
# middle product
temp = fast_dot(R1.v, R2.u)
return RankOneMatrix(R1.u * temp, R2.v)
end
Base.Matrix(R::RankOneMatrix) = R.u * R.v'
Base.collect(R::RankOneMatrix) = Matrix(R)
Base.copymutable(R::RankOneMatrix) = Matrix(R)
Base.copy(R::RankOneMatrix) = RankOneMatrix(copy(R.u), copy(R.v))
function Base.convert(::Type{<:RankOneMatrix{T,Vector{T},Vector{T}}}, R::RankOneMatrix) where {T}
return RankOneMatrix(convert(Vector{T}, R.u), convert(Vector{T}, R.v))
end
function LinearAlgebra.dot(
R::RankOneMatrix{T1},
S::SparseArrays.AbstractSparseMatrixCSC{T2},
) where {T1<:Real,T2<:Real}
(m, n) = size(R)
T = promote_type(T1, T2)
if (m, n) != size(S)
throw(DimensionMismatch("Size mismatch"))
end
s = zero(T)
if m * n == 0
return s
end
rows = SparseArrays.rowvals(S)
vals = SparseArrays.nonzeros(S)
@inbounds for j in 1:n
for ridx in SparseArrays.nzrange(S, j)
i = rows[ridx]
v = vals[ridx]
s += v * R.u[i] * R.v[j]
end
end
return s
end
LinearAlgebra.dot(R::RankOneMatrix, M::Matrix) = dot(R.u, M, R.v)
LinearAlgebra.dot(M::Matrix, R::RankOneMatrix) = conj(dot(R, M))
Base.@propagate_inbounds function Base.:-(a::RankOneMatrix, b::RankOneMatrix)
@boundscheck size(a) == size(b) || throw(DimensionMismatch())
r = similar(a)
@inbounds for j in 1:size(a, 2)
for i in 1:size(a, 1)
r[i, j] = a.u[i] * a.v[j] - b.u[i] * b.v[j]
end
end
return r
end
Base.:-(x::RankOneMatrix) = RankOneMatrix(-x.u, x.v)
Base.:*(x::Number, m::RankOneMatrix) = RankOneMatrix(x * m.u, m.v)
Base.:*(m::RankOneMatrix, x::Number) = RankOneMatrix(x * m.u, m.v)
Base.@propagate_inbounds function Base.:+(a::RankOneMatrix, b::RankOneMatrix)
@boundscheck size(a) == size(b) || throw(DimensionMismatch())
r = similar(a)
@inbounds for j in 1:size(a, 2)
for i in 1:size(a, 1)
r[i, j] = a.u[i] * a.v[j] + b.u[i] * b.v[j]
end
end
return r
end
LinearAlgebra.norm(R::RankOneMatrix) = norm(R.u) * norm(R.v)
Base.@propagate_inbounds function Base.isequal(a::RankOneMatrix, b::RankOneMatrix)
if size(a) != size(b)
return false
end
if isequal(a.u, b.u) && isequal(a.v, b.v)
return true
end
# needs to check actual values
@inbounds for j in 1:size(a, 2)
for i in 1:size(a, 1)
if !isequal(a.u[i] * a.v[j], b.u[i] * b.v[j])
return false
end
end
end
return true
end
Base.@propagate_inbounds function muladd_memory_mode(::InplaceEmphasis, d::Matrix, x::Union{RankOneMatrix, Matrix}, v::RankOneMatrix)
@boundscheck size(d) == size(x) || throw(DimensionMismatch())
@boundscheck size(d) == size(v) || throw(DimensionMismatch())
m, n = size(d)
@inbounds for j in 1:n
for i in 1:m
d[i,j] = x[i,j] - v[i,j]
end
end
return d
end
Base.@propagate_inbounds function muladd_memory_mode(::InplaceEmphasis, x::Matrix, gamma::Real, d::RankOneMatrix)
@boundscheck size(d) == size(x) || throw(DimensionMismatch())
m, n = size(x)
@inbounds for j in 1:n
for i in 1:m
x[i,j] -= gamma * d[i,j]
end
end
return x
end
"""
SymmetricArray{T, DT}
"""
struct SymmetricArray{HasMultiplicities,T,DT,V<:AbstractVector{T}} <: AbstractVector{T}
data::DT # full array to be symmetrised, will generally fall out of sync wrt vec
vec::V # vector representing the array
mul::Vector{T} # only used for scalar products
end
function SymmetricArray(data::DT, vec::V) where {DT,V<:AbstractVector{T}} where {T}
return SymmetricArray{false,T,DT,V}(data, vec, T[])
end
function SymmetricArray(data::DT, vec::V, mul::Vector) where {DT,V<:AbstractVector{T}} where {T}
return SymmetricArray{true,T,DT,V}(data, vec, convert(Vector{T}, mul))
end
Base.@propagate_inbounds function Base.getindex(A::SymmetricArray, i)
@boundscheck checkbounds(A.vec, i)
return @inbounds getindex(A.vec, i)
end
Base.@propagate_inbounds function Base.setindex!(A::SymmetricArray, x, i)
@boundscheck checkbounds(A.vec, i)
return @inbounds setindex!(A.vec, x, i)
end
Base.size(A::SymmetricArray) = size(A.vec)
Base.eltype(A::SymmetricArray) = eltype(A.vec)
Base.similar(A::SymmetricArray{true}) = SymmetricArray(similar(A.data), similar(A.vec), A.mul)
Base.similar(A::SymmetricArray{false}) = SymmetricArray(similar(A.data), similar(A.vec))
Base.similar(A::SymmetricArray{true}, ::Type{T}) where {T} = SymmetricArray(similar(A.data, T), similar(A.vec, T), convert(Vector{T}, A.mul))
Base.similar(A::SymmetricArray{false}, ::Type{T}) where {T} = SymmetricArray(similar(A.data, T), similar(A.vec, T))
Base.collect(A::SymmetricArray{true}) = SymmetricArray(collect(A.data), collect(A.vec), A.mul)
Base.collect(A::SymmetricArray{false}) = SymmetricArray(collect(A.data), collect(A.vec))
Base.copyto!(dest::SymmetricArray, src::SymmetricArray) = copyto!(dest.vec, src.vec)
Base.:*(scalar::Real, A::SymmetricArray{true}) = SymmetricArray(A.data, scalar * A.vec, A.mul)
Base.:*(scalar::Real, A::SymmetricArray{false}) = SymmetricArray(A.data, scalar * A.vec)
Base.:*(A::SymmetricArray, scalar::Real) = scalar * A
Base.:/(A::SymmetricArray, scalar::Real) = inv(scalar) * A
Base.:+(A1::SymmetricArray{true,T}, A2::SymmetricArray{true,T}) where {T} = SymmetricArray(A1.data, A1.vec + A2.vec, A1.mul)
Base.:+(A1::SymmetricArray{false,T}, A2::SymmetricArray{false,T}) where {T} = SymmetricArray(A1.data, A1.vec + A2.vec)
Base.:-(A1::SymmetricArray{true,T}, A2::SymmetricArray{true,T}) where {T} = SymmetricArray(A1.data, A1.vec - A2.vec, A1.mul)
Base.:-(A1::SymmetricArray{false,T}, A2::SymmetricArray{false,T}) where {T} = SymmetricArray(A1.data, A1.vec - A2.vec)
Base.:-(A::SymmetricArray{true,T}) where {T} = SymmetricArray(A.data, -A.vec, A.mul)
Base.:-(A::SymmetricArray{false,T}) where {T} = SymmetricArray(A.data, -A.vec)
LinearAlgebra.dot(A1::SymmetricArray{true}, A2::SymmetricArray{true}) = dot(A1.vec, Diagonal(A1.mul), A2.vec)
LinearAlgebra.dot(A1::SymmetricArray{false}, A2::SymmetricArray{false}) = dot(A1.vec, A2.vec)
LinearAlgebra.norm(A::SymmetricArray) = sqrt(dot(A, A))
Base.@propagate_inbounds Base.isequal(A1::SymmetricArray, A2::SymmetricArray) = isequal(A1.vec, A2.vec)
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 10830 |
##############################
### memory_mode macro
##############################
macro memory_mode(memory_mode, ex)
return esc(quote
if $memory_mode isa InplaceEmphasis
@. $ex
else
$ex
end
end)
end
"""
muladd_memory_mode(memory_mode::MemoryEmphasis, d, x, v)
Performs `d = x - v` in-place or not depending on MemoryEmphasis
"""
function muladd_memory_mode(memory_mode::MemoryEmphasis, d, x, v)
@memory_mode(memory_mode, d = x - v)
end
"""
(memory_mode::MemoryEmphasis, x, gamma::Real, d)
Performs `x = x - gamma * d` in-place or not depending on MemoryEmphasis
"""
function muladd_memory_mode(memory_mode::MemoryEmphasis, x, gamma::Real, d)
@memory_mode(memory_mode, x = x - gamma * d)
end
"""
(memory_mode::MemoryEmphasis, storage, x, gamma::Real, d)
Performs `storage = x - gamma * d` in-place or not depending on MemoryEmphasis
"""
function muladd_memory_mode(memory_mode::MemoryEmphasis, storage, x, gamma::Real, d)
@memory_mode(memory_mode, storage = x - gamma * d)
end
##############################################################
# simple benchmark of elementary costs of oracles and
# critical components
##############################################################
function benchmark_oracles(f, grad!, x_gen, lmo; k=100, nocache=true)
x = x_gen()
sv = sizeof(x) / 1024^2
println("\nSize of single atom ($(eltype(x))): $sv MB\n")
to = TimerOutput()
@showprogress 1 "Testing f... " for i in 1:k
x = x_gen()
@timeit to "f" temp = f(x)
end
@showprogress 1 "Testing grad... " for i in 1:k
x = x_gen()
temp = similar(x)
@timeit to "grad" grad!(temp, x)
end
@showprogress 1 "Testing lmo... " for i in 1:k
x = x_gen()
@timeit to "lmo" temp = compute_extreme_point(lmo, x)
end
@showprogress 1 "Testing dual gap... " for i in 1:k
x = x_gen()
gradient = collect(x)
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient)
@timeit to "dual gap" begin
dual_gap = fast_dot(x, gradient) - fast_dot(v, gradient)
end
end
@showprogress 1 "Testing update... (Emphasis: OutplaceEmphasis) " for i in 1:k
x = x_gen()
gradient = collect(x)
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient)
gamma = 1 / 2
@timeit to "update (OutplaceEmphasis)" @memory_mode(
OutplaceEmphasis(),
x = (1 - gamma) * x + gamma * v
)
end
@showprogress 1 "Testing update... (Emphasis: InplaceEmphasis) " for i in 1:k
x = x_gen()
gradient = collect(x)
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient)
gamma = 1 / 2
# TODO: to be updated to broadcast version once data structure ScaledHotVector allows for it
@timeit to "update (InplaceEmphasis)" @memory_mode(
InplaceEmphasis(),
x = (1 - gamma) * x + gamma * v
)
end
if !nocache
@showprogress 1 "Testing caching 100 points... " for i in 1:k
@timeit to "caching 100 points" begin
cache = [gen_x() for _ in 1:100]
x = gen_x()
gradient = collect(x)
grad!(gradient, x)
v = compute_extreme_point(lmo, gradient)
gamma = 1 / 2
test = (x -> fast_dot(x, gradient)).(cache)
v = cache[argmin(test)]
val = v in cache
end
end
end
print_timer(to)
return nothing
end
"""
_unsafe_equal(a, b)
Like `isequal` on arrays but without the checks. Assumes a and b have the same axes.
"""
function _unsafe_equal(a::Array, b::Array)
if a === b
return true
end
@inbounds for idx in eachindex(a)
if a[idx] != b[idx]
return false
end
end
return true
end
_unsafe_equal(a, b) = isequal(a, b)
function _unsafe_equal(a::SparseArrays.AbstractSparseArray, b::SparseArrays.AbstractSparseArray)
return a == b
end
fast_dot(A, B) = dot(A, B)
fast_dot(B::SparseArrays.SparseMatrixCSC, A::Matrix) = conj(fast_dot(A, B))
function fast_dot(A::Matrix{T1}, B::SparseArrays.SparseMatrixCSC{T2}) where {T1,T2}
T = promote_type(T1, T2)
(m, n) = size(A)
if (m, n) != size(B)
throw(DimensionMismatch("Size mismatch"))
end
s = zero(T)
if m * n == 0
return s
end
rows = SparseArrays.rowvals(B)
vals = SparseArrays.nonzeros(B)
@inbounds for j in 1:n
for ridx in SparseArrays.nzrange(B, j)
i = rows[ridx]
v = vals[ridx]
s += v * conj(A[i, j])
end
end
return s
end
"""
trajectory_callback(storage)
Callback pushing the state at each iteration to the passed storage.
The state data is only the 5 first fields, usually:
`(t,primal,dual,dual_gap,time)`
"""
function trajectory_callback(storage)
return function push_trajectory!(data, args...)
return push!(storage, callback_state(data))
end
end
"""
momentum_iterate(iter::MomentumIterator) -> ρ
Method to implement for a type `MomentumIterator`.
Returns the next momentum value `ρ` and updates the iterator internal state.
"""
function momentum_iterate end
"""
ExpMomentumIterator{T}
Iterator for the momentum used in the variant of Stochastic Frank-Wolfe.
Momentum coefficients are the values of the iterator:
`ρ_t = 1 - num / (offset + t)^exp`
The state corresponds to the iteration count.
Source:
Stochastic Conditional Gradient Methods: From Convex Minimization to Submodular Maximization
Aryan Mokhtari, Hamed Hassani, Amin Karbasi, JMLR 2020.
"""
mutable struct ExpMomentumIterator{T}
exp::T
num::T
offset::T
iter::Int
end
ExpMomentumIterator() = ExpMomentumIterator(2 / 3, 4.0, 8.0, 0)
function momentum_iterate(em::ExpMomentumIterator)
em.iter += 1
return 1 - em.num / (em.offset + em.iter)^(em.exp)
end
"""
ConstantMomentumIterator{T}
Iterator for momentum with a fixed damping value, always return the value and a dummy state.
"""
struct ConstantMomentumIterator{T}
v::T
end
momentum_iterate(em::ConstantMomentumIterator) = em.v
# batch sizes
"""
batchsize_iterate(iter::BatchSizeIterator) -> b
Method to implement for a batch size iterator of type `BatchSizeIterator`.
Calling `batchsize_iterate` returns the next batch size and typically update the internal state of `iter`.
"""
function batchsize_iterate end
"""
ConstantBatchIterator(batch_size)
Batch iterator always returning a constant batch size.
"""
struct ConstantBatchIterator
batch_size::Int
end
batchsize_iterate(cbi::ConstantBatchIterator) = cbi.batch_size
"""
IncrementBatchIterator(starting_batch_size, max_batch_size, [increment = 1])
Batch size starting at starting_batch_size and incrementing by `increment` at every iteration.
"""
mutable struct IncrementBatchIterator
starting_batch_size::Int
max_batch_size::Int
increment::Int
iter::Int
maxreached::Bool
end
function IncrementBatchIterator(starting_batch_size::Int, max_batch_size::Int, increment::Int)
return IncrementBatchIterator(starting_batch_size, max_batch_size, increment, 0, false)
end
function IncrementBatchIterator(starting_batch_size::Int, max_batch_size::Int)
return IncrementBatchIterator(starting_batch_size, max_batch_size, 1, 0, false)
end
function batchsize_iterate(ibi::IncrementBatchIterator)
if ibi.maxreached
return ibi.max_batch_size
end
new_size = ibi.starting_batch_size + ibi.iter * ibi.increment
ibi.iter += 1
if new_size > ibi.max_batch_size
ibi.maxreached = true
return ibi.max_batch_size
end
return new_size
end
"""
Vertex storage to store dropped vertices or find a suitable direction in lazy settings.
The algorithm will look for at most `return_kth` suitable atoms before returning the best.
See [Extra-lazification with a vertex storage](@ref) for usage.
A vertex storage can be any type that implements two operations:
1. `Base.push!(storage, atom)` to add an atom to the storage.
Note that it is the storage type responsibility to ensure uniqueness of the atoms present.
2. `storage_find_argmin_vertex(storage, direction, lazy_threshold) -> (found, vertex)`
returning whether a vertex with sufficient progress was found and the vertex.
It is up to the storage to remove vertices (or not) when they have been picked up.
"""
struct DeletedVertexStorage{AT}
storage::Vector{AT}
return_kth::Int
end
DeletedVertexStorage(storage::Vector) = DeletedVertexStorage(storage, 1)
DeletedVertexStorage{AT}() where {AT} = DeletedVertexStorage(AT[])
function Base.push!(vertex_storage::DeletedVertexStorage{AT}, atom::AT) where {AT}
# do not push duplicates
if !any(v -> _unsafe_equal(atom, v), vertex_storage.storage)
push!(vertex_storage.storage, atom)
end
return vertex_storage
end
Base.length(storage::DeletedVertexStorage) = length(storage.storage)
"""
Give the vertex `v` in the storage that minimizes `s = direction ⋅ v` and whether `s` achieves
`s ≤ lazy_threshold`.
"""
function storage_find_argmin_vertex(vertex_storage::DeletedVertexStorage, direction, lazy_threshold)
if isempty(vertex_storage.storage)
return (false, nothing)
end
best_idx = 1
best_val = lazy_threshold
found_good = false
counter = 0
for (idx, atom) in enumerate(vertex_storage.storage)
s = dot(direction, atom)
if s < best_val
counter += 1
best_val = s
found_good = true
best_idx = idx
if counter ≥ vertex_storage.return_kth
return (found_good, vertex_storage.storage[best_idx])
end
end
end
return (found_good, vertex_storage.storage[best_idx])
end
# temporary fix because argmin is broken on julia 1.8
argmin_(v) = argmin(v)
function argmin_(v::SparseArrays.SparseVector{T}) where {T}
if isempty(v.nzind)
return 1
end
idx = -1
val = T(Inf)
for s_idx in eachindex(v.nzind)
if v.nzval[s_idx] < val
val = v.nzval[s_idx]
idx = s_idx
end
end
# if min value is already negative or the indices were all checked
if val < 0 || length(v.nzind) == length(v)
return v.nzind[idx]
end
# otherwise, find the first zero
for idx in eachindex(v)
if idx ∉ v.nzind
return idx
end
end
error("unreachable")
end
function weight_purge_threshold_default(::Type{T}) where {T<:AbstractFloat}
return sqrt(eps(T) * Base.rtoldefault(T)) # around 1e-12 for Float64
end
weight_purge_threshold_default(::Type{T}) where {T<:Number} = Base.rtoldefault(T)
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 8741 | using Test
using FrankWolfe
import FrankWolfe: ActiveSet
using LinearAlgebra: norm
@testset "Active sets" begin
@testset "Constructors and eltypes" begin
active_set = ActiveSet([(0.1, [1, 2, 3]), (0.9, [2, 3, 4]), (0.0, [5, 6, 7])])
@test active_set.weights == [0.1, 0.9, 0.0]
@test active_set.atoms == [[1, 2, 3], [2, 3, 4], [5, 6, 7]]
@test eltype(active_set) === Tuple{Float64,Vector{Int}}
@test FrankWolfe.active_set_validate(active_set)
# providing the weight type converts the provided weights
active_set2 = ActiveSet{Vector{Int},Float64}([
(0.1f0, [1, 2, 3]),
(0.9f0, [2, 3, 4]),
(0.0f0, [5, 6, 7]),
])
@test eltype(active_set) === eltype(active_set2)
@test first(active_set) isa eltype(active_set)
@test first(active_set2) isa eltype(active_set)
end
@testset "Presence and cleanup" begin
active_set = ActiveSet([(0.1, [1, 2, 3]), (0.9, [2, 3, 4]), (0.0, [5, 6, 7])])
@test FrankWolfe.find_atom(active_set, [5, 6, 7]) > 0
FrankWolfe.active_set_cleanup!(active_set)
@test FrankWolfe.find_atom(active_set, [5, 6, 7]) == -1
end
@testset "Renormalization and validation" begin
active_set = ActiveSet([(0.1, [1, 2, 3]), (0.8, [2, 3, 4]), (0.0, [5, 6, 7])])
@test !FrankWolfe.active_set_validate(active_set)
FrankWolfe.active_set_renormalize!(active_set)
@test FrankWolfe.active_set_validate(active_set)
end
@testset "addition of elements and manipulation" begin
active_set = ActiveSet([(0.5, [1, 2, 3]), (0.5, [2, 3, 4])])
FrankWolfe.active_set_update!(active_set, 1 / 2, [5, 6, 7])
@test collect(active_set) == [(0.25, [1, 2, 3]), (0.25, [2, 3, 4]), (0.5, [5, 6, 7])]
# element addition
@test FrankWolfe.active_set_validate(active_set)
# update existing element
FrankWolfe.active_set_update!(active_set, 1.0 / 2, [5, 6, 7])
@test collect(active_set) == [(0.125, [1, 2, 3]), (0.125, [2, 3, 4]), (0.75, [5, 6, 7])]
@test FrankWolfe.active_set_validate(active_set)
end
@testset "active set isempty" begin
active_set = ActiveSet([(1.0, [1, 2, 3])])
@test !isempty(active_set)
empty!(active_set)
@test isempty(active_set)
end
@testset "Away step operations" begin
active_set = ActiveSet([(0.125, [1, 2, 3]), (0.125, [2, 3, 4]), (0.75, [5, 6, 7])])
lambda = FrankWolfe.weight_from_atom(active_set, [5, 6, 7])
@test lambda == 0.75
lambda_max = lambda / (1 - lambda)
FrankWolfe.active_set_update!(active_set, -lambda_max, [5, 6, 7])
@test collect(active_set) == [(0.5, [1, 2, 3]), (0.5, [2, 3, 4])]
## intermediate away step
lambda = FrankWolfe.weight_from_atom(active_set, [2, 3, 4])
@test lambda == 0.5
lambda_max = lambda / (1 - lambda)
FrankWolfe.active_set_update!(active_set, -lambda_max / 2, [2, 3, 4])
@test collect(active_set) == [(0.75, [1, 2, 3]), (0.25, [2, 3, 4])]
x = FrankWolfe.get_active_set_iterate(active_set)
@test x == [1.25, 2.25, 3.25]
λ, a, i = FrankWolfe.active_set_argmin(active_set, [1.0, 1.0, 1.0])
@test a == [1, 2, 3] && λ == 0.75 && i == 1
λ, a, i = FrankWolfe.active_set_argmin(active_set, [-1.0, -1.0, -1.0])
@test a == [2, 3, 4] && λ == 0.25 && i == 2
end
@testset "Copying active sets" begin
active_set = ActiveSet([(0.125, [1, 2, 3]), (0.125, [2, 3, 4]), (0.75, [5, 6, 7])])
as_copy = copy(active_set)
# copy is of same type
@test as_copy isa ActiveSet{Vector{Int},Float64,Vector{Float64}}
# copy fields are also copied, same value different location in memory
@test as_copy.weights !== active_set.weights
@test as_copy.weights == active_set.weights
@test as_copy.x !== active_set.x
@test as_copy.x == active_set.x
@test as_copy.atoms !== active_set.atoms
@test as_copy.atoms == active_set.atoms
# Individual atoms are not copied
@test as_copy.atoms[1] === active_set.atoms[1]
end
end
@testset "Simplex gradient descent" begin
# Gradient descent over a 2-D unit simplex
# each atom is a vertex, direction points to [1,1]
# note: integers for atom element types
# |\ - - +
# | \ |
# | \
# | \ |
# | \
# | \ |
# |______\|
active_set = ActiveSet([(0.5, [0, 0]), (0.5, [0, 1]), (0.0, [1, 0])])
x = FrankWolfe.get_active_set_iterate(active_set)
@test x ≈ [0, 0.5]
f(x) = (x[1] - 1)^2 + (x[2] - 1)^2
gradient = similar(x)
function grad!(storage, x)
return storage .= [2 * (x[1] - 1), 2 * (x[2] - 1)]
end
FrankWolfe.simplex_gradient_descent_over_convex_hull(
f,
grad!,
gradient,
active_set,
1e-3,
1,
0.0,
0,
max_iteration=1000,
callback=nothing,
)
FrankWolfe.active_set_cleanup!(active_set)
@test length(active_set) == 2
@test [1, 0] ∈ active_set.atoms
@test [0, 1] ∈ active_set.atoms
active_set2 = ActiveSet([(0.5, [0, 0]), (0.0, [0, 1]), (0.5, [1, 0])])
x2 = FrankWolfe.get_active_set_iterate(active_set2)
@test x2 ≈ [0.5, 0]
FrankWolfe.simplex_gradient_descent_over_convex_hull(
f,
grad!,
gradient,
active_set2,
1e-3,
1,
0.0,
0,
max_iteration=1000,
callback=nothing,
)
@test length(active_set) == 2
@test [1, 0] ∈ active_set.atoms
@test [0, 1] ∈ active_set.atoms
@test FrankWolfe.get_active_set_iterate(active_set2) ≈ [0.5, 0.5]
# updating again (at optimum) triggers the active set emptying
for as in (active_set, active_set2)
x = FrankWolfe.get_active_set_iterate(as)
number_of_steps = FrankWolfe.simplex_gradient_descent_over_convex_hull(
f,
grad!,
gradient,
as,
1.0e-3,
1,
0.0,
0,
max_iteration=1000,
callback=nothing,
)
@test number_of_steps == 0
end
end
@testset "LP separation oracle" begin
# Gradient descent over a L-inf ball of radius one
# current active set contains 3 vertices
# direction points to [1,1]
# |\ - - +
# | \ |
# | \
# | \ |
# | \
# | \ |
# |______\|
active_set = ActiveSet([(0.6, [-1, -1]), (0.2, [0, 1]), (0.2, [1, 0])])
f(x) = (x[1] - 1)^2 + (x[2] - 1)^2
∇f(x) = [2 * (x[1] - 1), 2 * (x[2] - 1)]
lmo = FrankWolfe.LpNormLMO{Inf}(1)
x = FrankWolfe.get_active_set_iterate(active_set)
@test x ≈ [-0.4, -0.4]
gradient_dir = ∇f(x)
(y, _) = FrankWolfe.lp_separation_oracle(lmo, active_set, gradient_dir, 0.5, 1)
@test y ∈ active_set.atoms
(y2, _) =
FrankWolfe.lp_separation_oracle(lmo, active_set, gradient_dir, 3 + dot(x, gradient_dir), 1)
# found new vertex not in active set
@test y2 ∉ active_set.atoms
# Criterion too high, no satisfactory point
(y3, _) = FrankWolfe.lp_separation_oracle(
lmo,
active_set,
gradient_dir,
norm(gradient_dir)^2 + dot(x, gradient_dir),
1,
)
end
@testset "Argminmax" begin
active_set = FrankWolfe.ActiveSet([(0.6, [-1, -1]), (0.2, [0, 1]), (0.2, [1, 0])])
(λ_min, a_min, i_min, val, λ_max, a_max, i_max, valM, progress) =
FrankWolfe.active_set_argminmax(active_set, [1, 1.5])
@test i_min == 1
@test i_max == 2
@test_throws ErrorException FrankWolfe.active_set_argminmax(active_set, [NaN, NaN])
end
@testset "LPseparationWithScaledHotVector" begin
v1 = FrankWolfe.ScaledHotVector(1, 1, 2)
v2 = FrankWolfe.ScaledHotVector(1, 2, 2)
v3 = FrankWolfe.ScaledHotVector(0, 2, 2)
active_set = FrankWolfe.ActiveSet([(0.6, v1), (0.2, v2), (0.2, v3)])
lmo = FrankWolfe.LpNormLMO{Float64,1}(1.0)
direction = ones(2)
min_gap = 0.5
Ktolerance = 1.0
FrankWolfe.lp_separation_oracle(
lmo,
active_set,
direction,
min_gap,
Ktolerance;
inplace_loop=true,
)
end
@testset "ActiveSet for BigFloat" begin
n = Int(1e2)
lmo = FrankWolfe.LpNormLMO{BigFloat,1}(rand())
x0 = Vector(FrankWolfe.compute_extreme_point(lmo, zeros(n)))
# add the first vertex to active set from initialization
active_set = FrankWolfe.ActiveSet([(1.0, x0)])
# ensure that ActiveSet is created correctly, tests a fix for a bug when x0 is a BigFloat
@test length(FrankWolfe.ActiveSet([(1.0, x0)])) == 1
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 7336 | using FrankWolfe
using LinearAlgebra
using Test
using SparseArrays
function test_callback(state, active_set, args...)
grad0 = similar(state.x)
state.grad!(grad0, state.x)
@test grad0 ≈ state.gradient
end
@testset "Testing active set Frank-Wolfe variants, BPFW, AFW, and PFW, including their lazy versions" begin
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2x
return nothing
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(4)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, zeros(10))
res_bpcg = FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
verbose=false,
epsilon=3e-7,
)
res_bpcg_lazy = FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
verbose=false,
epsilon=3e-7,
lazy=true,
)
res_afw = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=100,
verbose=false,
epsilon=3e-7,
)
res_afw_lazy = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=100,
verbose=false,
epsilon=3e-7,
lazy=true,
)
res_pfw = FrankWolfe.pairwise_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=100,
verbose=false,
epsilon=3e-7,
)
res_pfw_lazy = FrankWolfe.pairwise_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=100,
verbose=false,
lazy=true,
epsilon=3e-7,
)
@test res_afw[3] ≈ res_bpcg[3]
@test res_afw[3] ≈ res_pfw[3]
@test res_afw[3] ≈ res_afw_lazy[3]
@test res_pfw[3] ≈ res_pfw_lazy[3]
@test res_bpcg[3] ≈ res_bpcg_lazy[3]
@test norm(res_afw[1] - res_bpcg[1]) ≈ 0 atol = 1e-6
@test norm(res_afw[1] - res_pfw[1]) ≈ 0 atol = 1e-6
@test norm(res_afw[1] - res_afw_lazy[1]) ≈ 0 atol = 1e-6
@test norm(res_pfw[1] - res_pfw_lazy[1]) ≈ 0 atol = 1e-6
@test norm(res_bpcg[1] - res_bpcg_lazy[1]) ≈ 0 atol = 1e-6
res_bpcg2 = FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
verbose=false,
lazy=true,
epsilon=3e-7,
)
@test res_bpcg2[3] ≈ res_bpcg[3] atol = 1e-5
active_set_afw = res_afw[end]
storage = copy(active_set_afw.x)
grad!(storage, active_set_afw.x)
epsilon = 1e-6
d = active_set_afw.x * 0
@inferred FrankWolfe.afw_step(active_set_afw.x, storage, lmo_prob, active_set_afw, epsilon, d)
@inferred FrankWolfe.lazy_afw_step(
active_set_afw.x,
storage,
lmo_prob,
active_set_afw,
epsilon,
epsilon,
d,
)
res_bpcg = FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
verbose=false,
epsilon=3e-7,
callback=test_callback,
)
end
@testset "recompute or not last vertex" begin
n = 10
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2x
return nothing
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(4)
lmo = FrankWolfe.TrackingLMO(lmo_prob)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, ones(10))
FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
epsilon=3e-7,
verbose=false,
)
@test lmo.counter <= 51
prev_counter = lmo.counter
lmo.counter = 0
FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=6000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
epsilon=3e-7,
verbose=false,
recompute_last_vertex=false,
)
@test lmo.counter == prev_counter - 1
end
@testset "Quadratic active set" begin
n = 2 # number of dimensions
p = 10 # number of points
function simple_reg_loss(θ, data_point)
(xi, yi) = data_point
(a, b) = (θ[1:end-1], θ[end])
pred = a ⋅ xi + b
return (pred - yi)^2 / 2
end
function ∇simple_reg_loss(storage, θ, data_point)
(xi, yi) = data_point
(a, b) = (θ[1:end-1], θ[end])
pred = a ⋅ xi + b
@. storage[1:end-1] += xi * (pred - yi)
storage[end] += pred - yi
return storage
end
xs = [[9.42970533446119, 1.3392275765318449],
[15.250689085124804, 1.2390123120559722],
[-12.057722842599361, 3.1181717536024807],
[-2.3464126496126, -10.873522937105326],
[4.623106804313759, -0.8059308663320504],
[-8.124306879044243, -20.610343848003204],
[3.1305636922867732, -4.794303128671186],
[-9.443890241279835, 18.243232066781086],
[-10.582972181702795, 2.9216495153528084],
[12.469122418416605, -4.2927539788825735]]
params_perfect = [1:n; 4]
data_noisy = [([9.42970533446119, 1.3392275765318449], 16.579645754247938),
([15.250689085124804, 1.2390123120559722], 21.79567508806334),
([-12.057722842599361, 3.1181717536024807], -1.0588448811381594),
([-2.3464126496126, -10.873522937105326], -20.03150790822045),
([4.623106804313759, -0.8059308663320504], 6.408358929519689),
([-8.124306879044243, -20.610343848003204], -45.189085987370525),
([3.1305636922867732, -4.794303128671186], -2.5753631975362286),
([-9.443890241279835, 18.243232066781086], 30.498897745427072),
([-10.582972181702795, 2.9216495153528084], -0.5085178107814902),
([12.469122418416605, -4.2927539788825735], 7.843317917334855)]
f(x) = sum(simple_reg_loss(x, data_point) for data_point in data_noisy)
function gradf(storage, x)
storage .= 0
for dp in data_noisy
∇simple_reg_loss(storage, x, dp)
end
end
lmo = FrankWolfe.LpNormLMO{Float64, 2}(1.05 * norm(params_perfect))
x0 = FrankWolfe.compute_extreme_point(lmo, zeros(Float64, n+1))
active_set = FrankWolfe.ActiveSetQuadratic([(1.0, x0)], gradf)
res = FrankWolfe.blended_pairwise_conditional_gradient(
f,
gradf,
lmo,
active_set;
verbose=false,
lazy=true,
line_search=FrankWolfe.Adaptive(L_est=10.0, relaxed_smoothness=true),
trajectory=true,
)
@test abs(res[3] - 0.70939) ≤ 0.001
@test res[4] ≤ 1e-2
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 8275 | import FrankWolfe
using LinearAlgebra
using Test
using Random
Random.seed!(100)
f(x) = dot(x, x)
function grad!(storage, x)
@. storage = 2 * x
end
n = 10
lmo_nb = FrankWolfe.ScaledBoundL1NormBall(-ones(n), ones(n))
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1.0)
lmo1 = FrankWolfe.ScaledBoundLInfNormBall(-ones(n), zeros(n))
lmo2 = FrankWolfe.ScaledBoundLInfNormBall(zeros(n), ones(n))
lmo3 = FrankWolfe.ScaledBoundLInfNormBall(ones(n), 2 * ones(n))
@testset "Testing alternating linear minimization with block coordinate FW for different LMO-pairs " begin
x, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo_nb, lmo_prob),
ones(n),
lambda=1.0,
line_search=FrankWolfe.Adaptive(relaxed_smoothness=true),
)
@test abs(x.blocks[1][1] - 0.5 / n) < 1e-6
@test abs(x.blocks[2][1] - 1 / n) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo_nb, lmo_prob),
ones(n),
lambda=1/3,
line_search=FrankWolfe.Adaptive(relaxed_smoothness=true),
)
@test abs(x.blocks[1][1] - 0.75 / n) < 1e-6
@test abs(x.blocks[2][1] - 1 / n) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo_nb, lmo_prob),
ones(n),
lambda=1/9,
line_search=FrankWolfe.Adaptive(relaxed_smoothness=true),
)
@test abs(x.blocks[1][1] - 0.9 / n) < 1e-6
@test abs(x.blocks[2][1] - 1 / n) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo_nb, lmo_prob),
ones(n),
lambda=3.0,
line_search=FrankWolfe.Adaptive(relaxed_smoothness=true),
)
@test abs(x.blocks[1][1] - 0.25 / n) < 1e-6
@test abs(x.blocks[2][1] - 1 / n) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo1, lmo2),
ones(n),
)
@test abs(x.blocks[1][1]) < 1e-6
@test abs(x.blocks[2][1]) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo1, lmo2),
(-ones(n), ones(n)),
)
@test abs(x.blocks[1][1]) < 1e-6
@test abs(x.blocks[2][1]) < 1e-6
# test the edge case with a zero vector as direction for the step size computation
x, v, primal, dual_gap, traj_data = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
x -> 0,
(storage, x) -> storage .= zero(x),
(lmo1, lmo3),
ones(n),
verbose=true,
line_search=FrankWolfe.Shortstep(2),
)
@test norm(x.blocks[1] - zeros(n)) < 1e-6
@test norm(x.blocks[2] - ones(n)) < 1e-6
x, _, _, _, _, traj_data = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo1, lmo_prob),
ones(n),
trajectory=true,
verbose=true,
)
@test abs(x.blocks[1][1]) < 1e-6
@test abs(x.blocks[2][1] - 1 / n) < 1e-6
@test traj_data != []
@test length(traj_data[1]) == 6
@test length(traj_data) >= 2
@test length(traj_data) <= 10001
x, _, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo2, lmo_prob),
ones(n),
line_search=FrankWolfe.Agnostic(),
momentum=0.9,
)
@test abs(x.blocks[1][1] - 0.5 / n) < 1e-3
@test abs(x.blocks[2][1] - 1 / n) < 1e-3
end
@testset "Testing different update orders for block coordinate FW in within alternating linear minimization" begin
orders = [
FrankWolfe.FullUpdate(),
[FrankWolfe.CyclicUpdate(i) for i in [-1, 1, 2]]...,
[FrankWolfe.StochasticUpdate(i) for i in [-1, 1, 2]]...,
[FrankWolfe.DualGapOrder(i) for i in [-1, 1, 2]]...,
[FrankWolfe.DualProgressOrder(i) for i in [-1, 1, 2]]...,
]
for order in orders
x, _, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo2, lmo_prob),
ones(n),
line_search=FrankWolfe.Adaptive(relaxed_smoothness=true),
update_order=order,
)
@test abs(x.blocks[1][1] - 0.5 / n) < 1e-5
@test abs(x.blocks[2][1] - 1 / n) < 1e-5
end
end
@testset "Testing alternating linear minimization with different FW methods" begin
methods = [
FrankWolfe.frank_wolfe,
FrankWolfe.away_frank_wolfe,
FrankWolfe.lazified_conditional_gradient,
]
for fw_method in methods
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
fw_method,
f,
grad!,
(lmo2, lmo_prob),
ones(n),
)
@test abs(x.blocks[1][1] - 0.5 / n) < 1e-6
@test abs(x.blocks[2][1] - 1 / n) < 1e-6
end
end
@testset "Testing block-coordinate FW with different update steps and linesearch strategies" begin
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo1, lmo2),
ones(n),
line_search=(FrankWolfe.Shortstep(2.0), FrankWolfe.Adaptive()),
)
@test abs(x.blocks[1][1]) < 1e-6
@test abs(x.blocks[2][1]) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo1, lmo2),
ones(n),
update_step=FrankWolfe.BPCGStep(),
)
@test abs(x.blocks[1][1]) < 1e-6
@test abs(x.blocks[2][1]) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo1, lmo2),
ones(n),
update_step=FrankWolfe.BPCGStep(true, nothing, 1000, false, Inf),
)
@test abs(x.blocks[1][1]) < 1e-6
@test abs(x.blocks[2][1]) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo1, lmo2),
ones(n),
update_step=(FrankWolfe.BPCGStep(), FrankWolfe.FrankWolfeStep()),
)
@test abs(x.blocks[1][1]) < 1e-6
@test abs(x.blocks[2][1]) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_linear_minimization(
FrankWolfe.block_coordinate_frank_wolfe,
f,
grad!,
(lmo_nb, lmo_prob),
ones(n),
lambda=3.0,
line_search=(FrankWolfe.Shortstep(8.0), FrankWolfe.Adaptive()), # L-smooth in coordinates for L = 2+2*λ
update_step=(FrankWolfe.BPCGStep(), FrankWolfe.FrankWolfeStep()),
)
@test abs(x.blocks[1][1] - 0.25 / n) < 1e-6
@test abs(x.blocks[2][1] - 1 / n) < 1e-6
end
@testset "Testing alternating projections for different LMO-pairs " begin
x, _, _, _, _ = FrankWolfe.alternating_projections((lmo1, lmo_prob), rand(n), verbose=true)
@test abs(x[1][1]) < 1e-6
@test abs(x[2][1] - 1 / n) < 1e-6
x, _, _, _, _ = FrankWolfe.alternating_projections((lmo3, lmo_prob), rand(n))
@test abs(x[1][1] - 1) < 1e-6
@test abs(x[2][1] - 1 / n) < 1e-6
x, _, _, infeas, _ = FrankWolfe.alternating_projections((lmo1, lmo2), rand(n))
@test abs(x[1][1]) < 1e-6
@test abs(x[2][1]) < 1e-6
@test infeas < 1e-6
x, _, _, infeas, _ = FrankWolfe.alternating_projections((lmo2, lmo3), rand(n))
@test abs(x[1][1] - 1) < 1e-4
@test abs(x[2][1] - 1) < 1e-4
@test infeas < 1e-6
x, _, _, infeas, traj_data =
FrankWolfe.alternating_projections((lmo1, lmo3), rand(n), trajectory=true)
@test abs(x[1][1]) < 1e-6
@test abs(x[2][1] - 1) < 1e-6
@test traj_data != []
@test length(traj_data[1]) == 5
@test length(traj_data) >= 2
@test length(traj_data) <= 10001
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 1334 | import FrankWolfe
using LinearAlgebra
using Random
using Test
using SparseArrays
n = Int(1e4)
k = 3000
s = 41
Random.seed!(s)
xpi = rand(n);
total = sum(xpi);
const xp = xpi # ./ total;
f(x) = norm(x .- xp)^2
function grad!(storage, x)
@. storage = 2 * (x .- xp)
end
lmo = FrankWolfe.KSparseLMO(100, 1.0)
x0 = FrankWolfe.compute_extreme_point(lmo, spzeros(size(xp)...))
gradient = similar(xp)
x, v, primal, dual_gap, _, _ = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=2.0),
print_iter=100,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
trajectory=false,
lazy_tolerance=1.0,
weight_purge_threshold=1e-9,
epsilon=1e-8,
gradient=gradient,
)
@test dual_gap ≤ 5e-4
@test f(x0) - f(x) ≥ 180
x0 = FrankWolfe.compute_extreme_point(lmo, spzeros(size(xp)...))
x, v, primal_cut, dual_gap, _, _ = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=2.0),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
trajectory=false,
lazy_tolerance=1.0,
weight_purge_threshold=1e-10,
epsilon=1e-9,
timeout=3.0,
)
@test primal ≤ primal_cut
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 648 | import FrankWolfe
import LinearAlgebra
n = Int(1e6);
xpi = rand(n);
total = sum(xpi);
const xp = xpi ./ total;
const f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
function cf(x, xp)
return @. norm(x - xp)^2
end
function cgrad(storage, x, xp)
@. storage = 2 * (x - xp)
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1);
x0 = FrankWolfe.compute_extreme_point(lmo_prob, zeros(n));
FrankWolfe.benchmarkOracles(f, grad!, lmo_prob, n; k=100, T=Float64)
FrankWolfe.benchmarkOracles(
x -> cf(x, xp),
(storage, x) -> cgrad(storage, x, xp),
lmo_prob,
n;
k=100,
T=Float64,
)
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 1217 | # benchmark for tuple VS vector cache
using BenchmarkTools
using FrankWolfe
for n in (10, 100, 1000)
@info "n = $n"
direction = zeros(n)
rhs = 10 * rand()
lmo_unit = FrankWolfe.UnitSimplexOracle(rhs)
lmo_veccached = FrankWolfe.VectorCacheLMO(lmo_unit)
res_vec = @benchmark begin
for idx in 1:$n
$direction .= 0
$direction[idx] = -1
res_point_cached_vec =
FrankWolfe.compute_extreme_point($lmo_veccached, $direction, threshold=0)
_ = length($lmo_veccached)
end
empty!($lmo_veccached)
end
res_multi = map(1:10) do N
lmo_multicached = FrankWolfe.MultiCacheLMO{N}(lmo_unit)
@benchmark begin
for idx in 1:$n
$direction .= 0
$direction[idx] = -1
res_point_cached_vec =
FrankWolfe.compute_extreme_point($lmo_multicached, $direction, threshold=0)
_ = length($lmo_multicached)
end
empty!($lmo_multicached)
end
end
@info "Vec benchmark"
display(res_vec)
for N in 1:10
@info "Tuple benchmark $N"
display(res_multi[N])
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 2572 | using LinearAlgebra
using Random
using SparseArrays
using Test
using Test
using FrankWolfe
using DoubleFloats
n = 200
k = 200
s = 42
Random.seed!(s)
const matrix = rand(n, n)
const hessian = transpose(matrix) * matrix
const linear = rand(n)
f(x) = dot(linear, x) + 0.5 * transpose(x) * hessian * x
function grad!(storage, x)
return storage .= linear + hessian * x
end
const L = eigmax(hessian)
# This test covers the generic types with accelerated BCG
# only few iterations are run because linear algebra with BigFloat is intensive
@testset "Type $T" for T in (Float64, Double64, BigFloat)
@testset "LMO $(typeof(lmo)) Probability simplex" for lmo in (
FrankWolfe.ProbabilitySimplexOracle{T}(1.0),
FrankWolfe.KSparseLMO{T}(100, 100.0),
)
x0 = FrankWolfe.compute_extreme_point(lmo, spzeros(T, n))
target_tolerance = 1e-5
x, v, primal_accel, dual_gap_accel, _, _ = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
copy(x0),
epsilon=target_tolerance,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=L),
print_iter=k / 10,
hessian=hessian,
memory_mode=FrankWolfe.InplaceEmphasis(),
accelerated=true,
verbose=false,
trajectory=false,
lazy_tolerance=1.0,
weight_purge_threshold=1e-10,
)
x, v, primal_hessian, dual_gap_hessian, _, _ = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
copy(x0),
epsilon=target_tolerance,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=L),
print_iter=k / 10,
hessian=hessian,
memory_mode=FrankWolfe.InplaceEmphasis(),
accelerated=false,
verbose=false,
trajectory=false,
lazy_tolerance=1.0,
weight_purge_threshold=1e-10,
)
x, v, primal_bcg, dual_gap_bcg, _, _ = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
copy(x0),
epsilon=target_tolerance,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=L),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
trajectory=false,
lazy_tolerance=1.0,
weight_purge_threshold=1e-10,
)
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 4036 | using Test
using Random
using LinearAlgebra
using FrankWolfe
using SparseArrays
@testset "Block array behaviour" begin
arr = FrankWolfe.BlockVector([
[
1 3
4 6.0
],
[
1 3 1
4 1 2
1 3 5.0
],
],)
@test length(arr) == 4 + 9
@test arr[end] == 5.0
@test arr[1] == 1.0
@test arr[5] == 1.0
@test arr[4] == 6.0
v1 = Vector(arr)
arr2 = FrankWolfe.BlockVector([zeros(2, 2), ones(3, 3)],)
copyto!(arr2, arr)
v2 = Vector(arr2)
@test v1 == v2
v1[1] *= 2
@test v1 != v2
@test size(similar(arr)) == size(arr)
@test typeof(similar(arr)) == typeof(arr)
@test norm(arr) == norm(collect(arr))
@test dot(arr, arr) == dot(collect(arr), collect(arr))
arr3 = FrankWolfe.BlockVector([3 * ones(2, 2), ones(3, 3)],)
@test dot(arr3, arr) ≈ dot(arr, arr3)
@test dot(arr3, arr) ≈ dot(collect(arr3), collect(arr))
arr4 = 2 * arr3
@test arr4.blocks[1] == 6 * ones(2, 2)
arr5 = FrankWolfe.BlockVector([6 * ones(2, 2), 2 * ones(3, 3)],)
arr6 = arr3/2
arr7 = arr3 * 2
@test arr6.blocks[1] == 1.5 * ones(2, 2)
@test isequal(arr4, arr7)
@test isequal(arr4, arr4)
@test isequal(arr4, arr5)
@test !isequal(arr3, arr4)
@test !isequal(arr2, FrankWolfe.BlockVector([zeros(2, 2)]))
arr8 = FrankWolfe.BlockVector([ones(2, 2), ones(2, 2)])
@test_throws DimensionMismatch dot(arr3, arr8)
end
@testset "FrankWolfe array methods" begin
@testset "Block arrays" begin
mem = FrankWolfe.InplaceEmphasis()
arr0 = FrankWolfe.BlockVector([
[
1 3
4 6.0
],
[
1 3 1
4 1 2
1 3 5.0
],
],)
arr1 = rand() * arr0
d = similar(arr1)
FrankWolfe.muladd_memory_mode(mem, d, arr1, arr0)
dref = arr1 - arr0
@test d == dref
gamma = rand()
arr2 = zero(arr0)
FrankWolfe.muladd_memory_mode(mem, arr2, gamma, arr0)
@test arr2 == -gamma * arr0
arr3 = similar(arr0)
FrankWolfe.muladd_memory_mode(mem, arr3, zero(arr0), gamma, arr0)
@test arr3 == -gamma * arr0
active_set = FrankWolfe.ActiveSet(
[0.25, 0.75],
[
FrankWolfe.BlockVector([ones(100, 1), ones(30, 30)]),
FrankWolfe.BlockVector([3 * ones(100, 1), zeros(30, 30)]),
],
FrankWolfe.BlockVector([ones(100, 1), ones(30, 30)]),
)
FrankWolfe.compute_active_set_iterate!(active_set)
x = active_set.x
x_copy = 0 * x
for (λi, ai) in active_set
@. x_copy += λi * ai
end
@test norm(x_copy - x) ≤ 1e-12
end
@testset "Sparse vectors as atoms" begin
v1 = spzeros(3)
v2 = spzeros(3) .+ 1
v3 = spzeros(3)
v3[1] = 1
active_set = FrankWolfe.ActiveSet(
1/3 * ones(3),
[v1, v2, v3],
spzeros(3),
)
FrankWolfe.compute_active_set_iterate!(active_set)
active_set_dense = FrankWolfe.ActiveSet(
1/3 * ones(3),
collect.([v1, v2, v3]),
zeros(3),
)
FrankWolfe.compute_active_set_iterate!(active_set_dense)
@test active_set.x ≈ active_set_dense.x
end
@testset "Sparse matrices as atoms" begin
v1 = sparse(1.0I, 3, 3)
v2 = sparse(2.0I, 3, 3)
v2[1,2] = 2
v3 = spzeros(3, 3)
active_set = FrankWolfe.ActiveSet(
1/3 * ones(3),
[v1, v2, v3],
spzeros(3,3),
)
FrankWolfe.compute_active_set_iterate!(active_set)
active_set_dense = FrankWolfe.ActiveSet(
1/3 * ones(3),
collect.([v1, v2, v3]),
zeros(3,3),
)
FrankWolfe.compute_active_set_iterate!(active_set_dense)
@test active_set.x ≈ active_set_dense.x
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 3984 | # # Extra-lazification
using FrankWolfe
using Test
using LinearAlgebra
const n = 100
const center0 = 5.0 .+ 3 * rand(n)
f(x) = 0.5 * norm(x .- center0)^2
function grad!(storage, x)
return storage .= x .- center0
end
@testset "Blended Pairwise Conditional Gradient" begin
lmo = FrankWolfe.UnitSimplexOracle(4.3)
tlmo = FrankWolfe.TrackingLMO(lmo)
x0 = FrankWolfe.compute_extreme_point(lmo, randn(n))
# Adding a vertex storage
vertex_storage = FrankWolfe.DeletedVertexStorage(typeof(x0)[], 5)
tlmo.counter = 0
results = FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
tlmo,
x0,
max_iteration=4000,
lazy=true,
epsilon=1e-5,
add_dropped_vertices=true,
extra_vertex_storage=vertex_storage,
)
active_set = results[end]
lmo_calls0 = tlmo.counter
for iter in 1:10
center = 5.0 .+ 3 * rand(n)
f_i(x) = 0.5 * norm(x .- center)^2
function grad_i!(storage, x)
return storage .= x .- center
end
tlmo.counter = 0
FrankWolfe.blended_pairwise_conditional_gradient(
f_i,
grad_i!,
tlmo,
active_set,
max_iteration=4000,
lazy=true,
epsilon=1e-5,
add_dropped_vertices=true,
use_extra_vertex_storage=true,
extra_vertex_storage=vertex_storage,
)
@test tlmo.counter < lmo_calls0
end
end
@testset "Away-Frank-Wolfe" begin
lmo = FrankWolfe.UnitSimplexOracle(4.3)
tlmo = FrankWolfe.TrackingLMO(lmo)
x0 = FrankWolfe.compute_extreme_point(lmo, randn(n))
# Adding a vertex storage
vertex_storage = FrankWolfe.DeletedVertexStorage(typeof(x0)[], 5)
tlmo.counter = 0
results = FrankWolfe.away_frank_wolfe(
f,
grad!,
tlmo,
x0,
max_iteration=4000,
lazy=true,
epsilon=1e-5,
add_dropped_vertices=true,
extra_vertex_storage=vertex_storage,
)
active_set = results[end]
lmo_calls0 = tlmo.counter
for iter in 1:10
center = 5.0 .+ 3 * rand(n)
f_i(x) = 0.5 * norm(x .- center)^2
function grad_i!(storage, x)
return storage .= x .- center
end
tlmo.counter = 0
FrankWolfe.away_frank_wolfe(
f_i,
grad_i!,
tlmo,
active_set,
max_iteration=4000,
lazy=true,
epsilon=1e-5,
add_dropped_vertices=true,
use_extra_vertex_storage=true,
extra_vertex_storage=vertex_storage,
)
@test tlmo.counter < lmo_calls0
end
end
@testset "Blended Pairwise Conditional Gradient" begin
lmo = FrankWolfe.UnitSimplexOracle(4.3)
tlmo = FrankWolfe.TrackingLMO(lmo)
x0 = FrankWolfe.compute_extreme_point(lmo, randn(n))
# Adding a vertex storage
vertex_storage = FrankWolfe.DeletedVertexStorage(typeof(x0)[], 5)
tlmo.counter = 0
results = FrankWolfe.blended_conditional_gradient(
f,
grad!,
tlmo,
x0,
max_iteration=4000,
lazy=true,
epsilon=1e-5,
add_dropped_vertices=true,
extra_vertex_storage=vertex_storage,
)
active_set = results[end]
lmo_calls0 = tlmo.counter
for iter in 1:10
center = 5.0 .+ 3 * rand(n)
f_i(x) = 0.5 * norm(x .- center)^2
function grad_i!(storage, x)
return storage .= x .- center
end
tlmo.counter = 0
FrankWolfe.blended_conditional_gradient(
f_i,
grad_i!,
tlmo,
active_set,
max_iteration=4000,
lazy=true,
epsilon=1e-5,
add_dropped_vertices=true,
use_extra_vertex_storage=true,
extra_vertex_storage=vertex_storage,
)
@test tlmo.counter < lmo_calls0
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 5808 | using Test
using FrankWolfe
using Random
using LinearAlgebra
import FrankWolfe: compute_gradient, compute_value, compute_value_gradient
Random.seed!(123)
@testset "Simple and stochastic function gradient interface" begin
for n in (1, 5, 20)
A = rand(Float16, n, n)
A .+= A'
b = rand(Float16, n)
c = rand(Float16)
@testset "Simple function" begin
simple_quad(x) = A * x ⋅ x / 2 + b ⋅ x + c
function ∇simple_quad(storage, x)
return storage .= A * x + b
end
f_simple = FrankWolfe.SimpleFunctionObjective(
simple_quad,
∇simple_quad,
Vector{Float32}(undef, n), # storage
)
for _ in 1:5
x = randn(Float32, n)
@test FrankWolfe.compute_gradient(f_simple, x) == ∇simple_quad(similar(x), x)
@test FrankWolfe.compute_value(f_simple, x) == simple_quad(x)
@test FrankWolfe.compute_value_gradient(f_simple, x) ==
(simple_quad(x), ∇simple_quad(similar(x), x))
@test FrankWolfe.compute_gradient(f_simple, convert(Vector{Float32}, x)) isa
Vector{Float32}
@test FrankWolfe.compute_value(f_simple, convert(Vector{Float32}, x)) isa Float32
end
end
@testset "Stochastic function linear regression" begin
function simple_reg_loss(θ, data_point)
(xi, yi) = data_point
(a, b) = (θ[1:end-1], θ[end])
pred = a ⋅ xi + b
return (pred - yi)^2 / 2
end
function ∇simple_reg_loss(storage, θ, data_point)
(xi, yi) = data_point
(a, b) = (θ[1:end-1], θ[end])
storage[1:end-1] .+= xi * (a ⋅ xi + b - yi)
storage[end] += a ⋅ xi + b - yi
return storage
end
xs = [10 * randn(5) for i in 1:10000]
params = rand(6) .- 1 # start params in (-1,0)
bias = 4π
params_perfect = [1:5; bias]
@testset "Perfectly representable data" begin
# Y perfectly representable by X
data_perfect = [(x, x ⋅ (1:5) + bias) for x in xs]
storage = similar(params_perfect)
f_stoch = FrankWolfe.StochasticObjective(
simple_reg_loss,
∇simple_reg_loss,
data_perfect,
storage,
)
@test FrankWolfe._random_indices(f_stoch, 33, false)[1] == 33
@test FrankWolfe._random_indices(f_stoch, 33, true)[1] == length(xs)
@test compute_value(f_stoch, params) > compute_value(f_stoch, params_perfect)
@test compute_value(f_stoch, params_perfect) ≈ 0 atol = 1e-10
@test compute_gradient(f_stoch, params_perfect) ≈ zeros(6) atol = 1e-9
@test !isapprox(compute_gradient(f_stoch, params), zeros(6))
(f_estimate, g_estimate) = compute_value_gradient(
f_stoch,
params_perfect,
batch_size=length(data_perfect),
rng=Random.seed!(33),
)
@test f_estimate ≈ 0 atol = 1e-10
@test g_estimate ≈ zeros(6) atol = 6e-10
(f_estimate, g_estimate) = compute_value_gradient(
f_stoch,
params,
batch_size=length(data_perfect),
rng=Random.seed!(33),
)
@test f_estimate ≈ compute_value(
f_stoch,
params,
batch_size=length(data_perfect),
rng=Random.seed!(33),
)
@test g_estimate ≈ compute_gradient(
f_stoch,
params,
batch_size=length(data_perfect),
rng=Random.seed!(33),
)
end
@testset "Noisy data" begin
data_noisy = [(x, x ⋅ (1:5) + bias + 0.5 * randn()) for x in xs]
storage = similar(params_perfect)
f_stoch_noisy = FrankWolfe.StochasticObjective(
simple_reg_loss,
∇simple_reg_loss,
data_noisy,
storage,
)
@test compute_value(f_stoch_noisy, params) >
compute_value(f_stoch_noisy, params_perfect)
# perfect parameters shouldn't have too high of a residual gradient
@test norm(compute_gradient(f_stoch_noisy, params_perfect)) <=
length(data_noisy) * 0.05
@test norm(compute_gradient(f_stoch_noisy, params_perfect)) <
norm(compute_gradient(f_stoch_noisy, params))
@test !isapprox(compute_gradient(f_stoch_noisy, params), zeros(6))
(f_estimate, g_estimate) = compute_value_gradient(
f_stoch_noisy,
params,
batch_size=length(data_noisy),
rng=Random.seed!(33),
)
@test f_estimate ≈ compute_value(
f_stoch_noisy,
params,
batch_size=length(data_noisy),
rng=Random.seed!(33),
)
@test g_estimate ≈ compute_gradient(
f_stoch_noisy,
params,
batch_size=length(data_noisy),
rng=Random.seed!(33),
)
end
end
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 2758 | using FrankWolfe
using LinearAlgebra
using Test
# necessary for away step
function Base.convert(::Type{GenericArray{Float64,1}}, v::FrankWolfe.ScaledHotVector{Float64})
return GenericArray(collect(v))
end
@testset "GenericArray is maintained" begin
n = Int(1e3)
k = n
f_generic(x::GenericArray) = dot(x, x)
function grad_generic!(storage, x)
@. storage = 2 * x
end
lmo = FrankWolfe.ProbabilitySimplexOracle(1)
x0 = GenericArray(collect(FrankWolfe.compute_extreme_point(lmo, zeros(n))))
x, v, primal, dual_gap0, trajectory = FrankWolfe.frank_wolfe(
f_generic,
grad_generic!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test f_generic(x) < f_generic(x0)
@test x isa GenericArray
x, v, primal, dual_gap0, trajectory = FrankWolfe.lazified_conditional_gradient(
f_generic,
grad_generic!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.InplaceEmphasis(),
VType=FrankWolfe.ScaledHotVector{Float64},
)
@test f_generic(x) < f_generic(x0)
@test x isa GenericArray
@test_broken x, v, primal, dual_gap0, trajectory = FrankWolfe.away_frank_wolfe(
f_generic,
grad_generic!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
end
@testset "fast_equal special types" begin
@testset "ScaledHotVector" begin
a = FrankWolfe.ScaledHotVector(3.5, 3, 10)
b = FrankWolfe.ScaledHotVector(3.5, 3, 11)
@test !isequal(a, b)
c = FrankWolfe.ScaledHotVector(3.5, 4, 10)
@test !isequal(a, c)
d = FrankWolfe.ScaledHotVector(3, 3, 10)
@test !isequal(a, d)
e = FrankWolfe.ScaledHotVector(3.0, 3, 10)
@test isequal(d, e)
f = FrankWolfe.ScaledHotVector(big(3.0), 3, 10)
@test isequal(e, f)
v = SparseArrays.spzeros(10)
v[1:5] .= 3
v2 = copy(v)
copyto!(v, e)
@test norm(v) ≈ 3
@test norm(v[1:2]) ≈ 0
copyto!(v2, collect(e))
@test v == v2
end
@testset "RankOneMatrix" begin
a = FrankWolfe.RankOneMatrix(ones(3), ones(4))
b = FrankWolfe.RankOneMatrix(ones(3), 2 * ones(4))
@test !isequal(a, b)
@test isequal(2a, b)
@test !isequal(2a, b')
@test !isequal(2a, FrankWolfe.RankOneMatrix(2 * ones(4), ones(3)))
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 36028 | using Test
using FrankWolfe
using LinearAlgebra
import SparseArrays
using Random
import FrankWolfe: compute_extreme_point, LpNormLMO, KSparseLMO
import MathOptInterface as MOI
# solvers
import GLPK
import Clp
import Hypatia
using JuMP
@testset "Simplex LMOs" begin
n = 6
direction = zeros(6)
rhs = 10 * rand()
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(rhs)
lmo_unit = FrankWolfe.UnitSimplexOracle(rhs)
@testset "Choosing improving direction" for idx in 1:n
direction .= 0
direction[idx] = -1
res_point_prob = FrankWolfe.compute_extreme_point(lmo_prob, direction)
res_point_unit = FrankWolfe.compute_extreme_point(lmo_unit, direction)
for j in eachindex(res_point_prob)
if j == idx
@test res_point_prob[j] == res_point_unit[j] == rhs
else
@test res_point_prob[j] == res_point_unit[j] == 0
end
end
# computing dual solutions and testing complementarity
dual, redC = FrankWolfe.compute_dual_solution(lmo_prob, direction, res_point_prob)
@test sum((redC .* res_point_prob)) + (dual[1] * (rhs - sum(res_point_prob))) == 0
dual, redC = FrankWolfe.compute_dual_solution(lmo_unit, direction, res_point_unit)
@test sum((redC .* res_point_unit)) + (dual[1] * (rhs - sum(res_point_unit))) == 0
end
@testset "Choosing least-degrading direction" for idx in 1:n
# all directions worsening, must pick idx
direction .= 2
direction[idx] = 1
res_point_prob = FrankWolfe.compute_extreme_point(lmo_prob, direction)
res_point_unit = FrankWolfe.compute_extreme_point(lmo_unit, direction)
for j in eachindex(res_point_unit)
@test res_point_unit[j] == 0
if j == idx
@test res_point_prob[j] == rhs
else
@test res_point_prob[j] == 0
end
end
# computing dual solutions and testing complementarity
dual, redC = FrankWolfe.compute_dual_solution(lmo_prob, direction, res_point_prob)
@test sum((redC .* res_point_prob)) + (dual[1] * (rhs - sum(res_point_prob))) == 0
dual, redC = FrankWolfe.compute_dual_solution(lmo_unit, direction, res_point_unit)
@test sum((redC .* res_point_unit)) + (dual[1] * (rhs - sum(res_point_unit))) == 0
end
end
@testset "Hypersimplex" begin
@testset "Hypersimplex $n $K" for n in (2, 5, 10), K in (1, min(n, 4))
direction = randn(n)
hypersimplex = FrankWolfe.HyperSimplexOracle(K, 3.0)
unit_hypersimplex = FrankWolfe.UnitHyperSimplexOracle(K, 3.0)
v = FrankWolfe.compute_extreme_point(hypersimplex, direction)
@test SparseArrays.nnz(v) == K
v_unit = FrankWolfe.compute_extreme_point(unit_hypersimplex, direction)
@test SparseArrays.nnz(v_unit) == min(K, count(<=(0), direction))
optimizer = GLPK.Optimizer()
moi_hypersimpler = FrankWolfe.convert_mathopt(hypersimplex, optimizer; dimension=n)
v_moi = FrankWolfe.compute_extreme_point(moi_hypersimpler, direction)
@test norm(v_moi - v) ≤ 1e-4
moi_unit_hypersimpler =
FrankWolfe.convert_mathopt(unit_hypersimplex, optimizer; dimension=n)
v_moi_unit = FrankWolfe.compute_extreme_point(moi_unit_hypersimpler, direction)
@test norm(v_moi_unit - v_unit) ≤ 1e-4
end
end
@testset "Lp-norm epigraph LMO" begin
for n in (1, 2, 5, 10)
τ = 5 + 3 * rand()
# tests that the "special" p behaves like the "any" p, i.e. 2.0 and 2
@testset "$p-norm" for p in (1, 1.0, 1.5, 2, 2.0, Inf, Inf32)
lmo = LpNormLMO{Float64,p}(τ)
for _ in 1:100
c = 5 * randn(n)
v = FrankWolfe.compute_extreme_point(lmo, c)
@test norm(v, p) ≈ τ
end
c = zeros(n)
v = FrankWolfe.compute_extreme_point(lmo, c)
@test !any(isnan, v)
end
@testset "K-Norm ball $K" for K in 1:n
lmo_ball = FrankWolfe.KNormBallLMO(K, τ)
for _ in 1:20
c = 5 * randn(n)
v = FrankWolfe.compute_extreme_point(lmo_ball, c)
v1 = FrankWolfe.compute_extreme_point(FrankWolfe.LpNormLMO{1}(τ), c)
v_inf = FrankWolfe.compute_extreme_point(FrankWolfe.LpNormLMO{Inf}(τ / K), c)
# K-norm is convex hull of union of the two norm epigraphs
# => cannot do better than the best of them
@test dot(v, c) ≈ min(dot(v1, c), dot(v_inf, c))
# test according to original norm definition
# norm constraint must be tight
K_sum = 0.0
for vi in sort!(abs.(v), rev=true)[1:K]
K_sum += vi
end
@test K_sum ≈ τ
end
end
end
# testing issue on zero direction
for n in (1, 5)
lmo = FrankWolfe.LpNormLMO{Float64,2}(1.0)
x0 = FrankWolfe.compute_extreme_point(lmo, zeros(n))
@test all(!isnan, x0)
end
end
@testset "K-sparse polytope LMO" begin
@testset "$n-dimension" for n in (1, 2, 10)
τ = 5 + 3 * rand()
for K in 1:n
lmo = KSparseLMO(K, τ)
x = 10 * randn(n) # dense vector
v = compute_extreme_point(lmo, x)
# K-sparsity
@test count(!iszero, v) == K
@test sum(abs.(v)) ≈ K * τ
xsort = sort!(10 * rand(n))
v = compute_extreme_point(lmo, xsort)
@test all(iszero, v[1:n-K])
@test all(abs(vi) ≈ abs(τ * sign(vi)) for vi in v[K:end])
reverse!(xsort)
v = compute_extreme_point(lmo, xsort)
@test all(iszero, v[K+1:end])
@test all(abs(vi) ≈ abs(τ * sign(vi)) for vi in v[1:K])
end
end
# type stability of K-sparse polytope LMO
lmo = KSparseLMO(3, 2.0)
x = 10 * randn(10) # dense vector
@inferred compute_extreme_point(lmo, x)
v = FrankWolfe.compute_extreme_point(lmo, zeros(3))
SparseArrays.dropzeros!(v)
@test norm(v) > 0
end
@testset "Caching on simplex LMOs" begin
n = 6
direction = zeros(6)
rhs = 10 * rand()
lmo_unit = FrankWolfe.UnitSimplexOracle(rhs)
lmo_never_cached = FrankWolfe.SingleLastCachedLMO(lmo_unit)
lmo_cached = FrankWolfe.SingleLastCachedLMO(lmo_unit)
lmo_multicached = FrankWolfe.MultiCacheLMO{3}(lmo_unit)
lmo_veccached = FrankWolfe.VectorCacheLMO(lmo_unit)
@testset "Forcing no cache remains nothing" for idx in 1:n
direction .= 0
direction[idx] = -1
res_point_unit = FrankWolfe.compute_extreme_point(lmo_unit, direction)
res_point_cached = FrankWolfe.compute_extreme_point(lmo_cached, direction, threshold=0)
res_point_cached_multi =
FrankWolfe.compute_extreme_point(lmo_multicached, direction, threshold=-1000)
res_point_cached_vec =
FrankWolfe.compute_extreme_point(lmo_veccached, direction, threshold=-1000)
res_point_never_cached =
FrankWolfe.compute_extreme_point(lmo_cached, direction, store_cache=false)
@test res_point_never_cached == res_point_unit
@test lmo_never_cached.last_vertex === nothing
@test length(lmo_never_cached) == 0
empty!(lmo_never_cached)
@test lmo_cached.last_vertex !== nothing
@test length(lmo_cached) == 1
@test count(!isnothing, lmo_multicached.vertices) == min(3, idx) == length(lmo_multicached)
@test length(lmo_veccached.vertices) == idx == length(lmo_veccached)
# we set the cache at least at the first iteration
if idx == 1
@test lmo_cached.last_vertex == res_point_unit
end
# whatever the iteration, last vertex is always the one returned
@test lmo_cached.last_vertex == res_point_cached
end
empty!(lmo_multicached)
@test length(lmo_multicached) == 0
empty!(lmo_veccached)
@test length(lmo_veccached) == 0
end
function _is_doubly_stochastic(m)
for col in eachcol(m)
@test sum(col) == 1
end
for row in eachrow(m)
@test sum(row) == 1
end
end
@testset "Birkhoff polytope" begin
Random.seed!(42)
lmo = FrankWolfe.BirkhoffPolytopeLMO()
for n in (1, 2, 10)
cost = rand(n, n)
res = FrankWolfe.compute_extreme_point(lmo, cost)
_is_doubly_stochastic(res)
res2 = FrankWolfe.compute_extreme_point(lmo, vec(cost))
@test vec(res) ≈ res2
end
cost_mat = [
2 3 3
3 2 3
3 3 2
]
res = FrankWolfe.compute_extreme_point(lmo, cost_mat)
@test res == I
@test sum(cost_mat .* res) == 6
cost_mat = [
3 2 3
2 3 3
3 3 2
]
res = FrankWolfe.compute_extreme_point(lmo, cost_mat)
@test sum(cost_mat .* res) == 6
@test res == Bool[
0 1 0
1 0 0
0 0 1
]
cost_mat = [
3 2 3
3 3 2
2 3 3
]
res = FrankWolfe.compute_extreme_point(lmo, cost_mat)
@test dot(cost_mat, res) == 6
@test res == Bool[
0 1 0
0 0 1
1 0 0
]
end
@testset "Matrix completion and nuclear norm" begin
nfeat = 50
nobs = 100
r = 5
Xreal = Matrix{Float64}(undef, nobs, nfeat)
X_gen_cols = randn(nfeat, r)
X_gen_rows = randn(r, nobs)
svals = 100 * rand(r)
for i in 1:nobs
for j in 1:nfeat
Xreal[i, j] = sum(X_gen_cols[j, k] * X_gen_rows[k, i] * svals[k] for k in 1:r)
end
end
@test rank(Xreal) == r
missing_entries = unique!([(rand(1:nobs), rand(1:nfeat)) for _ in 1:1000])
f(X) =
0.5 *
sum((X[i, j] - Xreal[i, j])^2 for i in 1:nobs, j in 1:nfeat if (i, j) ∉ missing_entries)
function grad!(storage, X)
storage .= 0
for i in 1:nobs
for j in 1:nfeat
if (i, j) ∉ missing_entries
storage[i, j] = X[i, j] - Xreal[i, j]
end
end
end
return nothing
end
# TODO value of radius?
lmo = FrankWolfe.NuclearNormLMO(sum(svdvals(Xreal)))
x0 = @inferred FrankWolfe.compute_extreme_point(lmo, zero(Xreal))
gradient = similar(x0)
grad!(gradient, x0)
v0 = FrankWolfe.compute_extreme_point(lmo, gradient)
@test dot(v0 - x0, gradient) < 0
xfin, vmin, _ = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0;
epsilon=1e-6,
max_iteration=400,
print_iter=100,
trajectory=false,
verbose=false,
line_search=FrankWolfe.Backtracking(),
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test 1 - (f(x0) - f(xfin)) / f(x0) < 1e-3
svals_fin = svdvals(xfin)
@test sum(svals_fin[r+1:end]) / sum(svals_fin) ≤ 2e-2
xfin, vmin, _ = FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo,
x0;
epsilon=1e-6,
max_iteration=400,
print_iter=100,
trajectory=false,
verbose=false,
line_search=FrankWolfe.Backtracking(),
memory_mode=FrankWolfe.InplaceEmphasis(),
)
end
@testset "Spectral norms" begin
Random.seed!(42)
o = Hypatia.Optimizer()
MOI.set(o, MOI.Silent(), true)
optimizer = MOI.Bridges.full_bridge_optimizer(
MOI.Utilities.CachingOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
o,
),
Float64,
)
radius = 5.0
@testset "Spectraplex $n" for n in (2, 10)
lmo = FrankWolfe.SpectraplexLMO(radius, n)
direction = Matrix{Float64}(undef, n, n)
lmo_moi = FrankWolfe.convert_mathopt(lmo, optimizer; side_dimension=n, use_modify=false)
for _ in 1:10
Random.randn!(direction)
v = @inferred FrankWolfe.compute_extreme_point(lmo, direction)
vsym = @inferred FrankWolfe.compute_extreme_point(lmo, direction + direction')
vsym2 =
@inferred FrankWolfe.compute_extreme_point(lmo, Symmetric(direction + direction'))
@test v ≈ vsym atol = 1e-6
@test v ≈ vsym2 atol = 1e-6
@testset "Vertex properties" begin
eigen_v = eigen(Matrix(v))
@test eigmax(Matrix(v)) ≈ radius
@test norm(eigen_v.values[1:end-1]) ≈ 0 atol = 1e-7
# u can be sqrt(r) * vec or -sqrt(r) * vec
case_pos =
≈(norm(eigen_v.vectors[:, n] * sqrt(eigen_v.values[n]) - v.u), 0, atol=1e-9)
case_neg =
≈(norm(eigen_v.vectors[:, n] * sqrt(eigen_v.values[n]) + v.u), 0, atol=1e-9)
@test case_pos || case_neg
end
@testset "Comparison with SDP solution" begin
v_moi = FrankWolfe.compute_extreme_point(lmo_moi, direction)
@test norm(v - v_moi) <= 1e-6
end
end
end
@testset "Unit spectrahedron $n" for n in (2, 10)
lmo = FrankWolfe.UnitSpectrahedronLMO(radius, n)
direction = Matrix{Float64}(undef, n, n)
lmo_moi = FrankWolfe.convert_mathopt(lmo, optimizer; side_dimension=n, use_modify=false)
direction_sym = similar(direction)
for _ in 1:10
Random.randn!(direction)
@. direction_sym = direction + direction'
v = @inferred FrankWolfe.compute_extreme_point(lmo, direction)
vsym = @inferred FrankWolfe.compute_extreme_point(lmo, direction_sym)
@test v ≈ vsym atol = 1e-6
@testset "Vertex properties" begin
emin = eigmin(direction_sym)
if emin ≥ 0
@test norm(Matrix(v)) ≈ 0
else
eigen_v = eigen(Matrix(v))
@test eigmax(Matrix(v)) ≈ radius
@test norm(eigen_v.values[1:end-1]) ≈ 0 atol = 1e-7
# u can be sqrt(r) * vec or -sqrt(r) * vec
case_pos =
≈(norm(eigen_v.vectors[:, n] * sqrt(eigen_v.values[n]) - v.u), 0, atol=1e-9)
case_neg =
≈(norm(eigen_v.vectors[:, n] * sqrt(eigen_v.values[n]) + v.u), 0, atol=1e-9)
@test case_pos || case_neg
# make direction PSD
direction_sym += 1.1 * abs(emin) * I
@assert isposdef(direction_sym)
v2 = FrankWolfe.compute_extreme_point(lmo, direction_sym)
@test norm(Matrix(v2)) ≈ 0
end
end
@testset "Comparison with SDP solution" begin
v_moi = FrankWolfe.compute_extreme_point(lmo_moi, direction)
@test norm(v - v_moi) <= 1e-6
# forcing PSD direction to test 0 matrix case
@. direction_sym = direction + direction'
direction_sym += 1.1 * abs(eigmin(direction_sym)) * I
@assert isposdef(direction_sym)
v_moi2 = FrankWolfe.compute_extreme_point(lmo_moi, direction_sym)
v_lmo2 = FrankWolfe.compute_extreme_point(lmo_moi, direction_sym)
@test norm(v_moi2 - v_lmo2) <= 1e-6
@test norm(v_moi2) <= 1e-6
end
end
end
end
@testset "MOI oracle consistency" begin
Random.seed!(42)
o = GLPK.Optimizer()
MOI.set(o, MOI.Silent(), true)
@testset "MOI oracle consistent with unit simplex" for n in (1, 2, 10)
MOI.empty!(o)
x = MOI.add_variables(o, n)
for xi in x
MOI.add_constraint(o, xi, MOI.Interval(0.0, 1.0))
end
MOI.add_constraint(
o,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(1.0, x), 0.0),
MOI.LessThan(1.0),
)
lmo = FrankWolfe.MathOptLMO(o)
lmo_ref = FrankWolfe.UnitSimplexOracle(1.0)
lmo_moi_ref = FrankWolfe.convert_mathopt(lmo_ref, GLPK.Optimizer(), dimension=n)
direction = Vector{Float64}(undef, n)
for _ in 1:5
Random.randn!(direction)
vref = compute_extreme_point(lmo_ref, direction)
v = compute_extreme_point(lmo, direction)
v_moi = compute_extreme_point(lmo_moi_ref, direction)
@test vref ≈ v
@test vref ≈ v_moi
end
end
@testset "MOI consistent probability simplex" for n in (1, 2, 10)
MOI.empty!(o)
x = MOI.add_variables(o, n)
for xi in x
MOI.add_constraint(o, xi, MOI.Interval(0.0, 1.0))
end
MOI.add_constraint(
o,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(1.0, x), 0.0),
MOI.EqualTo(1.0),
)
lmo = FrankWolfe.MathOptLMO(o)
lmo_ref = FrankWolfe.ProbabilitySimplexOracle(1.0)
lmo_moi_ref = FrankWolfe.convert_mathopt(lmo_ref, GLPK.Optimizer(), dimension=n)
direction = Vector{Float64}(undef, n)
for _ in 1:5
Random.randn!(direction)
vref = compute_extreme_point(lmo_ref, direction)
v = compute_extreme_point(lmo, direction)
v_moi = compute_extreme_point(lmo_moi_ref, direction)
@test vref ≈ v
@test vref ≈ v_moi
end
end
@testset "Direction with coefficients" begin
n = 5
MOI.empty!(o)
x = MOI.add_variables(o, n)
for xi in x
MOI.add_constraint(o, xi, MOI.Interval(0.0, 1.0))
end
MOI.add_constraint(
o,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(1.0, x), 0.0),
MOI.EqualTo(1.0),
)
lmo = FrankWolfe.MathOptLMO(o, false)
direction = [MOI.ScalarAffineTerm(-2.0i, x[i]) for i in 2:3]
v = compute_extreme_point(lmo, direction)
@test v ≈ [0, 1]
end
@testset "Non-settable optimizer with cache" begin
n = 5
o = MOI.Utilities.CachingOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
Clp.Optimizer(),
)
MOI.set(o, MOI.Silent(), true)
x = MOI.add_variables(o, 5)
for xi in x
MOI.add_constraint(o, xi, MOI.Interval(0.0, 1.0))
end
MOI.add_constraint(
o,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(1.0, x), 0.0),
MOI.EqualTo(1.0),
)
lmo = FrankWolfe.MathOptLMO(o, false)
lmo_ref = FrankWolfe.ProbabilitySimplexOracle(1.0)
direction = Vector{Float64}(undef, n)
for _ in 1:5
Random.randn!(direction)
vref = compute_extreme_point(lmo_ref, direction)
v = compute_extreme_point(lmo, direction)
@test vref ≈ v
end
end
@testset "Nuclear norm" for n in (5, 10)
o = Hypatia.Optimizer()
MOI.set(o, MOI.Silent(), true)
inner_optimizer = MOI.Utilities.CachingOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
o,
)
optimizer = MOI.Bridges.full_bridge_optimizer(inner_optimizer, Float64)
MOI.set(optimizer, MOI.Silent(), true)
nrows = 3n
ncols = n
direction = Matrix{Float64}(undef, nrows, ncols)
τ = 10.0
lmo = FrankWolfe.NuclearNormLMO(τ)
lmo_moi = FrankWolfe.convert_mathopt(
lmo,
optimizer,
row_dimension=nrows,
col_dimension=ncols,
use_modify=false,
)
nsuccess = 0
for _ in 1:10
randn!(direction)
v_r = FrankWolfe.compute_extreme_point(lmo, direction)
flattened = collect(vec(direction))
push!(flattened, 0)
v_moi = FrankWolfe.compute_extreme_point(lmo_moi, flattened)
if v_moi === nothing
# ignore non-terminating MOI solver results
continue
end
nsuccess += 1
v_moi_mat = reshape(v_moi[1:end-1], nrows, ncols)
@test v_r ≈ v_moi_mat rtol = 1e-2
end
@test nsuccess > 1
end
end
@testset "MOI oracle on Birkhoff polytope" begin
o = GLPK.Optimizer()
o_ref = GLPK.Optimizer()
for n in (1, 2, 10)
MOI.empty!(o)
(x, _) = MOI.add_constrained_variables(o, fill(MOI.Interval(0.0, 1.0), n * n))
xmat = reshape(x, n, n)
for idx in 1:n
# column constraint
MOI.add_constraint(
o,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), xmat[:, idx]), 0.0),
MOI.EqualTo(1.0),
)
# row constraint
MOI.add_constraint(
o,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(ones(n), xmat[idx, :]), 0.0),
MOI.EqualTo(1.0),
)
end
direction_vec = Vector{Float64}(undef, n * n)
lmo_bkf = FrankWolfe.BirkhoffPolytopeLMO()
lmo_moi = FrankWolfe.MathOptLMO(o)
lmo_moi_ref = FrankWolfe.convert_mathopt(lmo_bkf, o_ref, dimension=n)
for _ in 1:10
randn!(direction_vec)
direction_mat = reshape(direction_vec, n, n)
v_moi = FrankWolfe.compute_extreme_point(lmo_moi, direction_vec)
v_moi_mat = reshape(v_moi, n, n)
v_bfk = FrankWolfe.compute_extreme_point(lmo_bkf, direction_mat)
@test all(isapprox.(v_moi_mat, v_bfk, atol=1e-4))
v_moi_mat2 = FrankWolfe.compute_extreme_point(lmo_moi, direction_mat)
@test all(isapprox.(v_moi_mat2, v_moi_mat))
end
end
end
@testset "MOI oracle and KSparseLMO" begin
o_base = GLPK.Optimizer()
cached = MOI.Utilities.CachingOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
o_base,
)
o = MOI.Bridges.full_bridge_optimizer(cached, Float64)
o_ref = MOI.Bridges.full_bridge_optimizer(
MOI.Utilities.CachingOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
GLPK.Optimizer(),
),
Float64,
)
for n in (1, 2, 5, 10)
for K in 1:3:n
τ = 10 * rand()
MOI.empty!(o)
x = MOI.add_variables(o, n)
tinf = MOI.add_variable(o)
MOI.add_constraint(o, MOI.VectorOfVariables([tinf; x]), MOI.NormInfinityCone(n + 1))
MOI.add_constraint(o, tinf, MOI.LessThan(τ))
t1 = MOI.add_variable(o)
MOI.add_constraint(o, MOI.VectorOfVariables([t1; x]), MOI.NormOneCone(n + 1))
MOI.add_constraint(o, t1, MOI.LessThan(τ * K))
direction = Vector{Float64}(undef, n)
lmo_moi = FrankWolfe.MathOptLMO(o, false)
lmo_ksp = FrankWolfe.KSparseLMO(K, τ)
lmo_moi_convert =
FrankWolfe.convert_mathopt(lmo_ksp, o_ref, dimension=n, use_modify=false)
for _ in 1:20
randn!(direction)
v_moi =
FrankWolfe.compute_extreme_point(lmo_moi, MOI.ScalarAffineTerm.(direction, x))
v_ksp = FrankWolfe.compute_extreme_point(lmo_ksp, direction)
v_moi_conv = FrankWolfe.compute_extreme_point(
lmo_moi_convert,
MOI.ScalarAffineTerm.(direction, x),
)
for idx in eachindex(v_moi)
@test isapprox(v_moi[idx], v_ksp[idx], atol=1e-4)
@test isapprox(v_moi_conv[idx], v_ksp[idx], atol=1e-4)
end
end
# verifying absence of a bug
if n == 5
direction .= (
-0.07020498519126772,
0.4298929981513661,
-0.8678437699266819,
-0.08899938054920563,
1.160622285477465,
)
v_moi =
FrankWolfe.compute_extreme_point(lmo_moi, MOI.ScalarAffineTerm.(direction, x))
v_ksp = FrankWolfe.compute_extreme_point(lmo_ksp, direction)
for idx in eachindex(v_moi)
@test isapprox(v_moi[idx], v_ksp[idx], atol=1e-4)
end
end
end
end
end
@testset "Product LMO" begin
lmo = FrankWolfe.ProductLMO(FrankWolfe.LpNormLMO{Inf}(3.0), FrankWolfe.LpNormLMO{1}(2.0))
dinf = randn(10)
d1 = randn(5)
vtup = FrankWolfe.compute_extreme_point(lmo, (dinf, d1))
@test length(vtup) == 2
(vinf, v1) = vtup
@test sum(abs, vinf) ≈ 10 * 3.0
@test sum(!iszero, v1) == 1
vvec = FrankWolfe.compute_extreme_point(lmo, [dinf; d1], direction_indices=(1:10, 11:15))
@test vvec ≈ [vinf; v1]
# Test different constructor for ProductLMO and and direction as BlockVector
lmo2 = FrankWolfe.ProductLMO([FrankWolfe.LpNormLMO{Inf}(3.0), FrankWolfe.LpNormLMO{1}(2.0)])
v_block = FrankWolfe.compute_extreme_point(lmo2, FrankWolfe.BlockVector([dinf, d1]))
@test FrankWolfe.BlockVector([vinf, v1]) == v_block
end
@testset "Scaled L-1 norm polytopes" begin
lmo = FrankWolfe.ScaledBoundL1NormBall(-ones(10), ones(10))
# equivalent to LMO
lmo_ref = FrankWolfe.LpNormLMO{1}(1)
# all coordinates shifted up
lmo_shifted = FrankWolfe.ScaledBoundL1NormBall(zeros(10), 2 * ones(10))
lmo_scaled = FrankWolfe.ScaledBoundL1NormBall(-2 * ones(10), 2 * ones(10))
for _ in 1:100
d = randn(10)
v = FrankWolfe.compute_extreme_point(lmo, d)
vref = FrankWolfe.compute_extreme_point(lmo_ref, d)
@test v ≈ vref
vshift = FrankWolfe.compute_extreme_point(lmo_shifted, d)
@test v .+ 1 ≈ vshift
v2 = FrankWolfe.compute_extreme_point(lmo_scaled, d)
@test v2 ≈ 2v
end
d = zeros(10)
v = FrankWolfe.compute_extreme_point(lmo, d)
vref = FrankWolfe.compute_extreme_point(lmo_ref, d)
@test v ≈ vref
@test norm(v) == 1
# non-uniform scaling
# validates bugfix
lmo_nonunif = FrankWolfe.ScaledBoundL1NormBall([-1.0, -1.0], [3.0, 1.0])
direction = [-0.8272727272727383, -0.977272727272718]
v = FrankWolfe.compute_extreme_point(lmo_nonunif, direction)
@test v ≈ [3, 0]
v = FrankWolfe.compute_extreme_point(lmo_nonunif, -direction)
@test v ≈ [-1, 0]
end
@testset "Scaled L-inf norm polytopes" begin
# tests ScaledBoundLInfNormBall for the standard hypercube, a shifted one, and a scaled one
lmo = FrankWolfe.ScaledBoundLInfNormBall(-ones(10), ones(10))
lmo_ref = FrankWolfe.LpNormLMO{Inf}(1)
lmo_shifted = FrankWolfe.ScaledBoundLInfNormBall(zeros(10), 2 * ones(10))
lmo_scaled = FrankWolfe.ScaledBoundLInfNormBall(-2 * ones(10), 2 * ones(10))
bounds = collect(1.0:10)
# tests another ScaledBoundLInfNormBall with unequal bounds against a MOI optimizer
lmo_scaled_unequally = FrankWolfe.ScaledBoundLInfNormBall(-bounds, bounds)
o = GLPK.Optimizer()
MOI.set(o, MOI.Silent(), true)
x = MOI.add_variables(o, 10)
MOI.add_constraint.(o, x, MOI.GreaterThan.(-bounds))
MOI.add_constraint.(o, x, MOI.LessThan.(bounds))
scaled_unequally_opt = FrankWolfe.MathOptLMO(o)
for _ in 1:100
d = randn(10)
v = FrankWolfe.compute_extreme_point(lmo, d)
vref = FrankWolfe.compute_extreme_point(lmo_ref, d)
@test v ≈ vref
vshift = FrankWolfe.compute_extreme_point(lmo_shifted, d)
@test v .+ 1 ≈ vshift
v2 = FrankWolfe.compute_extreme_point(lmo_scaled, d)
@test v2 ≈ 2v
v3 = FrankWolfe.compute_extreme_point(lmo_scaled_unequally, d)
v3_test = compute_extreme_point(scaled_unequally_opt, d)
@test v3 ≈ v3_test
end
d = zeros(10)
v = FrankWolfe.compute_extreme_point(lmo, d)
vref = FrankWolfe.compute_extreme_point(lmo_ref, d)
@test v ≈ vref
@test norm(v, Inf) == 1
# test with non-flat array
lmo = FrankWolfe.ScaledBoundLInfNormBall(-ones(3, 3), ones(3, 3))
lmo_flat = FrankWolfe.ScaledBoundLInfNormBall(-ones(9), ones(9))
for _ in 1:10
d = randn(3, 3)
v = FrankWolfe.compute_extreme_point(lmo, d)
vflat = FrankWolfe.compute_extreme_point(lmo_flat, vec(d))
@test vec(v) == vflat
@test size(d) == size(v)
end
end
@testset "Copy MathOpt LMO" begin
o_clp = MOI.Utilities.CachingOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
Clp.Optimizer(),
)
for o in (GLPK.Optimizer(), o_clp)
MOI.set(o, MOI.Silent(), true)
n = 100
x = MOI.add_variables(o, n)
f = sum(1.0 * xi for xi in x)
MOI.add_constraint(o, f, MOI.LessThan(1.0))
MOI.add_constraint(o, f, MOI.GreaterThan(1.0))
lmo = FrankWolfe.MathOptLMO(o)
lmo2 = copy(lmo)
for d in (ones(n), -ones(n))
v = FrankWolfe.compute_extreme_point(lmo, d)
v2 = FrankWolfe.compute_extreme_point(lmo2, d)
@test v ≈ v2
end
end
end
@testset "MathOpt LMO with BlockVector" begin
o = GLPK.Optimizer()
MOI.set(o, MOI.Silent(), true)
x = MOI.add_variables(o, 10)
y = MOI.add_variables(o, 10)
MOI.add_constraint.(o, x, MOI.GreaterThan.(-ones(10)))
MOI.add_constraint.(o, x, MOI.LessThan.(ones(10)))
MOI.add_constraint.(o, y, MOI.GreaterThan.(-2 * ones(10)))
MOI.add_constraint.(o, y, MOI.LessThan.(2 * ones(10)))
lmo = FrankWolfe.MathOptLMO(o)
direction = FrankWolfe.BlockVector([ones(10), -ones(10)])
v = FrankWolfe.compute_extreme_point(lmo, direction)
v_ref = FrankWolfe.BlockVector([-ones(10), 2 * ones(10)])
@test v == v_ref
end
@testset "Inplace LMO correctness" begin
V = [-6.0, -6.15703, -5.55986]
M = [3.0 2.8464949 2.4178848; 2.8464949 3.0 2.84649498; 2.4178848 2.84649498 3.0]
fun0(p) = dot(V, p) + dot(p, M, p)
function fun0_grad!(g, p)
g .= V
return mul!(g, M, p, 2, 1)
end
lmo_dense = FrankWolfe.ScaledBoundL1NormBall(-ones(3), ones(3))
lmo_standard = FrankWolfe.LpNormLMO{1}(1.0)
x_dense, _, _, _, _ = FrankWolfe.frank_wolfe(fun0, fun0_grad!, lmo_dense, [1.0, 0.0, 0.0])
x_standard, _, _, _, _ = FrankWolfe.frank_wolfe(fun0, fun0_grad!, lmo_standard, [1.0, 0.0, 0.0])
@test x_dense == x_standard
lmo_dense = FrankWolfe.ScaledBoundLInfNormBall(-ones(3), ones(3))
lmo_standard = FrankWolfe.LpNormLMO{Inf}(1.0)
x_dense, _, _, _, _ = FrankWolfe.frank_wolfe(fun0, fun0_grad!, lmo_dense, [1.0, 0.0, 0.0])
x_standard, _, _, _, _ = FrankWolfe.frank_wolfe(fun0, fun0_grad!, lmo_standard, [1.0, 0.0, 0.0])
@test x_dense == x_standard
end
@testset "Ellipsoid LMO $n" for n in (2, 5, 10)
A = zeros(n, n)
A[1, 1] = 3
@test_throws PosDefException FrankWolfe.EllipsoidLMO(A)
for i in 1:n
A[i, i] = 3
end
radius = 4 * rand()
center = randn(n)
lmo = FrankWolfe.EllipsoidLMO(A, center, radius)
d = randn(n)
v = FrankWolfe.compute_extreme_point(lmo, d)
@test dot(v - center, A, v - center) ≈ radius atol = 1e-10
A = randn(n, n)
A += A'
while !isposdef(A)
A += I
end
lmo = FrankWolfe.EllipsoidLMO(A, center, radius)
d = randn(n)
v = FrankWolfe.compute_extreme_point(lmo, d)
@test dot(v - center, A, v - center) ≈ radius atol = 1e-10
m = Model(Hypatia.Optimizer)
@variable(m, x[1:n])
@constraint(m, dot(x - center, A, x - center) ≤ radius)
@objective(m, Min, dot(x, d))
JuMP.set_silent(m)
optimize!(m)
xv = JuMP.value.(x)
@test dot(xv, d) ≈ dot(v, d) atol = 1e-5 * n
end
@testset "Convex hull" begin
lmo = FrankWolfe.ConvexHullOracle([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
for _ in 1:100
d = randn(3)
v = FrankWolfe.compute_extreme_point(lmo, d)
v_simplex = FrankWolfe.compute_extreme_point(FrankWolfe.ProbabilitySimplexOracle(1), d)
@test v == v_simplex
end
d = zeros(3)
v = FrankWolfe.compute_extreme_point(lmo, d)
@test v == lmo.vertices[1]
end
@testset "Symmetric LMO" begin
# See examples/reynolds.jl
struct BellCorrelationsLMO{T} <: FrankWolfe.LinearMinimizationOracle
m::Int # number of inputs
tmp::Vector{T} # used to compute scalar products
end
function FrankWolfe.compute_extreme_point(
lmo::BellCorrelationsLMO{T},
A::Array{T,3};
kwargs...,
) where {T<:Number}
ax = [ones(T, lmo.m) for n in 1:3]
sc1 = zero(T)
sc2 = one(T)
axm = [zeros(Int, lmo.m) for n in 1:3]
scm = typemax(T)
L = 2^lmo.m
intax = zeros(Int, lmo.m)
for λa3 in 0:(L÷2)-1
digits!(intax, λa3, base=2)
ax[3][1:lmo.m] .= 2intax .- 1
for λa2 in 0:L-1
digits!(intax, λa2, base=2)
ax[2][1:lmo.m] .= 2intax .- 1
for x1 in 1:lmo.m
lmo.tmp[x1] = 0
for x2 in 1:lmo.m, x3 in 1:lmo.m
lmo.tmp[x1] += A[x1, x2, x3] * ax[2][x2] * ax[3][x3]
end
ax[1][x1] = lmo.tmp[x1] > zero(T) ? -one(T) : one(T)
end
sc = dot(ax[1], lmo.tmp)
if sc < scm
scm = sc
for n in 1:3
axm[n] .= ax[n]
end
end
end
end
return [
axm[1][x1] * axm[2][x2] * axm[3][x3] for x1 in 1:lmo.m, x2 in 1:lmo.m, x3 in 1:lmo.m
]
end
p = [0.5cos((i + j + k) * pi / 4) for i in 1:4, j in 1:4, k in 1:4]
normp2 = dot(p, p) / 2
f = let p = p, normp2 = normp2
x -> normp2 + dot(x, x) / 2 - dot(p, x)
end
grad! = let p = p
(storage, xit) -> begin
for x in eachindex(xit)
storage[x] = xit[x] - p[x]
end
end
end
function reynolds_permutedims(atom::Array{Int,3}, lmo::BellCorrelationsLMO{Float64})
res = zeros(size(atom))
for per in [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
res .+= permutedims(atom, per)
end
res ./= 6
return res
end
reynolds_adjoint(gradient, lmo) = gradient
lmo = BellCorrelationsLMO{Float64}(size(p, 1), zeros(size(p, 1)))
sym = FrankWolfe.SymmetricLMO(lmo, reynolds_permutedims, reynolds_adjoint)
x0 = FrankWolfe.compute_extreme_point(sym, -p)
active_set = FrankWolfe.ActiveSet([(1.0, x0)])
res = FrankWolfe.blended_pairwise_conditional_gradient(
f,
grad!,
sym,
active_set;
lazy=true,
line_search=FrankWolfe.Shortstep(1.0),
)
@test norm(res[1] - p) < 1e-6
@test length(res[6]) < 25
end
@testset "Ordered Weighted Norm LMO" begin
Random.seed!(4321)
N = Int(1e3)
for _ in 1:10
radius = abs(randn())+1
direction = randn(N)
#norm l1
weights = ones(N)
lmo = FrankWolfe.OrderWeightNormLMO(weights,radius)
lmo_l1 = FrankWolfe.LpNormLMO{1}(radius)
v1 = FrankWolfe.compute_extreme_point(lmo,direction)
v2 = FrankWolfe.compute_extreme_point(lmo_l1,direction)
@test v1 == v2
#norm L_∞
weights = zeros(N)
weights[1] = 1
lmo = FrankWolfe.OrderWeightNormLMO(weights,radius)
lmo_l_inf = FrankWolfe.LpNormLMO{Inf}(radius)
v1 = FrankWolfe.compute_extreme_point(lmo,direction)
v2 = FrankWolfe.compute_extreme_point(lmo_l_inf,direction)
@test v1 == v2
#symmetry
direction_opp = -1*direction
weights = rand(N)
lmo_opp = FrankWolfe.OrderWeightNormLMO(weights,radius)
v = FrankWolfe.compute_extreme_point(lmo_opp,direction)
v_opp = FrankWolfe.compute_extreme_point(lmo_opp,direction_opp)
@test v == -1*v_opp
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 918 | import FrankWolfe
import LinearAlgebra
import Random
using Test
n = Int(1e3)
k = 10000
s = rand(1:100)
@info "Seed: $s"
Random.seed!(s)
xpi = rand(n);
total = sum(xpi);
const xp = xpi ./ total;
f(x) = LinearAlgebra.norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
return nothing
end
lmo = FrankWolfe.UnitSimplexOracle(1.0)
x0 = FrankWolfe.compute_extreme_point(lmo, rand(n))
xblas, _ = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2.0),
memory_mode=FrankWolfe.OutplaceEmphasis(),
verbose=false,
trajectory=false,
momentum=0.9,
)
xmem, _ = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2.0),
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
trajectory=true,
momentum=0.9,
)
@test f(xblas) ≈ f(xmem)
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 2007 | import FrankWolfe
using LinearAlgebra
using Test
@testset "Testing adaptive LS when already optimal and gradient is 0" begin
f(x) = norm(x)^2
function grad!(storage, x)
return storage .= 2x
end
lmo = FrankWolfe.UnitSimplexOracle(1.0)
x00 = FrankWolfe.compute_extreme_point(lmo, ones(5))
x0 = copy(x00)
@test abs(
FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=true,
)[3],
) < 1.0e-10
x0 = copy(x00)
@test abs(
FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=1000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
verbose=true,
)[3],
) < 1.0e-10
@test abs(
FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=1000,
line_search=FrankWolfe.Adaptive(),
verbose=true,
)[3],
) < 1.0e-10
x0 = copy(x00)
@test abs(
FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=1000,
lazy=true,
line_search=FrankWolfe.AdaptiveZerothOrder(),
verbose=true,
)[3],
) < 1.0e-10
@test abs(
FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=1000,
lazy=true,
line_search=FrankWolfe.Adaptive(),
verbose=true,
)[3],
) < 1.0e-10
x0 = copy(x00)
@test abs(
FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=1000,
line_search=FrankWolfe.Adaptive(),
verbose=true,
)[3],
) < 1.0e-10
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 1239 |
using FrankWolfe
using LinearAlgebra
using Test
n = Int(1e3)
k = n
f(x) = dot(x, x)
function grad!(storage, x)
@. storage = 2 * x
end
# pick feasible region
lmo = FrankWolfe.ProbabilitySimplexOracle{Rational{BigInt}}(1); # radius needs to be integer or rational
# compute some initial vertex
x0 = FrankWolfe.compute_extreme_point(lmo, zeros(n));
x, v, primal, dual_gap0, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
xmem, vmem, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
copy(x0),
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
xstep, _ = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2 // 1),
print_iter=k / 10,
verbose=true,
)
@test eltype(xmem) == eltype(xstep) == Rational{BigInt}
if !(eltype(xmem) <: Rational)
@test eltype(xmem) == eltype(x)
end
@test xmem == x
@test abs(f(xstep) - f(x)) <= 1e-3
@test vmem == v
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 20804 | using FrankWolfe
using Test
using LinearAlgebra
using DoubleFloats
include("lmo.jl")
include("function_gradient.jl")
include("active_set.jl")
include("utils.jl")
include("active_set_variants.jl")
include("alternating_methods_tests.jl")
@testset "Testing vanilla Frank-Wolfe with various step size and momentum strategies" begin
f(x) = norm(x)^2
function grad!(storage, x)
return storage .= 2x
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, zeros(5))
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=10000,
line_search=FrankWolfe.GeneralizedAgnostic(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
g(x) = 2 + log(1 + log(x + 1))
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=10000,
line_search=FrankWolfe.GeneralizedAgnostic(g),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
gradient=collect(similar(x0)),
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Goldenratio(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Backtracking(),
verbose=false,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Nonconvex(),
verbose=false,
)[3] - 0.2,
) < 1.0e-2
@test FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Shortstep(2.0),
verbose=false,
)[3] ≈ 0.2
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Nonconvex(),
verbose=false,
)[3] - 0.2,
) < 1.0e-2
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
momentum=0.9,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
momentum=0.5,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
momentum=0.9,
memory_mode=FrankWolfe.InplaceEmphasis(),
)[3] - 0.2,
) < 1.0e-3
end
@testset "Gradient with momentum correctly updated" begin
# fixing https://github.com/ZIB-IOL/FrankWolfe.jl/issues/47
include("momentum_memory.jl")
end
@testset "Testing Lazified Conditional Gradients with various step size strategies" begin
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2x
return nothing
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, zeros(5))
@test abs(
FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Goldenratio(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Backtracking(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Shortstep(2.0),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.AdaptiveZerothOrder(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
end
@testset "Testing Lazified Conditional Gradients with cache strategies" begin
n = Int(1e5)
L = 2
k = 1000
bound = 16 * L * 2 / (k + 2)
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2 * x
return nothing
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, zeros(n))
x, v, primal, dual_gap, trajectory = FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2.0),
verbose=true,
)
@test primal - 1 / n <= bound
x, v, primal, dual_gap, trajectory = FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2.0),
cache_size=100,
verbose=false,
)
@test primal - 1 / n <= bound
x, v, primal, dual_gap, trajectory = FrankWolfe.lazified_conditional_gradient(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2.0),
cache_size=100,
greedy_lazy=true,
verbose=false,
)
@test primal - 1 / n <= bound
end
@testset "Testing memory_mode blas vs memory" begin
n = Int(1e5)
k = 100
xpi = rand(n)
total = sum(xpi)
xp = xpi ./ total
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
return nothing
end
@testset "Using sparse structure" begin
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1.0)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, spzeros(n))
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
@test primal < f(x0)
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test primal < f(x0)
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.MonotonicStepSize(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test primal < f(x0)
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.MonotonicNonConvexStepSize(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test primal < f(x0)
end
end
@testset "Testing rational variant" begin
rhs = 1
n = 40
k = 1000
xpi = rand(big(1):big(100), n)
total = sum(xpi)
xp = xpi .// total
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
lmo = FrankWolfe.ProbabilitySimplexOracle{Rational{BigInt}}(rhs)
direction = rand(n)
x0 = FrankWolfe.compute_extreme_point(lmo, direction)
@test eltype(x0) == Rational{BigInt}
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
memory_mode=FrankWolfe.OutplaceEmphasis(),
verbose=false,
)
@test eltype(x0) == Rational{BigInt}
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
)
@test eltype(x0) == eltype(x) == Rational{BigInt}
@test f(x) <= 1e-4
# very slow computation, explodes quickly
x0 = collect(FrankWolfe.compute_extreme_point(lmo, direction))
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=15,
line_search=FrankWolfe.Shortstep(2 // 1),
print_iter=k / 100,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
)
x0 = FrankWolfe.compute_extreme_point(lmo, direction)
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=15,
line_search=FrankWolfe.Shortstep(2 // 1),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
)
@test eltype(x) == Rational{BigInt}
end
@testset "Multi-precision tests" begin
rhs = 1
n = 100
k = 1000
xp = zeros(n)
L = 2
bound = 2 * L * 2 / (k + 2)
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
test_types = (Float16, Float32, Float64, Double64, BigFloat, Rational{BigInt})
@testset "Multi-precision test for $T" for T in test_types
lmo = FrankWolfe.ProbabilitySimplexOracle{T}(rhs)
direction = rand(n)
x0 = FrankWolfe.compute_extreme_point(lmo, direction)
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
memory_mode=FrankWolfe.OutplaceEmphasis(),
verbose=false,
)
@test eltype(x0) == T
@test primal - 1 / n <= bound
x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
)
@test eltype(x0) == T
@test primal - 1 // n <= bound
x, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
)
@test eltype(x0) == T
@test primal - 1 // n <= bound
x, v, primal, dual_gap, trajectory, _ = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=true,
)
@test eltype(x0) == T
@test primal - 1 // n <= bound
end
end
@testset "Stochastic FW linear regression" begin
function simple_reg_loss(θ, data_point)
(xi, yi) = data_point
(a, b) = (θ[1:end-1], θ[end])
pred = a ⋅ xi + b
return (pred - yi)^2 / 2
end
function ∇simple_reg_loss(storage, θ, data_point)
(xi, yi) = data_point
(a, b) = (θ[1:end-1], θ[end])
pred = a ⋅ xi + b
storage[1:end-1] .+= xi * (pred - yi)
storage[end] += pred - yi
return storage
end
xs = [10 * randn(5) for i in 1:20000]
params = rand(6) .- 1 # start params in (-1,0)
bias = 2π
params_perfect = [1:5; bias]
params = rand(6) .- 1 # start params in (-1,0)
data_perfect = [(x, x ⋅ (1:5) + bias) for x in xs]
f_stoch = FrankWolfe.StochasticObjective(
simple_reg_loss,
∇simple_reg_loss,
data_perfect,
similar(params),
)
lmo = FrankWolfe.LpNormLMO{2}(1.1 * norm(params_perfect))
θ, _, _, _, _ = FrankWolfe.stochastic_frank_wolfe(
f_stoch,
lmo,
copy(params),
momentum=0.95,
verbose=false,
line_search=FrankWolfe.Nonconvex(),
max_iteration=100_000,
batch_size=length(f_stoch.xs) ÷ 100,
trajectory=false,
)
@test norm(θ - params_perfect) ≤ 0.05 * length(θ)
# SFW with incrementing batch size
batch_iterator =
FrankWolfe.IncrementBatchIterator(length(f_stoch.xs) ÷ 1000, length(f_stoch.xs) ÷ 10, 2)
θ, _, _, _, _ = FrankWolfe.stochastic_frank_wolfe(
f_stoch,
lmo,
copy(params),
momentum=0.95,
verbose=false,
line_search=FrankWolfe.Nonconvex(),
max_iteration=5000,
batch_iterator=batch_iterator,
trajectory=false,
)
@test batch_iterator.maxreached
# SFW damped momentum
momentum_iterator = FrankWolfe.ExpMomentumIterator()
θ, _, _, _, _ = FrankWolfe.stochastic_frank_wolfe(
f_stoch,
lmo,
copy(params),
verbose=false,
line_search=FrankWolfe.Nonconvex(),
max_iteration=5000,
batch_size=1,
trajectory=false,
momentum_iterator=momentum_iterator,
)
θ, _, _, _, _ = FrankWolfe.stochastic_frank_wolfe(
f_stoch,
lmo,
copy(params),
line_search=FrankWolfe.Nonconvex(),
max_iteration=5000,
batch_size=1,
verbose=false,
trajectory=false,
momentum_iterator=nothing,
)
end
@testset "Away-step FW" begin
n = 50
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1.0)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, rand(n))
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2x
end
k = 1000
active_set = ActiveSet([(1.0, x0)])
# compute reference from vanilla FW
xref, _ = FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
x, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
@test x !== nothing
@test xref ≈ x atol = (1e-3 / length(x))
xs, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
active_set,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
@test xs !== nothing
@test xref ≈ xs atol = (1e-3 / length(x))
x, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
away_steps=false,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
@test x !== nothing
@test xref ≈ x atol = (1e-3 / length(x))
xs, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
active_set,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
@test xs !== nothing
@test xref ≈ xs atol = (1e-3 / length(x))
x, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test x !== nothing
@test xref ≈ x atol = (1e-3 / length(x))
x, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
away_steps=false,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test x !== nothing
@test xref ≈ x atol = (1e-3 / length(x))
xs, v, primal, dual_gap, trajectory = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
active_set,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.InplaceEmphasis(),
)
@test xs !== nothing
@test xref ≈ xs atol = (1e-3 / length(x))
empty!(active_set)
@test_throws ArgumentError("Empty active set") FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo_prob,
active_set,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
print_iter=k / 10,
verbose=true,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
end
@testset "Blended conditional gradient" begin
n = 50
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1.0)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, randn(n))
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2x
end
k = 1000
# compute reference from vanilla FW
xref, _ = FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=k,
line_search=FrankWolfe.Backtracking(),
verbose=true,
memory_mode=FrankWolfe.OutplaceEmphasis(),
)
x, v, primal, dual_gap, trajectory, _ = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo_prob,
x0;
line_search=FrankWolfe.Backtracking(),
epsilon=1e-9,
max_iteration=k,
print_iter=1,
trajectory=false,
verbose=false,
)
@test x !== nothing
@test f(x) ≈ f(xref)
end
include("oddities.jl")
include("tracking.jl")
# in separate module for name space issues
module BCGDirectionError
using Test
@testset "BCG direction accuracy" begin
include("bcg_direction_error.jl")
end
end
module RationalTest
using Test
@testset "Rational test and shortstep" begin
include("rational_test.jl")
end
end
module BCGAccel
using Test
@testset "BCG acceleration with different types" begin
include("blended_accelerated.jl")
end
end
module VertexStorageTest
using Test
@testset "Vertex storage" begin
include("extra_storage.jl")
end
end
include("generic-arrays.jl")
include("blocks.jl")
@testset "End-to-end trajectory tests" begin
trajectory_testfiles = readdir(joinpath(@__DIR__, "trajectory_tests"), join=true)
for file in trajectory_testfiles
@eval Module() begin
Base.include(@__MODULE__, $file)
end
end
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 4582 | using FrankWolfe
using LinearAlgebra
using SparseArrays
@testset "Timing out" begin
f(x) = norm(x)^2
function grad!(storage, x)
return storage .= 2x
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, spzeros(5))
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
gradient=collect(similar(x0)),
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Goldenratio(),
verbose=true,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Backtracking(),
verbose=false,
)[3] - 0.2,
) < 1.0e-5
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Nonconvex(),
verbose=false,
)[3] - 0.2,
) < 1.0e-2
@test FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Shortstep(2.0),
verbose=false,
)[3] ≈ 0.2
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Nonconvex(),
verbose=false,
)[3] - 0.2,
) < 1.0e-2
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
momentum=0.9,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
momentum=0.5,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Agnostic(),
verbose=false,
momentum=0.9,
memory_mode=FrankWolfe.InplaceEmphasis(),
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=100.0),
verbose=false,
momentum=0.9,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Adaptive(L_est=100.0),
verbose=false,
momentum=0.9,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Adaptive(L_est=100.0),
verbose=false,
momentum=0.5,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=100.0),
verbose=false,
momentum=0.5,
)[3] - 0.2,
) < 1.0e-3
@test abs(
FrankWolfe.frank_wolfe(
f,
grad!,
lmo_prob,
x0,
max_iteration=1000,
line_search=FrankWolfe.Adaptive(L_est=100.0),
verbose=false,
momentum=0.9,
memory_mode=FrankWolfe.InplaceEmphasis(),
)[3] - 0.2,
) < 1.0e-3
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 2854 | using Test
using LinearAlgebra
using SparseArrays
using FrankWolfe
@testset "Tracking Testset" begin
f(x) = norm(x)^2
function grad!(storage, x)
return storage .= 2x
end
x = zeros(6)
gradient = similar(x)
rhs = 10 * rand()
lmo = FrankWolfe.ProbabilitySimplexOracle(rhs)
direction = zeros(6)
direction[1] = -1
@testset "TrackingGradient" begin
tgrad! = FrankWolfe.TrackingGradient(grad!)
@test tgrad!.counter == 0
@test tgrad!.grad! === grad!
tgrad!(gradient, direction)
@test tgrad!.counter == 1
end
@testset "TrackingObjective" begin
tf = FrankWolfe.TrackingObjective(f, 0)
@test tf.counter == 0
tf(x)
@test tf.counter == 1
end
@testset "TrackingLMO" begin
tlmo_prob = FrankWolfe.TrackingLMO(lmo, 0)
@test tlmo_prob.counter == 0
@test tlmo_prob.lmo === lmo
compute_extreme_point(tlmo_prob, direction)
@test tlmo_prob.counter == 1
end
end
@testset "Testing vanilla Frank-Wolfe with various step size and momentum strategies" begin
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2x
end
lmo = FrankWolfe.ProbabilitySimplexOracle(1)
tf = FrankWolfe.TrackingObjective(f, 0)
tgrad! = FrankWolfe.TrackingGradient(grad!, 0)
tlmo = FrankWolfe.TrackingLMO(lmo)
storage = []
x0 = FrankWolfe.compute_extreme_point(tlmo, spzeros(1000))
FrankWolfe.frank_wolfe(
tf,
tgrad!,
tlmo,
x0,
line_search=FrankWolfe.Agnostic(),
max_iteration=50,
trajectory=true,
callback=nothing,
traj_data=storage,
verbose=true,
)
@test length(storage[1]) == 5
niters = length(storage)
@test tf.counter == niters
@test tgrad!.counter == niters
@test tlmo.counter == niters + 1 # x0 computation and initialization
end
@testset "Testing lazified Frank-Wolfe with various step size and momentum strategies" begin
f(x) = norm(x)^2
function grad!(storage, x)
@. storage = 2x
end
lmo = FrankWolfe.ProbabilitySimplexOracle(1)
tf = FrankWolfe.TrackingObjective(f, 0)
tgrad! = FrankWolfe.TrackingGradient(grad!, 0)
tlmo = FrankWolfe.TrackingLMO(lmo)
storage = []
x0 = FrankWolfe.compute_extreme_point(tlmo, spzeros(1000))
results = FrankWolfe.lazified_conditional_gradient(
tf,
tgrad!,
tlmo,
x0,
line_search=FrankWolfe.Agnostic(),
max_iteration=50,
trajectory=true,
callback=nothing,
traj_data=storage,
verbose=false,
)
@test length(storage[1]) == 5
niters = length(storage)
@test tf.counter == niters
@test tgrad!.counter == niters
# lazification
@test tlmo.counter < niters
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 5815 | import FrankWolfe
using LinearAlgebra
using Test
using SparseArrays
@testset "Simple benchmark_oracles function" begin
n = Int(1e3)
xpi = rand(n)
total = sum(xpi)
xp = xpi ./ total
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
lmo_prob = FrankWolfe.ProbabilitySimplexOracle(1)
x0 = FrankWolfe.compute_extreme_point(lmo_prob, zeros(n))
FrankWolfe.benchmark_oracles(f, grad!, () -> rand(n), lmo_prob; k=100)
end
@testset "RankOneMatrix" begin
for n in (1, 2, 5)
for _ in 1:5
v = rand(n)
u = randn(2n)
M = u * v'
R = FrankWolfe.RankOneMatrix(u, v)
for i in 1:2n
for j in 1:n
@test M[i, j] ≈ R[i, j]
end
end
@testset "Right- left-mul" for _ in 1:5
x = rand(n)
r1 = R * x
r2 = M * x
@test r1 ≈ r2
end
@testset "Identity test" begin
x = 1.0
r1 = R
r2 = R * x
@test r1 ≈ r2
end
@testset "Add and sub" begin
@test M + R ≈ R + R
@test M - R ≈ R - R
MR = -R
@test MR isa FrankWolfe.RankOneMatrix
@test -MR == R
@test 3R isa FrankWolfe.RankOneMatrix
end
@testset "Dot, norm, mul" begin
@test dot(R, M) ≈ dot(collect(R), M)
@test dot(M, R) ≈ dot(M, collect(R))
@test dot(R, sparse(M)) ≈ dot(collect(R), M)
@test norm(R) ≈ norm(collect(R))
@test R * M' ≈ R * transpose(M) ≈ M * M'
end
end
end
end
@testset "RankOne muladd_memory_mode $n" for n in (1, 2, 5)
for _ in 1:5
n = 5
v = rand(n)
u = randn(2n)
M = u * v'
R = FrankWolfe.RankOneMatrix(u, v)
X = similar(M)
X .= 0
FrankWolfe.muladd_memory_mode(FrankWolfe.InplaceEmphasis(), X, 0.7, R)
X2 = similar(M)
X2 .= 0
FrankWolfe.muladd_memory_mode(FrankWolfe.InplaceEmphasis(), X2, 0.7, M)
@test norm(M - R) ≤ 1e-14
@test norm(X - X2) ≤ 1e-14
end
end
@testset "Line Search methods" begin
a = [-1.0, -1.0, -1.0]
b = [1.0, 1.0, 1.0]
function grad!(storage, x)
return storage .= 2x
end
f(x) = norm(x)^2
gradient = similar(a)
grad!(gradient, a)
function reset_state()
gradient .= 0
grad!(gradient, a)
end
ls = FrankWolfe.Backtracking()
reset_state()
gamma_bt = @inferred FrankWolfe.perform_line_search(
ls,
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
FrankWolfe.build_linesearch_workspace(ls, a, gradient),
FrankWolfe.InplaceEmphasis(),
)
@test gamma_bt ≈ 0.5
ls_secant = FrankWolfe.Secant()
reset_state()
gamma_secant = @inferred FrankWolfe.perform_line_search(
ls_secant,
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
FrankWolfe.build_linesearch_workspace(ls_secant, a, gradient),
FrankWolfe.InplaceEmphasis(),
)
@test gamma_secant ≈ 0.5
ls_gr = FrankWolfe.Goldenratio()
reset_state()
gamma_gr = @inferred FrankWolfe.perform_line_search(
ls_gr,
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
FrankWolfe.build_linesearch_workspace(ls_gr, a, gradient),
FrankWolfe.InplaceEmphasis(),
)
@test gamma_gr ≈ 0.5 atol = 1e-4
reset_state()
@inferred FrankWolfe.perform_line_search(
FrankWolfe.Agnostic(),
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
nothing,
FrankWolfe.InplaceEmphasis(),
)
reset_state()
@inferred FrankWolfe.perform_line_search(
FrankWolfe.Nonconvex(),
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
nothing,
FrankWolfe.InplaceEmphasis(),
)
reset_state()
@inferred FrankWolfe.perform_line_search(
FrankWolfe.Nonconvex(),
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
nothing,
FrankWolfe.InplaceEmphasis(),
)
ls = @inferred FrankWolfe.AdaptiveZerothOrder()
reset_state()
@inferred FrankWolfe.perform_line_search(
ls,
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
FrankWolfe.build_linesearch_workspace(ls, a, gradient),
FrankWolfe.InplaceEmphasis(),
)
ls = @inferred FrankWolfe.Adaptive()
reset_state()
@inferred FrankWolfe.perform_line_search(
ls,
1,
f,
grad!,
gradient,
a,
a - b,
1.0,
FrankWolfe.build_linesearch_workspace(ls, a, gradient),
FrankWolfe.InplaceEmphasis(),
)
end
@testset "Momentum tests" begin
it = FrankWolfe.ExpMomentumIterator()
it.num = 0
# no momentum -> 1
@test FrankWolfe.momentum_iterate(it) == 1
end
@testset "Fast dot complex & norm" begin
s = sparse(I, 3, 3)
m = randn(Complex{Float64}, 3, 3)
@test dot(s, m) ≈ FrankWolfe.fast_dot(s, m)
@test dot(m, s) ≈ FrankWolfe.fast_dot(m, s)
a = FrankWolfe.ScaledHotVector(3.5 + 2im, 2, 4)
b = rand(ComplexF64, 4)
@test dot(a, b) ≈ dot(collect(a), b)
@test dot(b, a) ≈ dot(b, collect(a))
c = sparse(b)
@test dot(a, c) ≈ dot(collect(a), c)
@test dot(c, a) ≈ dot(c, collect(a))
@test norm(a) ≈ norm(collect(a))
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 35649 | using FrankWolfe
using Test
using LinearAlgebra
@testset "Approximate Caratheodory" begin
n = Int(1e2)
k = n
f(x) = dot(x, x)
function grad!(storage, x)
@. storage = 2 * x
end
lmo = FrankWolfe.ProbabilitySimplexOracle{Rational{BigInt}}(1)
x0 = FrankWolfe.compute_extreme_point(lmo, zeros(n))
res1 = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
trajectory=true,
)
x_true = [
0.0003882741215298000420906058020008131649408310609791293789170887356180438746488335,
0.01980198019801980174204644541789292442808870460109720167417109952972281608614392,
0.0005824111822947000954662239221379876968608268608067998030881882653408599607928077,
0.0007765482430596001991334434942656928089513067592163031453228607158571840579260239,
0.0009706853038245001142071576214289134799237722821789055237774017039680826787031422,
0.001164822364589400111184336970405283587112639773765304875456557608308253871966003,
0.001358959425354300205152461976791955089903124178924704383577732186271746843393673,
0.001553096486119200123613161507864747469883195782712153608246462591276847641400415,
0.001747233546884100357294434425521019957092786851921236172277015496813510946277349,
0.001941370607649000355084148151697916605542320405471402241189730786877249702816797,
0.002135507668413900189066931434248524727347073349191061808421826725016298033411679,
0.002329644729178800488410312568010179561296432106402094015372436636547190870300332,
0.002523781789943700225565434613449155479169439923525110640264880421825234405418941,
0.002717918850708600350269848067771177013721412922862882874142871429918104894240619,
0.00291205591147350041570201695367579159623787972254067984203230754762306055249153,
0.003106192972238400394560786197225285036706905836085303605037534758293128693317118,
0.003300330033003300258916355706332062721509041503956562888727843249850295719733871,
0.003494467093768200251325330593196232310842990450393933524221947330680444464801797,
0.003688604154533100697556137630165387507087463584696562039873803199973987540303863,
0.003882741215298000280510808464921223759615693413602755056045890689674985547160767,
0.00407687827606290064532026901580120486067843846746828308661372200214047850445762,
0.004271015336827800427670876015566418686819475875595140831696815232904816981848156,
0.004465152397592700300644336281093783497378622647194256618042782330258695147220924,
0.004659289458357600677783291847942320143740766052565949841229649920963748897450388,
0.004853426519122500896862928565677777041960696594773910546541017125149389768231225,
0.005047563579887400349929630024666106085486734275760558106092747026142268542084198,
0.005241700640652300341005936027750888413411734405841787912836956874284273716155194,
0.00543583770141720057436003632732971030264900193553537983270382110156803150697447,
0.005629974762182100589292066545240496295677412189293474973894895544004801637854435,
0.005824111822947000517638310026842471159962562890845771609185545744710134470069804,
0.006018248883711900701932882326610513372895371860262337947266895500772264370506452,
0.006212385944476800908128635903858300909265914693511109145245709075835008967892594,
0.00640652300524170066422578228968641770665207338003948639873636061394374866678618,
0.006600660066006600557359378411173783772985854572743890592194880849228212329337688,
0.006794797126771500386545512812456811572419257253162939345016658340655232305565304,
0.006988934187536401195686594588074609470046050625234469822884195336852657125810076,
0.007183071248301300409266749345183476159104719175745343710122816828861705300913898,
0.007377208309066200560061965330916936616011159980384306485951899215672861836708123,
0.007571345369831101279899089099088304922555625123844674161593767025998054468133567,
0.007765482430596001164881812390191680924328763077692843290633454302067358885193008,
0.007959619491360900453909058475207330562637289289433195582248086795503407199549887,
0.008153756552125800798928511006417766098936651650480496399871402018830343330168034,
0.008347893612890701176534868560091450195396973866365810906807885915571452626113312,
0.008542030673655601307967178640919486153647539009220933851635363471482090487691809,
0.00873616773442050075078826721717919899202251630021742963554249833846591305019406,
0.008930304795185400788816446073157731797754066857474622838211076501534872729621664,
0.009124441855950300499031628042345539294270742940546650118460350669628920497759703,
0.009318578916715200251694679550134014468299418906561575450695397869751669122905964,
0.009512715977480101222301324703840348642382550557410309832498657210498216952646775,
0.009706853038245000904973779903363673581004979002947935413756836518327343874430699,
0.0099009900990099016320770682571002291766549020792077889481789544538601141709446,
0.01009512715977480070330824787906891629563373076946674992991200547443165470943348,
0.01028926422053970051637508985296103104660194327194007132380297848464365888908827,
0.01048340128130460057964603797243673491034795241123139853761533363574100564529313,
0.01067753834206950049433723497680551125679768720723401690218629975107771825032686,
0.01087167540283440048137975861551520190308648645415513892201368413746230465165757,
0.01106581246359930094519821056024475725539512769931169270997742942154266365415643,
0.0112599495243642010776072982374634441426459478403852462389394401015731387373364,
0.01145408658512910097148740796889579104395205691141874912211224599265740517284452,
0.01164822364589400177634721185875880307334706151764883596750916727135335832714923,
0.01184236070665890085000844219501227066229223105968599835591091296187120571031923,
0.01203649776742380050795620263230436802814918235516324391622967535376103153864806,
0.01223063482818870119508566421211684305164362598722788261331502425648517932718499,
0.01242477188895360192566433248854698343239195924888124543133065605136144662402779,
0.01261890894971850161645291494117749275706921765669271800234889834719208741784181,
0.01281304601048340103366692941290102843591929193787306581993324382956797460467683,
0.01300718307124830111155011896558288170400676047079890947090334808860479446565325,
0.0132013201320132014764352267990904589902516307904252174466644298270810754193482,
0.01339545719277810090490999756557855998351794416471997932888884896144015361937024,
0.01358959425354300165770749624107258273621732815857823972553851445204449384523709,
0.01378373131430790058353427727134755693341739798151426914212557635497450527288925,
0.01397786837507280056989595539462618913710466709102404872348580950795279206680487,
0.01417200543583770217307274924529067217964816864079098545083758936335685302700349,
0.01436614249660260235270996444740609603744037097610924457965873509741432887767511,
0.01456027955736750061985247998325491756704232592649562644968080288920001566116641,
0.01475441661813240244569157876376825183183079469330507518766274847124142133175206,
0.01494855367889730096019031098249851356565128185557548309989320843792554392292997,
0.01514269073966220125547184677174924561603050296439632178532462686450923065046429,
0.01533682780042710238420887516800915735472049531756248279604816939853819969912974,
0.01553096486119200066827888284966917628380692198382831995136190350118819394452864,
0.0157251019219569021087643008579889656067583836404881456889707058514564626115519,
0.01591923898272180243140911317995190618158270529328470342331381641626380482146769,
0.01611337604348670070620444686537384592071367002483289832602471899478622134821486,
0.01630751310425160138819624759733579805501498450009937461693400873057554799529194,
0.01650165016501650139926986008137823799559838250160816524032817173921091857383403,
0.01669578722578140141028007979048119408425319324677463861957170414247959742750423,
0.01688992428654630214076512442467616982886122586518095906913109519577109285864251,
0.01708406134731120120611506433379078225892196616485648363362907091079387525566909,
0.01727819840807610237377742877896019445606740817927518800647707479448108625659192,
0.01747233546884100312822173580837901199072761007053886286328615959502762658879238,
0.01766647252960590128265011872399721132014544232993445792944682128778320059295789,
0.0178606095903708032490284312604307728446385580457409920995885098087747905279215,
0.01805474665113570139561221383225131733707823572401386027164683146405154870468538,
0.01824888371190060143342528481993271072179130589404018055997421790869707617200101,
0.01844302077266550081901437253928410048000392634317940606703856904328115317566703,
0.01863715783343040149908517569608539728431614317130150542900034863564971816073049,
0.01883129489419530034004655890248654653852444965838982238279157704916206502274489,
0.01902543195496020351226333102072831389732383717536576363318028356443370391048994,
0.01921956901572510232266421678436112468933955605034956800251944650364831594880664,
0.01941370607649000218250087532506190641350721586961201686937898271255334512602753,
]
primal_true = 0.01314422099649411305714214236596045839642713180124049726321024688069930261252318
@test norm(res1[1] - x_true) ≈ 0 atol = 1e-6
@test res1[3] ≈ primal_true
@test res1[5][end][1] == 101
res2 = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2 // 1),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
trajectory=true,
)
x_true = fill(0.01, n)
primal_true = 0.01
@test norm(res2[1] - x_true) ≈ 0 atol = 1e-6
@test res2[3] ≈ primal_true
@test res2[5][end][1] == 100
res3 = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
trajectory=true,
)
x_true = [
0.01941747572815534389500426171171199030140996910631656646728515625,
0.0197982105463544663941262424788902762884390540421009063720703125,
0.000571102227298686689581364017698206225759349763393402099609375,
0.000761469636398249606103194597750416505732573568820953369140625,
0.0009518370454978121973643734321512965834699571132659912109375,
0.00114220445459737337916272803539641245151869952678680419921875,
0.00133257186369693564516325512414596232702024281024932861328125,
0.00152293927279649921220638919550083301146514713764190673828125,
0.00171330668189606061084517829584683568100444972515106201171875,
0.001903674090995624394728746864302593166939914226531982421875,
0.00209404150009518362496319099363972782157361507415771484375,
0.0022844089091947467583254560707928249030373990535736083984375,
0.0024747763182943077232833761769370539695955812931060791015625,
0.0026651437273938712903265102482919246540404856204986572265625,
0.00285551113649343442368877532544502173550426959991455078125,
0.003045878545592995388646695431589250802062451839447021484375,
0.003236245954692557220966353526137027074582874774932861328125,
0.00342661336379211818592427363228125614114105701446533203125,
0.0036169807728916821866482766978379004285670816898345947265625,
0.0038073481819912470547340177517980919219553470611572265625,
0.003997715591090806284968461881135226576589047908782958984375,
0.0041880830001903672499263819872794556431472301483154296875,
0.004378450409289933419054730023844967945478856563568115234375,
0.004568817818389493516650912141585649806074798107147216796875,
0.004759185227489053614247094259326331666670739650726318359375,
0.004949552636588615446566752353874107939191162586212158203125,
0.00513992004568817988097162441363252582959830760955810546875,
0.005330287454787742580653020496583849308080971240997314453125,
0.005520654863887302678249202614324531168676912784576416015625,
0.0057110222729868688473775506508900434710085391998291015625,
0.005901389682086429812335470757034272537566721439361572265625,
0.00609175709118599077729339086317850160412490367889404296875,
0.006282124500285551742251310969322730670683085918426513671875,
0.006472491909385111839847493087063412531279027462005615234375,
0.006662859318484675406890627158418283215723931789398193359375,
0.0068532267275842363718485472645625122822821140289306640625,
0.007043594136683799071529943347513835760764777660369873046875,
0.007233961545783364373296553395675800857134163379669189453125,
0.007424328954882922736169259536609388305805623531341552734375,
0.007614696363982494109468035503596183843910694122314453125,
0.00780506377308205247234074164452977129258215427398681640625,
0.0079954311821816108352134477854633587412536144256591796875,
0.00818579859128116919808615392639694618992507457733154296875,
0.0083761660003807310304058120209447224624454975128173828125,
0.00856653340948029286272547011549249873496592044830322265625,
0.00875690081857986336866250809407574706710875034332275390625,
0.0089472682276794286704291181422377121634781360626220703125,
0.00913763563677898182913139635275001637637615203857421875,
0.00932800304587855060034495835452617029659450054168701171875,
0.00951837045497810375904723656503847450949251651763916015625,
0.009708737864077665591366894659586250782012939453125,
0.00989910527317723089313350470774821587838232517242431640625,
0.01008947268227679446017663877910308656282722949981689453125,
0.0102798400913763528230493449200366740114986896514892578125,
0.0104702075004759198595394309450057335197925567626953125,
0.01066057490957548169185908903955350979231297969818115234375,
0.01085094231867504525890222311090838047675788402557373046875,
0.01104130972777460535649840522864906233735382556915283203125,
0.01123167713687416545409458734638974419794976711273193359375,
0.01142204454597373075586119739455170929431915283203125,
0.01161241195507328911873390353548529674299061298370361328125,
0.01180277936417285962467094151406854507513344287872314453125,
0.0119931467732724179875436476550021325238049030303955078125,
0.01218351418237198328931025770316409762017428874969482421875,
0.0123738815914715451216299157977118738926947116851806640625,
0.01256424900057110695394957389225965016521513462066650390625,
0.01275461640967066011265185210277195437811315059661865234375,
0.0129449838187702288838654141045481082983314990997314453125,
0.01313535122786978724673812024548169574700295925140380859375,
0.01332571863696935081378125431683656643144786357879638671875,
0.01351608604606891438082438838819143711589276790618896484375,
0.0137064534551684762131440464827392133884131908416748046875,
0.0138968208642680328412932766468657064251601696014404296875,
0.01408718827336760161250683864864186034537851810455322265625,
0.0142775556824671530364856408823470701463520526885986328125,
0.01446792309156672180769920288412322406657040119171142578125,
0.01465829050066628537474233695547809475101530551910400390625,
0.0148486579097658437376150430964116821996867656707763671875,
0.01503902531886540903938165314457364729605615139007568359375,
0.01522939272796497954531869112315689562819898128509521484375,
0.015419760137064530969297493356862105429172515869140625,
0.01561012754616410147523453133544535376131534576416015625,
0.0158004949552636615728307134531860356219112873077392578125,
0.0159908623643632182009799436173125286586582660675048828125,
0.0161812297734627817680230776886673993431031703948974609375,
0.0163715971825623453350662117600222700275480747222900390625,
0.016561964591661905432662393877762951888144016265869140625,
0.016752332000761462060811624041889444924890995025634765625,
0.016942699409861032566748662020472693257033824920654296875,
0.0171330668189605926643448441382133751176297664642333984375,
0.0173234342280601527619410262559540569782257080078125,
0.01751380163715972326787806423453730531036853790283203125,
0.01770416904625927989602729439866379834711551666259765625,
0.017894536455358843463070428470018669031560420989990234375,
0.0180849038644584035606666105877593508921563625335693359375,
0.0182752712735579671277097446591142215766012668609619140625,
0.018465638682657527225305926776854903437197208404541015625,
0.018656006091757097731242964755438151769340038299560546875,
0.018846373500856654359392194919564644806087017059326171875,
0.01903674090995621792643532899091951549053192138671875,
]
primal_true = 0.01303054586957625556729890004358024648004703487744009407127266414409524716045483
@test norm(res3[1] - x_true) ≈ 0 atol = 1e-6
@test res3[3] ≈ primal_true
@test res3[5][end][1] == 101
res4 = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
trajectory=true,
)
res4_adaptive = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=2k,
line_search=FrankWolfe.Adaptive(),
print_iter=k / 10,
verbose=false,
memory_mode=FrankWolfe.OutplaceEmphasis(),
trajectory=true,
)
x_true = [
0.0110488779224248954979881176541312015615403652191162109375,
0.01116382439959395615758364073144548456184566020965576171875,
0.01132266603788188719104113033608882687985897064208984375,
0.01096697959160035373837871475188876502215862274169921875,
0.01099748235218585799832791138896936899982392787933349609375,
0.01090658273640816855465374146660906262695789337158203125,
0.01100728641192584740526871911470152554102241992950439453125,
0.01113317498199122533575344817791119567118585109710693359375,
0.01129240465802835817477056679081215406768023967742919921875,
0.01066971268420941788834799268670394667424261569976806640625,
0.01073806129575670918752106075544361374340951442718505859375,
0.01081623406552431089500121430546641931869089603424072265625,
0.01090669919495564944844634425180629477836191654205322265625,
0.011012761038243910893807964157531387172639369964599609375,
0.011138933094013821201162528495842707343399524688720703125,
0.01129152502908182219287791525630382238887250423431396484375,
0.0106825195127519152749062669727209140546619892120361328125,
0.01075709593593467301719801554327204939909279346466064453125,
0.010841556533814002138971233080155798234045505523681640625,
0.0109381334615336230087212499029192258603870868682861328125,
0.0110670496344356487916638087654064293019473552703857421875,
0.0113528003501498948868420058033734676428139209747314453125,
0.010755333351140705655524243411491625010967254638671875,
0.01048383730090962639991403193562291562557220458984375,
0.01067948351180760153955606739373251912184059619903564453125,
0.01090231617566354838100295410185935907065868377685546875,
0.011158644863763077237361898141898564063012599945068359375,
0.01145699293377413878480819420246916706673800945281982421875,
0.0101981244628182483868972241225492325611412525177001953125,
0.01036021643924461659025393345245902310125529766082763671875,
0.01054198990165635708982083684759345487691462039947509765625,
0.01074709040997723179244882629745916347019374370574951171875,
0.010980253194607388078640752837600302882492542266845703125,
0.01124773117307073695692043457938780193217098712921142578125,
0.01155792943935683714240525432614958845078945159912109375,
0.0102594043125243845893113103784344275481998920440673828125,
0.01043029476421276045827735146076520322822034358978271484375,
0.0106219729796506283381329893700240063481032848358154296875,
0.0108381932769191467735847567155360593460500240325927734375,
0.01108380957646447860509564264930304489098489284515380859375,
0.01136520571619974682986420333463684073649346828460693359375,
0.01015188403354872447026391313329440890811383724212646484375,
0.01031140103979160359271016744742155424319207668304443359375,
0.01048962535578343464870432200086725060828030109405517578125,
0.01068961614661836749540224644761110539548099040985107421875,
0.0109152507282073325811655450934267719276249408721923828125,
0.01117152676702971858535562432734877802431583404541015625,
0.01146500004615019947806775491017106105573475360870361328125,
0.0102103010985286381251402332281941198743879795074462890625,
0.0103773954918663681434853884866242879070341587066650390625,
0.0105642139757310508929588621640505152754485607147216796875,
0.010773965466789041378614655286583001725375652313232421875,
0.01101070848304721259969252145083373761735856533050537109375,
0.01127966475382357995627113922409989754669368267059326171875,
0.01010692369146876622154618274862514226697385311126708984375,
0.0102628472748964548466599211451466544531285762786865234375,
0.0104367298381483307456729647810789174400269985198974609375,
0.0106312766291480863267704393138046725653111934661865234375,
0.01084984936168993142902028381513446220196783542633056640625,
0.01109669576874410847067142782407245249487459659576416015625,
0.0113772771187743877707720940861690905876457691192626953125,
0.01016309273690228949516001222264094394631683826446533203125,
0.01032593705535572552178802396838364074937999248504638671875,
0.01050767080610974339716090497631739708594977855682373046875,
0.010711151044073143057122621257803984917700290679931640625,
0.010939927274482348640294304686904069967567920684814453125,
0.011198484026182613237931917637979495339095592498779296875,
0.01006344361601584948273657715844819904305040836334228515625,
0.0102154242798425699823017254175283596850931644439697265625,
0.0103847197150773624951813900452179950661957263946533203125,
0.0105737916639839467369821335296364850364625453948974609375,
0.01078565122675433952947887661366621614433825016021728515625,
0.01102404130098686395322626907500307424925267696380615234375,
0.01129369392894255010040271969273817376233637332916259765625,
0.01011769773639966361888919976763645536266267299652099609375,
0.0102761657076108035846484511921516968868672847747802734375,
0.0104528084497103428140984959782144869677722454071044921875,
0.0106502317386623530925948699632499483413994312286376953125,
0.0108716260264075381680726195554598234593868255615234375,
0.01112096145948445434503693007854963070712983608245849609375,
0.0120102566865593306244530680260140798054635524749755859375,
0.00932655184389477413808844374898399109952151775360107421875,
0.00826079786559208613383464836488201399333775043487548828125,
0.00916835118748905719687769533265964128077030181884765625,
0.0101832309647222028770041646339450380764901638031005859375,
0.01132195055394567655138171602402508142404258251190185546875,
0.012605048988675919552360227271492476575076580047607421875,
0.00972619723519543323553282476723325089551508426666259765625,
0.0086199687394420236585812489238378475420176982879638671875,
0.0095702153731971155437019405098908464424312114715576171875,
0.0106337321108964551197306747098991763778030872344970703125,
0.01182819416640477905300343763883574865758419036865234375,
0.01317564671500810573323558827496526646427810192108154296875,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
]
primal_true = 0.01079492075856676147135835760962987221028689269130597783892595739691365095379305
@test norm(res4[1] - x_true) ≈ 0 atol = 1e-6
@test res4[3] ≈ primal_true
@test res4[5][end][1] == 101
@test res4_adaptive[3] ≈ 0.01 atol=1e-8
@test res4_adaptive[5][end][1] == 138
end
@testset "Approximate Caratheodory with random initialization" begin
rhs = 1
k = 1e5
x_true = [
61512951376323730454002197150348389314089326897787615721998692413353959632437 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
7278301191941549131183323094243942700957644187929251522094354780914218275643 //
7410693711188236507108543040556026102609279018600996098525285376506440296955904,
8366562124555104321121369841697389597845181508166497753247502851926662059563 //
231584178474632390847141970017375815706539969331281128078915168015826259279872,
85023391065000333202828293111143357401972379805025875286177370028514589002563 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
65161147193679930666908924856262469104197138809185702944157386640936864997051 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
79601478169795915975697070307050727165420854919928218988885008389058048219799 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
67837373726039687662074349377195592477915195880054271380448921303995127196787 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
55169871312251590938351075012017608231499182261935245722772561815939463686945 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
86815771044534708965244863268893818174646630872044525249352735709981389751563 //
29642774844752946028434172162224104410437116074403984394101141506025761187823616,
72336771117105959301574221890003216380657564844338588751171518976178113048017 //
29642774844752946028434172162224104410437116074403984394101141506025761187823616,
19890931658710480666057076719356895452123545713808612893617662915732470931561 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
79585978057301384008717145909924897970180606286778393928727017924984613374659 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
113965904146211811471977184949419222372334011462703157205004739574650127142033 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
5428354262203226529922598481638522646897396408804020092482524536075502397089 //
926336713898529563388567880069503262826159877325124512315660672063305037119488,
34827625827775960484301801523292094477572109942336300722774749588002270047107 //
926336713898529563388567880069503262826159877325124512315660672063305037119488,
8144733136987354412249131885422478920455820770248694226860937021089948464221 //
926336713898529563388567880069503262826159877325124512315660672063305037119488,
83223495385376576134214902972508569795914027222867150904993148656647549582643 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
54297750348315411085069411691276033515094776339188270147174153874826550949759 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
37999445234583642959973667475688948272912144623017138000156880088920795412827 //
926336713898529563388567880069503262826159877325124512315660672063305037119488,
79609315854867434707411488589752461150308986825456950218827676254431104225223 //
14821387422376473014217086081112052205218558037201992197050570753012880593911808,
36228520792880844351408349957314092789406418697994688604833502039464381047593 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
87747074626700853575232381986258310602806824140384221969315398151119893566027 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
14247237619794261330995555194505323439550547179850901735114007176618394961353 //
463168356949264781694283940034751631413079938662562256157830336031652518559744,
14248684606965137684515955910711963166771474351946426521187714925472414576673 //
463168356949264781694283940034751631413079938662562256157830336031652518559744,
84150822879115430935288141198806087582607671818743223481767144916744174202711 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
80512422222849887485621734147521502765322572979265885473937061004907501946415 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
13575133430342896240925710532529889229904841799812827659124544788029451500505 //
926336713898529563388567880069503262826159877325124512315660672063305037119488,
85930842192362005344537760883863364225750024310074067572323399741581216569741 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
65021782163379251030074430456678178405938486301538530120830779975596245752847 //
14821387422376473014217086081112052205218558037201992197050570753012880593911808,
40701251232106608633770622134695258535560875020915747471858891813546395472325 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
39798030372341094444100232335522337649867082740716224935897408719862574204305 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
84121644147995396625591066877556253744715337783486488304563392406881190793051 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
33922055663316267391672695885159354882451875454551025177383028349114163057371 //
926336713898529563388567880069503262826159877325124512315660672063305037119488,
15831205501799787359855727259669406012682835451292628159505016130571475753067 //
463168356949264781694283940034751631413079938662562256157830336031652518559744,
97667231102575253732993923620041238774510608407541976676513500282167400753847 //
7410693711188236507108543040556026102609279018600996098525285376506440296955904,
61506200807405941080369582838580555432120089840841225703478555148085366801593 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
69663077113345636859399373513055005486354570697173148668421658523479885425043 //
1852673427797059126777135760139006525652319754650249024631321344126610074238976,
101464980607353895107673290372367186084458336535036844511537017865818241482095 //
29642774844752946028434172162224104410437116074403984394101141506025761187823616,
30762334036323628501430433726571171454828575613210821709890893791022869772097 //
3705346855594118253554271520278013051304639509300498049262642688253220148477952,
29403498868980333524589803906472036743111538604830514310901745746061273020257 //
926336713898529563388567880069503262826159877325124512315660672063305037119488,
]
primal_true =
9.827847816235913956551323164596263945321701473649212104977642156975401442102586e-10
xp = [
17 // 1024,
1 // 1024,
37 // 1024,
47 // 1024,
9 // 512,
11 // 256,
75 // 2048,
61 // 2048,
3 // 1024,
5 // 2048,
11 // 2048,
11 // 512,
63 // 2048,
3 // 512,
77 // 2048,
9 // 1024,
23 // 1024,
15 // 512,
21 // 512,
11 // 2048,
5 // 512,
97 // 2048,
63 // 2048,
63 // 2048,
93 // 2048,
89 // 2048,
15 // 1024,
95 // 2048,
9 // 2048,
45 // 2048,
11 // 512,
93 // 2048,
75 // 2048,
35 // 1024,
27 // 2048,
17 // 512,
77 // 2048,
7 // 2048,
17 // 2048,
65 // 2048,
]
direction = [
0.00928107242432663,
0.3194042202333671,
0.7613490224961625,
0.9331502775657023,
0.5058966756232495,
0.7718148164937879,
0.3923111977240855,
0.12491790837874406,
0.8485975494086246,
0.453457809041527,
0.43297176382458114,
0.6629759429794072,
0.8986003842140354,
0.6074039179253773,
0.9114822007027404,
0.04278632498941526,
0.352674631558033,
0.7886492242572878,
0.7952842710030733,
0.7874206770511923,
0.7726147629233262,
0.6012149427173692,
0.13299869717521284,
0.49058432205062985,
0.57373575784723,
0.9237295811565405,
0.13315214983763268,
0.3558682954823691,
0.8655648010180531,
0.2246697359783949,
0.5047341378190603,
0.34094108472913265,
0.11227329675627062,
0.27474436461569807,
0.1803131027661613,
0.5219938641083894,
0.6233658038612543,
0.2217260674856315,
0.5254499622424393,
0.14597502257203032,
]
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
lmo = FrankWolfe.ProbabilitySimplexOracle{Rational{BigInt}}(rhs)
x0 = FrankWolfe.compute_extreme_point(lmo, direction)
res5 = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Agnostic(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
trajectory=true,
)
@test norm(res5[1] - x_true) ≈ 0 atol = 1e-6
@test res5[3] ≈ primal_true
@test res5[5][end][1] == 100001
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 16188 | using FrankWolfe
using Test
using LinearAlgebra
const xp = [
0.2221194121408555,
0.37070712502470504,
0.024120713402762894,
0.23878317833696794,
0.9774658250856014,
0.9328848703961752,
0.19666437903254597,
0.3108438697934143,
0.8611370560284857,
0.5638902027565588,
0.6717542256037482,
0.37500671876420233,
0.43229958494828336,
0.4455524748732561,
0.23223904983081323,
0.8786466197670292,
0.5909835272840192,
0.972946051414218,
0.8295833654216703,
0.12165838006949647,
0.5573162248498043,
0.7783217768142197,
0.9405585096577254,
0.4096010036741623,
0.4146694259495587,
0.12202417615334182,
0.12416203446866858,
0.3135396651797776,
0.8463925650597949,
0.5435139172669606,
0.05977604793386093,
0.9179329261313978,
0.9584333638309193,
0.288632342896219,
0.8445244137513961,
0.7174538816882624,
0.20921745715914342,
0.8558382048640315,
0.32234336062015523,
0.32349875021987073,
0.38283519134249555,
0.33281059318207173,
0.9068883983548414,
0.08810942376469555,
0.4540478820261079,
0.8286156745759701,
0.3251714302397716,
0.6926837792258961,
0.16918531873053577,
0.3045901922130101,
0.6854793931009404,
0.06651125212604247,
0.11380352462639065,
0.08508026574096728,
0.9547766463258776,
0.1861768772348652,
0.5484894320605861,
0.24822097257281062,
0.3889425215408887,
0.49747336643471984,
0.026478564673962035,
0.2754275925598161,
0.5969678463343207,
0.8896103799119639,
0.1108714508332197,
0.9283688295031338,
0.9713472351114413,
0.891466118006637,
0.96634040453533,
0.00355941854573949,
0.7867279585604435,
0.9510563391713888,
0.0692488661882199,
0.49865755273497236,
0.11863122104246815,
0.1710296777218261,
0.6363240295890795,
0.13113427653058585,
0.09117615810736701,
0.43340842523155443,
0.685958886328903,
0.12577668795016073,
0.26730497196368863,
0.9249813878356242,
0.20938064379327703,
0.84121853886278,
0.19283763945286048,
0.8795998946120226,
0.9245987481505632,
0.41859788484460025,
0.6468433655631147,
0.2614312743910776,
0.9109750609820051,
0.38773597147345606,
0.17899781432954076,
0.3444279212619652,
0.3161112859016656,
0.9212820835055795,
0.7501699548719438,
0.6951058583384379,
]
@testset "Away-Step CG" begin
# n = Int(1e1)
n = Int(1e2)
k = Int(1e4)
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
lmo = FrankWolfe.KSparseLMO(40, 1.0)
x0 = FrankWolfe.compute_extreme_point(lmo, zeros(n))
x_true = [
0.12350331520527039,
0.2720911600489062,
0.0,
0.140167169125791,
0.8788497081329242,
0.8342685990885751,
0.09804837088605657,
0.212227647433356,
0.7625208605543947,
0.46527409557434884,
0.5731382333696704,
0.2763905827604689,
0.3336837864396474,
0.3469363114955107,
0.1336290781022528,
0.780030185474837,
0.49236737077583526,
0.8743244783341335,
0.730967269701777,
0.02304965724670187,
0.45870005788163015,
0.6797054213208934,
0.8419422209838555,
0.3109848428453597,
0.3160534364494893,
0.023408368324288265,
0.02554590234308165,
0.214923591871615,
0.7477761809848499,
0.44489775388921676,
0.0,
0.8193163927062596,
0.859817175743167,
0.19001619361014938,
0.7459080255491606,
0.6188376723372043,
0.11060131843677788,
0.7572219825793343,
0.22372714201350155,
0.2248826346064741,
0.2842189977123998,
0.234194441570774,
0.8082719384545783,
0.0,
0.35543171903388127,
0.7299992900251845,
0.22655532373895734,
0.5940675939547932,
0.07056937013046714,
0.20597419863272642,
0.586863240643373,
0.0,
0.015194189630647736,
0.0,
0.8561604566330895,
0.08756099706437867,
0.44987303972084425,
0.1496049653804154,
0.2903263916627384,
0.39885743548767694,
0.0,
0.17681118234902266,
0.49835126912686845,
0.7909941352550856,
0.012262316522948954,
0.829752604845485,
0.8727309453679273,
0.7928498840116429,
0.8677240510599421,
0.0,
0.6881116971780795,
0.8524400345642169,
0.0,
0.4000416430046448,
0.02001508476237797,
0.07241364329590354,
0.5377080641185094,
0.03252490896928947,
0.0,
0.334792268924615,
0.5873428846300117,
0.02716712761647248,
0.16868859862650792,
0.8263648962248804,
0.11076441441975882,
0.7426025346638739,
0.09422137265867661,
0.7809836031959027,
0.8259825071643098,
0.31998162124628227,
0.5482270985450096,
0.16281512986932242,
0.8123588544851766,
0.28911985191570744,
0.08038187268675007,
0.24581172390971173,
0.2174952886170703,
0.8226657834983702,
0.6515537033215051,
0.5964896156444087,
]
primal_true = 0.9223845604218518
niters = 1909
res1 = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=100.0),
print_iter=k / 10,
epsilon=1e-5,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
away_steps=true,
trajectory=true,
)
res1_adaptive = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Adaptive(L_est=100.0),
print_iter=k / 10,
epsilon=1e-5,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
away_steps=true,
trajectory=true,
)
@test norm(res1[1] - x_true) ≈ 0 atol = 1e-5
@test res1[3] ≈ primal_true
@test res1[5][end][1] <= niters
@test res1_adaptive[3] ≈ primal_true
x_true2 = [
0.12350325628679909,
0.27209922793666613,
0.0,
0.1401669208593975,
0.8788494948178499,
0.8342685623927103,
0.09804796463636488,
0.2122275998207822,
0.7625208834020012,
0.4652738908441709,
0.5731379884683532,
0.27639045997386924,
0.3336832995487319,
0.3469361951837413,
0.1336229980083404,
0.780030397630848,
0.49236727599406177,
0.874329744225315,
0.7309671468077595,
0.023042160241989237,
0.45869985746647546,
0.679705467413878,
0.8419422095529443,
0.31098474678315424,
0.3160531049488661,
0.023415892579793818,
0.025545746462217238,
0.21492339006780664,
0.7477763707338895,
0.4448976738194912,
0.0,
0.8193165394183596,
0.859817070627424,
0.19001602422893987,
0.7459081193869738,
0.6188376817399694,
0.1106012104488174,
0.7572218842338574,
0.22372704506073327,
0.2248824342409964,
0.28421873176658263,
0.2341947720818703,
0.8082721381894483,
0.0,
0.3554316828149227,
0.7299995942545656,
0.22655537502111792,
0.5940675416770479,
0.07056917339550282,
0.205973823076617,
0.5868631102448789,
0.0,
0.015195600977709636,
0.0,
0.8561603595443996,
0.08756893289369261,
0.44987314906166886,
0.14960475522281372,
0.2903262193913907,
0.39885700591829637,
0.0,
0.1768112686682394,
0.4983518341496353,
0.7909940162586777,
0.012255265619101422,
0.8297525700627989,
0.8727310624708051,
0.7928498862034395,
0.8677241994701683,
0.0,
0.6881116863638452,
0.8524400418873481,
0.0,
0.40004132924861774,
0.020014967561619194,
0.07241355411852693,
0.5377079346778642,
0.03251798352195498,
0.0,
0.3347921887674731,
0.5873426243318487,
0.027168981303859988,
0.16868876068051325,
0.8263651638803798,
0.11076450575931521,
0.7426024306918094,
0.09422153728454051,
0.7809837470618066,
0.8259826763067796,
0.31998160902571865,
0.5482271318602744,
0.16281519396942526,
0.8123588180758603,
0.28911953790429545,
0.0803816656438147,
0.24581174746305717,
0.21749506130863475,
0.8226657631621945,
0.6515536470906864,
0.596489706318256,
]
primal_true2 = 0.9223845604496933
niters2 = 3408
res2 = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=100.0, eta=0.95, verbose=false),
print_iter=k / 10,
epsilon=1e-5,
momentum=0.9,
memory_mode=FrankWolfe.OutplaceEmphasis(),
verbose=false,
away_steps=true,
trajectory=true,
)
@test res2[3] ≈ primal_true2 atol = 1e-6
x_true3 = [
0.12350364160905855,
0.2720912507358009,
0.0,
0.14016737894919556,
0.8788498863896176,
0.83426901624493,
0.09804858376590986,
0.21222819898266776,
0.7625211675983882,
0.46527425004082035,
0.573138394455831,
0.27639086842991223,
0.3336836492542,
0.3469367015262871,
0.1336233437062462,
0.7800306483527641,
0.4923676450024285,
0.8743301048502704,
0.7309673888704789,
0.02304260429126816,
0.45870028337813995,
0.6797058236678196,
0.8419424107695108,
0.31098512227015357,
0.3160535988475176,
0.023408358109346508,
0.025546351416447947,
0.214923870144732,
0.7477764202045378,
0.4448980496190519,
0.0,
0.8193168093268758,
0.8598171865270792,
0.19001650514605778,
0.7459084135022188,
0.6188379006111643,
0.11060177634453179,
0.7572222388624699,
0.22372744881962495,
0.22488297766113136,
0.2842196974407023,
0.23419493747178544,
0.8082723871719079,
0.0,
0.3554320385006412,
0.7299997464397213,
0.22655567318872008,
0.5940678549930419,
0.07056943610960685,
0.2059743993650674,
0.5868635475401429,
0.0,
0.0151919890089084,
0.0,
0.8561606585006025,
0.08756108714417242,
0.44987351232451545,
0.1496053567903214,
0.2903267440991662,
0.398857499658823,
0.0,
0.1768118504458742,
0.49835202963825764,
0.790994367452785,
0.012256124565600572,
0.8297528912334032,
0.8727309391686804,
0.7928501038401042,
0.8677244512292245,
0.0,
0.6881120640228882,
0.8524402440686749,
0.0,
0.4000417000030933,
0.0200154362247207,
0.07241395223591116,
0.5377083244045926,
0.03251891157220403,
0.0,
0.3347925120063812,
0.5873426183530177,
0.0271611272960249,
0.1686892300620705,
0.8263653847605529,
0.11076483683657806,
0.7426026880906017,
0.09422332107845836,
0.7809839803090287,
0.825982839429656,
0.3199821281896926,
0.5482274470499936,
0.16281572051063387,
0.8123591550715057,
0.28912016031441284,
0.08038280259301499,
0.24581214317616248,
0.217495515572685,
0.8226662321278636,
0.6515539414710015,
0.5964899915623191,
]
primal_true3 = 0.9223845601906837
niters3 = 337
res3 = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=100.0),
print_iter=k / 10,
epsilon=1e-5,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
away_steps=true,
trajectory=true,
)
@test norm(res3[1] - x_true3) <= 5e-5
@test res3[3] ≈ primal_true3
@test res3[5][end][1] <= 451
x_true4 = [
0.12350364160905855,
0.2720912507358009,
0.0,
0.14016737894919556,
0.8788498863896176,
0.83426901624493,
0.09804858376590986,
0.21222819898266776,
0.7625211675983882,
0.46527425004082035,
0.573138394455831,
0.27639086842991223,
0.3336836492542,
0.3469367015262871,
0.1336233437062462,
0.7800306483527641,
0.4923676450024285,
0.8743301048502704,
0.7309673888704789,
0.02304260429126816,
0.45870028337813995,
0.6797058236678196,
0.8419424107695108,
0.31098512227015357,
0.3160535988475176,
0.023408358109346508,
0.025546351416447947,
0.214923870144732,
0.7477764202045378,
0.4448980496190519,
0.0,
0.8193168093268758,
0.8598171865270792,
0.19001650514605778,
0.7459084135022188,
0.6188379006111643,
0.11060177634453179,
0.7572222388624699,
0.22372744881962495,
0.22488297766113136,
0.2842196974407023,
0.23419493747178544,
0.8082723871719079,
0.0,
0.3554320385006412,
0.7299997464397213,
0.22655567318872008,
0.5940678549930419,
0.07056943610960685,
0.2059743993650674,
0.5868635475401429,
0.0,
0.0151919890089084,
0.0,
0.8561606585006025,
0.08756108714417242,
0.44987351232451545,
0.1496053567903214,
0.2903267440991662,
0.398857499658823,
0.0,
0.1768118504458742,
0.49835202963825764,
0.790994367452785,
0.012256124565600572,
0.8297528912334032,
0.8727309391686804,
0.7928501038401042,
0.8677244512292245,
0.0,
0.6881120640228882,
0.8524402440686749,
0.0,
0.4000417000030933,
0.0200154362247207,
0.07241395223591116,
0.5377083244045926,
0.03251891157220403,
0.0,
0.3347925120063812,
0.5873426183530177,
0.0271611272960249,
0.1686892300620705,
0.8263653847605529,
0.11076483683657806,
0.7426026880906017,
0.09422332107845836,
0.7809839803090287,
0.825982839429656,
0.3199821281896926,
0.5482274470499936,
0.16281572051063387,
0.8123591550715057,
0.28912016031441284,
0.08038280259301499,
0.24581214317616248,
0.217495515572685,
0.8226662321278636,
0.6515539414710015,
0.5964899915623191,
]
primal_true4 = 0.9223845601906837
niters4 = 337
res4 = FrankWolfe.blended_conditional_gradient(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(L_est=100.0),
print_iter=k / 10,
epsilon=1e-5,
momentum=0.9,
memory_mode=FrankWolfe.OutplaceEmphasis(),
verbose=false,
away_steps=true,
trajectory=true,
)
@test norm(res4[1] - x_true4) <= 5e-5
@test res4[3] ≈ primal_true4
@test res4[5][end][1] <= 451
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 153525 | using FrankWolfe
using LinearAlgebra
using Random
using Test
n = Int(1e3)
k = 1000
s = 67
Random.seed!(s)
const xp = [
0.0014225829730746685,
0.00027273617345220023,
0.0004982501651537384,
0.00016781398571202372,
0.0007277581309468943,
0.0002292449202586443,
0.000586282153185683,
0.0001643306060072405,
0.0013573219013060527,
0.0017062956439693735,
0.0018805197883047205,
0.00036600380804269097,
0.0014251818134256385,
0.0016059380694325566,
0.0007985016721114605,
0.0007445625606451596,
0.0016881023473138599,
1.2635475952604431e-5,
0.0005625740951153886,
0.0004956060562970549,
0.0008664562903436179,
0.0004691476042227225,
0.0007407378074266904,
5.8218822022077696e-5,
0.0016668039943773883,
0.001230111678583221,
0.0014207383443248756,
0.00019629812732103628,
0.00023149798720790618,
0.0005457730481090465,
0.0004647273343765338,
0.0016567737337628164,
0.0006045563167841241,
6.79433941935833e-5,
0.0014508076394611818,
0.0009517077724100463,
0.0019777517342556054,
0.0015469323005765387,
0.0018741722738131758,
0.001543216015845832,
0.0014368860199185534,
8.123743519456117e-5,
0.0017304519788969876,
0.0009952125105021016,
0.001435347078363032,
0.0017044076620036219,
0.001370899801864165,
0.0017276689884084628,
0.0017207388360604057,
0.0005881117499865442,
0.0015843186972879391,
0.0002248903229268006,
0.0010789359594175554,
0.0013330122614207032,
0.0004199228230914178,
0.0001663156687595009,
0.0016064302448467124,
0.0006240639188353371,
0.0014750986252874063,
0.0008635840035783843,
0.0005818680243533776,
0.001122065868172068,
0.0015992917244000212,
0.0010582389504527334,
0.0019218317984081924,
0.0004358829777676219,
0.0015350408595329386,
0.0019150762478400594,
0.0011025998295428525,
1.552818560481631e-5,
0.0014681788128353534,
0.00010509940072605435,
0.0013962483523074832,
0.0005197183340729313,
0.0001985541908166003,
0.0018652939837433737,
0.0009494974103657329,
6.553696203023463e-5,
2.1731312863730182e-5,
0.0005872042575536399,
0.0017695830803026993,
0.001543177645476947,
0.0019442830961184038,
0.0002195404124343261,
0.0006762506740697591,
7.178001367589448e-6,
0.0001720387806437584,
0.0018371860762179462,
0.0006645798689715189,
1.5606577851214757e-5,
0.00043116222443045845,
0.001582408136187116,
0.00019166722790704569,
0.0009058144517547876,
9.535138143364876e-5,
0.0002448162608221115,
0.0008105073291824005,
0.00015599543481626288,
0.0014887306605149715,
0.00014239732148511232,
0.0015252030585656015,
0.00048282906401242106,
0.001640868543364915,
0.0009144831653524673,
0.00025350058852607735,
0.001759175429970381,
0.0003180421616147551,
0.00012625190354449787,
0.0012697356819963406,
0.0013558842617387545,
0.001213785617968065,
0.0015971668861470961,
0.0011491769537972049,
0.001752941760416418,
0.00021317496889315207,
0.0002616486794134621,
0.0011650225275642565,
0.0006522880062417026,
0.001979643109370393,
0.0020054541832613495,
0.0003148423515202374,
0.0007566885853996769,
0.0004918472421501449,
0.00031656967827039747,
0.0001918152234768508,
0.0018281654222492318,
0.0011533894999170135,
0.0005738681491066433,
0.0016659749624834204,
0.0013950726445840942,
0.0008431838004008162,
0.0017493945386526715,
0.0010129266531879585,
6.439075581973415e-5,
0.000668572835057624,
0.00044097868297955303,
0.0016334368839821985,
0.00030493326913045237,
0.0005789650694724851,
0.0017477952842328568,
0.00031196535075644156,
0.0019880985071043748,
0.0017476244132139682,
0.0016824754451223664,
0.0012848772893631225,
0.0009006681703641811,
0.0012325359195736816,
0.00196585423034127,
0.0012941244767165057,
0.0019402010039768934,
0.0016387730965204952,
0.00014496440086838826,
0.0013288836222637177,
0.0002792432544553741,
0.00037630513544492373,
0.00010736630005572997,
8.25956341021556e-5,
0.000799257704695363,
0.00032088771390445753,
3.9857898811463734e-5,
0.0015451889767061544,
0.001193403384458047,
0.0004210297422544032,
0.0006864541974307154,
0.0002433322075956111,
0.00031918970798436384,
0.0005711111051890588,
0.0016054760747165858,
0.0018515936022881752,
0.000490184453972966,
0.0004600333891919782,
1.2671542513416094e-5,
0.00037579867373211626,
0.000629804522218123,
0.00011705488279009928,
0.00041294868227935335,
0.00024277385968770864,
0.0013710095981204651,
0.0013364057795948441,
0.001261630491778122,
0.0019927696517590128,
0.0005029442221333206,
0.0012150950276685485,
0.0006972288288707543,
0.0002651860052693955,
0.0007848344961727201,
0.0012398392549124518,
0.001816756340931745,
0.0018212477275619064,
0.001410350863550584,
0.0013910443194918112,
0.0012804278072098797,
0.00033675242457422225,
0.0016400211737636066,
3.683761696182542e-5,
0.0011426299633260965,
0.0014251565811630661,
0.0011625295007978245,
0.00016334692345112194,
0.0015753511038089905,
9.498766765719075e-5,
0.0003688648658667572,
0.0004428771810992299,
0.0004335421163525156,
0.00014669168347603348,
0.000960727656501515,
0.0017388352025956846,
0.0012199470010173447,
0.00047386021397838866,
0.00016289575380331686,
0.0008063383317527575,
0.0017790777172098354,
0.0006471525490103279,
0.00027338176849918465,
0.0016323523128177432,
0.0014388213557773152,
0.0015858013996187335,
2.5328684352336216e-5,
0.00013426485852941858,
0.0013789009950120892,
0.0016098933709620643,
0.0015334608699318485,
0.0001504873614723311,
0.0003137788469648133,
0.0013781531350813402,
0.00043375213097234633,
0.0009784180782994377,
6.389319176519076e-5,
0.0017343206167148779,
0.0006450202539701317,
0.0008304456683779456,
0.0015885185376653043,
0.0009978498817924482,
0.0017497325552822012,
0.0003193194820436,
0.0019816755896353505,
0.0008959836044206313,
0.0014934780674162446,
0.00010829940298036558,
0.0017701658144083552,
0.0007247032532871117,
0.001002068880650653,
0.0005018434395144133,
9.577497058882493e-6,
0.0014349312885360813,
0.0003996918246625879,
0.00020479530791282435,
0.0015498412290078337,
0.0008047122969117834,
0.001437993761595762,
0.0008314269473453154,
0.0018494703491537538,
5.538929067719523e-5,
0.000573001134440481,
0.0004286477637823486,
0.0009391080324561438,
0.0019890285018640264,
0.0017895996397510933,
0.0005983484560665042,
0.0011878533084640373,
0.00020393940255329272,
0.0012864452667014036,
0.00056282486086491,
0.001386281514517723,
0.0018025535733172135,
0.0003738041486706437,
0.000449009638032906,
0.000779117017002669,
0.00045773656732915044,
0.0012377335924829548,
0.0010404995332000339,
0.001364187638683425,
0.0019502557025712444,
0.0019199985857245821,
0.0017927791837919922,
0.000571685295613876,
0.00016766206957098014,
0.0008070420790599257,
0.00032201232575932933,
0.0011636743053765463,
0.0016257189566375385,
0.0005844488043855814,
7.617781434075272e-5,
0.0007973292442984844,
0.00183020003447009,
0.001913506929951082,
0.0008501916628805596,
0.0018565277146927934,
0.0012163484149613775,
0.0016013806467931433,
0.0013594317738963907,
0.00046933399836569307,
0.0015519769602222277,
0.0005190206730682707,
0.0017951492920578209,
0.0003528092133331824,
0.0015695041100253799,
0.0014172341002727077,
0.0006113649234644023,
8.246148060835662e-5,
0.0015216245717466549,
0.00014082732247942627,
0.0004888271400282999,
0.0003620412019191197,
0.00023552809052613247,
0.0010522476332758247,
0.0011330280716784751,
0.0011919004394500186,
0.0001999239184882932,
0.0012578579682001442,
6.81560097974536e-5,
5.620784619652595e-5,
0.0015560949134335593,
0.0006731689968200158,
0.0008932039797485442,
0.000872702343437884,
0.0016405810215582685,
0.00035429434975047,
0.0003187697915258196,
0.0015016443445056923,
6.64042829665131e-5,
0.0008912890953257125,
0.0019966693130079533,
0.00045847806261945515,
0.001919652492603607,
0.00025326054797598956,
0.0013547056756098796,
0.0014396998863221834,
0.001486047707058099,
0.00044725593678386947,
0.001314413433300196,
0.0003646375717519197,
0.0003645431490166326,
0.0007737989810852643,
3.7403736134581684e-5,
0.00036235643630038025,
0.0010392698105147625,
0.00044576427620295826,
0.001658335974052411,
0.0018412151588818907,
0.0016897878513190163,
0.001138478375397692,
0.0008425102380056849,
0.0004845750437687568,
0.0013109477143974518,
0.0006680411125982277,
0.00026480645283318585,
0.0005793940986069932,
0.002007718594989109,
0.00025654655139448353,
0.00048808242636074703,
0.00193870459617474,
0.0012624318319217885,
0.00012610086423128045,
0.0004822664243645331,
0.0006995910783991009,
0.0018343834533313178,
0.00035618970224208835,
0.0015795229721178893,
0.00188936640712125,
0.0019625338448100373,
0.00042054385669217505,
0.0010034908904701797,
0.0016390143925221687,
0.001837700390234282,
0.0012565153576574043,
0.00022105274287425566,
0.0012662897590817335,
0.0009447584260034436,
0.0015937105558610845,
0.000995052949640822,
0.001933792333852781,
0.0012952633194697476,
0.0019186107813653208,
0.0005639190586868324,
0.0008654626847821067,
0.0001473047606306817,
0.0006739036440435369,
0.0011341036866187538,
0.0003067213579947775,
0.0015342332763611482,
0.0019925656641059746,
0.0009773026202449242,
0.001549236154749225,
0.001847918975796324,
0.0014108561209018181,
0.0016459813879631316,
0.0008047156537357154,
0.0017241046391939091,
0.00045557876981122745,
0.0013508718480724747,
0.0015656119635699386,
0.0007124724096625895,
0.0004041937937868055,
0.0009747104174367392,
0.0009805195733719023,
0.0015187054531335855,
0.0005213653296996159,
0.00027910099742593385,
0.00034137762315484193,
0.0009675376320895608,
0.0014787231435549062,
0.0016581717177690176,
3.710136260687701e-5,
0.0015476082870335757,
0.0001464069426865392,
8.080987325999988e-5,
0.0015552962238936023,
0.0018178149777897596,
0.001327106716333705,
0.0005714134281097281,
0.0005346464119960912,
0.0018858202831895242,
0.0013436309434906762,
0.0008328413960901492,
0.0009882817570009282,
0.0010543682618844167,
0.0011976491796568604,
0.0012467679722571376,
0.0010398607128184795,
0.001361608822661806,
0.0013867854704599026,
0.0010421561195515735,
0.0003830833383726635,
0.0012626049152821735,
0.0016019626189675779,
0.0019195943870069867,
0.001179710441692755,
0.0017246953969155686,
0.001059355549820652,
8.871825201101645e-5,
0.0017516580061682713,
0.001028716271075169,
0.0005981716482185058,
0.0010555882488528455,
0.0002633587507720345,
0.0011528277493200968,
0.0010726325205459252,
0.0005611877948603352,
0.00140845854300012,
0.0010461453626100178,
0.0019993923525821137,
0.001397195603117328,
0.0013930685078893433,
0.0019019705238663828,
0.00046372564216749985,
0.0019783187056816743,
2.5392703094837675e-5,
0.0019063486066126778,
2.3252116283804123e-5,
0.0009103915283001037,
0.0012206501588948252,
0.0017075537678668412,
0.0004972857490398049,
0.000526706559493638,
0.001009423841767406,
0.0018142128081296233,
0.001115595515528934,
0.0010736326239073827,
0.001527035886119384,
0.0014332001238930188,
0.0019578191863363348,
0.0006303434582234104,
0.00033172768771474564,
0.001797553659067984,
0.0007884331410750877,
0.0019432162528753788,
0.0006182625655236285,
0.00013000224000990954,
0.001242434370402485,
0.0019522719977704884,
0.0013528893312904893,
0.0009195345843056242,
0.0012686033338687242,
0.001231448771365785,
0.0020121041512915785,
0.00015331242640691763,
0.0009504315115270128,
0.0016553550309291304,
0.0004987751828173625,
1.8061519251257906e-5,
0.0006186728449469149,
0.0005920521893881824,
0.001908220870448575,
0.0002205036623445366,
0.0018846492370764411,
0.0016494410451628717,
0.0015854863842742677,
0.00024155985856704875,
0.00013159895671226933,
0.0005767677259911404,
0.0004553228545598211,
0.0007748676020906012,
0.0013286214455836079,
0.001091278879553795,
0.0002858707916060778,
0.0015346429912678266,
0.001841942711447502,
0.0012287136844843117,
0.0017539494532146488,
0.0007762032512225517,
0.0018104781769599939,
0.000975640977123887,
0.00010748120413993646,
0.000849691832052351,
0.00014029856335695293,
0.0011047690754086258,
0.0015142689124562267,
0.00030226865531931776,
0.0011549217637641255,
6.691355679364822e-5,
0.0008031842791010631,
0.0014565305921752628,
0.0008335947465890271,
0.00020759794336028733,
0.001458188635333983,
0.0005148620989943951,
0.0005635426425700353,
0.00042604790335893413,
0.0013069072680508493,
0.00035994797345680665,
0.001356042565331949,
0.0014572228754304445,
0.00032897063904729424,
0.0009189062781903981,
0.0019203413143139268,
0.001286431247398028,
0.0012462345067831822,
0.0018189975286370629,
0.001985475189142025,
7.712852992397094e-5,
0.001526665411699278,
0.001059854604294616,
0.0015489054821369603,
0.000918017971282879,
0.00037606271088591457,
0.001719783473476843,
0.0006928424587896554,
0.0010718750030958464,
0.0007047606940762046,
0.0002853923986268533,
0.0005109056253858266,
0.0020141294696619156,
0.0015512092488933434,
0.0011191843459915781,
0.001231168426393991,
0.001740236132536594,
0.0008078549240013852,
0.0008781330722390806,
0.001800076170448688,
0.0007401333104629241,
0.0015147410396491917,
0.001285580617951326,
0.0015782105962813086,
0.0013863636861261646,
0.0014540986179455684,
0.0012609685897404031,
0.0003174541527607249,
0.00046581161135928427,
0.001131094146732926,
0.0014473128882542638,
0.0005915013930146079,
0.0006948530868565294,
0.0002852502552601266,
0.0007283789563952781,
2.655043569839603e-5,
0.0006445866385715326,
0.0003285745001755108,
0.0001255192471324481,
0.0011179188090113304,
0.0009587672649033661,
0.0016780325639011303,
4.575158458010835e-5,
0.0014225283747152954,
0.00039625237834410077,
0.0006524293521695967,
0.0008939871382032231,
0.0007728206274946616,
0.0012276422872195894,
0.0003379720555377532,
0.0010361792114243,
0.000992123354623973,
0.0016742618749752145,
0.001141895140069696,
0.0011254883718693133,
0.0011796080992514286,
0.001687513988079289,
0.0008345610876173094,
0.0014612737137882274,
0.0006579103193452829,
0.0017453970148688287,
0.0008591074494377854,
0.001699583736033031,
0.0010509353330690689,
0.0003355206879655129,
0.0017483971228195708,
0.0006776495275691602,
0.0016892321334132094,
0.0015432150515412323,
0.001978625944342522,
0.0007472892897239079,
0.0016030467005865696,
0.0007048388586598108,
0.0017167153458345647,
0.0003797434941319426,
0.0007207856531035437,
0.0017245936757519014,
0.000872230007084668,
0.0005945354017790036,
0.001928672314445635,
0.0012940446479220156,
0.0005992857387460298,
0.00025901812348612846,
0.0014556092901899212,
0.001119789808402566,
0.0006903324505245297,
0.0009907848948431377,
0.0008028236812708298,
0.0002804432825771429,
0.0018508864193117912,
0.0009063591051592336,
0.0007300042312496485,
0.0013136149497010557,
0.0013435237754819338,
0.0002869366570851323,
0.0014957120264071004,
0.00113224169021684,
0.0007084865892753494,
0.0010027418411637191,
0.0013999186550814606,
0.002018370494453206,
0.00035787464434598114,
0.0015732415271333274,
0.0013346760850029228,
5.396256554262455e-5,
0.0019500249869953174,
0.0003183614245684218,
0.0018499414684380881,
0.00022451032507613667,
0.0006256693596330921,
0.001892534391138038,
0.0008323693672608353,
0.0018494619350907283,
0.0005528073762110686,
0.0013287922964342344,
0.0008518480747300117,
0.0015655089940693795,
0.0014250890095806486,
0.0017836921659680886,
7.399501652438056e-5,
0.0012244377536486464,
0.001928668797875879,
0.000368231100283004,
0.0010479702852958044,
0.0007664304036454839,
0.001277055835293943,
0.0014612319867427642,
0.001721978176243194,
0.0013531995455601954,
0.000390416081387736,
0.0011340566351650265,
0.00026464997452869135,
0.0001582626699650248,
0.0009384294915254233,
0.0011552652956635142,
0.0006697931115025893,
0.0016512784115313536,
0.0016720761294911188,
0.00013004175793061926,
0.000604732874723968,
0.001946368063850652,
0.0014097141398374694,
0.0005939033734966149,
0.0003463284530779445,
0.0019092870029996125,
0.0014981523044342224,
0.0013033405661748217,
0.0013615477093145017,
0.0006815375463533257,
0.0017006268278526202,
0.0010138000051263505,
0.0013065164623536842,
0.0013703925262707967,
0.0012401228391997524,
0.0018888139358684802,
0.0005517860761207222,
0.0007704313408891517,
0.0015646785272202589,
0.0017288904895688996,
0.0009074479771028894,
0.00032489270218414863,
0.00019230637647188353,
0.001973470578763725,
0.001010799972431649,
0.0007379351281253648,
0.0003613157489228872,
0.0011335961311765255,
0.001614070790713692,
0.0007282297710248562,
0.0017996318677530117,
0.0015951867070882707,
0.001715427695039696,
0.0017561474105838451,
0.0017910129122431753,
0.0007325282043603991,
0.001551107393933763,
0.00045841701692327243,
2.5432708172976657e-5,
0.0013207136799443765,
0.0016596925425870937,
0.0009271256453301118,
0.0010807490771064922,
0.0019088534451276032,
0.0019282809276060522,
0.0014683232457560235,
0.0017977305269067246,
0.00013036911061194633,
0.0011219297862102749,
0.0017913484246202317,
0.0015638342087054946,
0.0003956537566486,
0.0009333039080981982,
0.0005055040877443921,
0.001450178900724977,
0.0014549290318311401,
0.0010803486360573752,
0.001131300941630895,
0.0006647576382844433,
0.0017128619319465629,
0.0009361701316409294,
0.0013879660212940937,
0.0005926049524011536,
0.000628458307112509,
0.0014149537178390788,
0.0007730954536801809,
0.0002755105487138394,
0.001061549045341235,
0.0005827754141220098,
0.0003866537860650106,
0.001333912285497736,
0.0011601265781305728,
0.0010522942749647034,
0.0016876664626944689,
5.855498155123065e-5,
0.0014131853547619515,
0.0002457439825020026,
0.0016884114401086337,
0.0009296867082127962,
0.001045151491409887,
0.0009819450134137563,
0.0005856080329713324,
0.0004090782892621781,
0.0016377108410346331,
0.001123698337585406,
0.001220982598857711,
0.0019562165605960915,
0.0018292076668669308,
0.0010294598634595488,
0.0013478339105567724,
0.0017603706991018721,
0.0014371728102072962,
0.0012235015928238255,
0.0007213793198109632,
0.0020148414318788923,
9.810411476098035e-5,
0.0018584553374505022,
0.0007844749573715261,
0.0005994353591995659,
0.0010270968892109186,
0.0009371180219366003,
0.0007996457466250777,
0.0019957537203612046,
0.0018763523198881617,
0.0011040638229239165,
0.0009800891664213855,
0.0007691398549665108,
0.0006858343026304385,
0.0007589891322079315,
0.0009280235119971932,
0.0004285293666738591,
0.0014982170522007518,
0.0007432184718891272,
0.0001851659446321819,
0.0002326778296392575,
0.0011666249787194542,
2.2665926138682885e-5,
0.0019071669784413395,
0.00037418643557223706,
0.0002015091579607481,
0.0011304088641328532,
0.00046052641581946214,
0.0012023781005911101,
0.001681033734290235,
0.001328953625901482,
0.00038571690456725956,
0.0011586788304359969,
0.0019890162693459636,
0.001929094576633232,
0.00040016043956587566,
0.0019096902755350211,
0.0007593408436130094,
0.0014703115807820604,
0.001515240424575666,
0.0004992136534917434,
0.0007682493960219643,
0.00021590614816095814,
0.0005469991138807453,
0.00011693160303371259,
0.00019989032800547357,
0.0005446715593595313,
8.934944637443384e-5,
0.0013333510572576721,
0.0005332103411317778,
0.0008368455512728243,
0.000962194187018558,
0.00026451279436036216,
0.0010716772783333892,
0.001878756357890447,
0.0002928341676673364,
0.000814312173401349,
0.0005982950648058293,
0.0014569414244273145,
0.0010959326329531,
0.0007470813365541071,
0.0007827603056285682,
0.0004991047238701802,
0.0013750008301846584,
3.925615317768748e-5,
0.0019024015811104642,
0.0008353160412387871,
0.0006211049579554875,
0.0012379690299341077,
0.001278307658978047,
0.0015145648367387628,
0.0007959692144559928,
0.0007757628179737477,
0.0016694548150350346,
0.00024788452482422344,
0.0018742188199002477,
0.00014317920897765214,
0.0011185483576795741,
0.001709040501803795,
0.0014204240339547012,
0.0009239312620334554,
0.0014475749271278295,
0.0004330816024704612,
0.0007101789642348186,
0.0013792399717161953,
0.00159407146741197,
0.0006648787423760073,
0.0013288432169835278,
0.00031868692691503766,
0.001422653739648178,
0.0019663008282803664,
0.0007250562672805323,
0.0011894551256465369,
0.0011957698204556125,
0.00044245981387134724,
0.0004945024320793509,
0.0017749446039923675,
0.0012083916275163107,
0.00016764046975264828,
0.0005541379211860165,
1.6463204721307958e-5,
0.0016218015835627211,
0.00031177606699018645,
0.0016146404188655975,
0.0009111375782937904,
3.7604554709354944e-6,
0.00015122991437470473,
0.00043441581531724076,
0.0013974610007264057,
0.0018782025058311808,
9.200578691560263e-6,
0.00011266403727269566,
0.0010396732327238446,
0.0009695938910306256,
0.001338315016532539,
0.0002651101500308568,
0.0011537172263599185,
0.0004679810165320436,
0.0007590249506698967,
0.00159604086805764,
0.00021563499933159122,
0.0004603270397485177,
0.001450495693971434,
0.0017487778289521565,
0.0007876988515836151,
0.0019703176780635997,
0.0018971099754136829,
0.0010113348282952154,
0.0001325609843352507,
0.00029984165357390134,
0.00046104154967000925,
0.0014195171608235079,
0.0018029601400828192,
0.0014733644094703483,
0.001519911269089821,
0.000980829426427464,
0.0003693747816075631,
0.0017294142969565404,
0.000348511109502126,
0.0007082503261385923,
0.0003210365325876314,
0.0012646978965944829,
0.0015347028868335742,
0.0010527982657362277,
2.4795948316527575e-5,
0.0009964336959383726,
0.001685841930250312,
0.0009232755278053173,
0.00041431007666195004,
0.0003701132190313045,
0.0011708980317930743,
0.0004987849525083744,
0.0019365038792075592,
0.0008768666439910665,
0.0007215015250508931,
0.001976084911273778,
0.001104528821429371,
1.4340706320463055e-6,
0.0018381030133881513,
0.0004620641277131269,
0.0012761423672548507,
0.001768116111430507,
0.0010893948179095134,
0.000403120667887494,
0.001730182006695354,
0.0004408412815176264,
0.001672112282952945,
0.001636662471949778,
0.0008324088327207932,
0.0013578952418601348,
0.001903636420578739,
0.0017521586788196376,
0.0005736374491482669,
8.286423766507618e-5,
0.0003912122726180794,
0.0014120086358199821,
0.0014314196458646475,
0.00041469286099672843,
0.0010408926750579426,
9.641386432206783e-5,
0.0019114325250229693,
0.0007714150806026338,
0.0005426877224868825,
0.0018266841640463495,
0.0012482059603143342,
0.0014184433487956678,
0.0013506498430931827,
0.0001518179300747105,
0.0018834088259760391,
0.0005105652389871029,
0.00019460640327764186,
0.0010486062238223093,
0.00032766695735130473,
0.0009851875900107766,
0.0007642923802915474,
0.0008856009052559529,
0.00048486733493274597,
0.00048539928090889344,
0.0011129448263626327,
0.0002546283096939784,
0.0002496131464590531,
0.0016961716253364298,
0.001368704227191942,
0.0005443572020511274,
0.0017257559870764464,
0.0012703934432636054,
2.3778866312800337e-5,
0.0019605453253382014,
0.00030704150185665294,
0.0004600453064153849,
0.0008809731527354484,
0.0006942007573040998,
0.0014157256651722728,
0.001199700419600618,
0.0018668234202866192,
0.0004090409300695781,
0.0014243666634633208,
0.0013505142009286768,
0.0008180617479802867,
0.0005150098530964131,
0.001078786284436023,
0.00032989795772690836,
0.0006389489213384656,
0.00017834541945003157,
0.0013029725022187244,
0.0015276601328353138,
0.0014204690865051905,
0.000722166240553017,
0.001438185149311649,
6.60796211955629e-5,
0.0012900885532524267,
0.0013859504363514486,
0.0008854596703943416,
0.0007426617078624007,
0.0007564014678163869,
0.0010870259212903868,
0.0007593487651548561,
]
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
const lmo = FrankWolfe.KSparseLMO(100, 1.0)
const x00 = FrankWolfe.compute_extreme_point(lmo, rand(n))
function build_callback(trajectory_arr)
return function callback(state, active_set, args...)
return push!(trajectory_arr, (FrankWolfe.callback_state(state)..., length(active_set)))
end
end
@testset "Lazy Away Step CG" begin
x0 = deepcopy(x00)
res1 = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Shortstep(2.0),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
trajectory=true,
)
x_true1 = [
0.001422583298436932,
0.00027273619213263807,
0.0004982505954516348,
0.00016781414194964753,
0.0007277579866777386,
0.00022924464056524115,
0.0005862819582276917,
0.00016433101785554369,
0.0013573218913879833,
0.0017062956531315118,
0.001880519386637409,
0.0003660037194265856,
0.001425181673020117,
0.0016059379769033152,
0.0007985016372647361,
0.0007445621908502428,
0.001688102174812349,
1.2635658299699916e-5,
0.0005625744973508139,
0.0004956060654237624,
0.0008664564471334144,
0.0004691476292198133,
0.0007407375932988738,
5.8219185751327486e-5,
0.0016668042520459239,
0.0012301120930461491,
0.0014207383332020325,
0.00019629817246414512,
0.00023149816615342805,
0.0005457729620649364,
0.00046472742910844605,
0.0016567740433120327,
0.0006045563049609739,
6.794338511093809e-5,
0.0014508076551340596,
0.0009517078868957123,
0.001977751457938242,
0.001546932200578655,
0.001874171900483568,
0.0015432158965580597,
0.001436885697973832,
8.123783195490047e-5,
0.0017304521475545753,
0.0009952123505532783,
0.001435346934369604,
0.001704407444452622,
0.0013708999994775754,
0.0017276689804006057,
0.0017207386293186337,
0.0005881119999966264,
0.0015843187626965185,
0.0002248900005468801,
0.0010789356512070402,
0.0013330125500510962,
0.00041992272669491267,
0.0001663155483209697,
0.0016064306007644942,
0.0006240640136417282,
0.0014750988923257387,
0.0008635840117228274,
0.0005818681034150127,
0.0011220659002221156,
0.001599291798036956,
0.001058238610046571,
0.0019218317576815624,
0.0004358829009323019,
0.0015350408836077494,
0.0019150763101474454,
0.0011026000041810858,
1.552821592390492e-5,
0.0014681790112043998,
0.000105099754976968,
0.001396248297986154,
0.0005197180122391385,
0.00019855379679623088,
0.0018652938805804734,
0.0009494975453571945,
6.553689588068293e-5,
2.173143679411229e-5,
0.0005872042310431497,
0.0017695832489658418,
0.00154317807420678,
0.0019442827037914254,
0.00021954052231948132,
0.0006762506460557135,
7.177979881036352e-6,
0.00017203856745373142,
0.0018371863241565844,
0.0006645802958977139,
1.560677312329672e-5,
0.0004311625427945239,
0.0015824080871079422,
0.0001916669325429381,
0.0009058143759747405,
9.535097336617209e-5,
0.00024481621985804607,
0.000810507339679925,
0.00015599582913259713,
0.001488730799761298,
0.00014239762387376954,
0.0015252026281489237,
0.0004828291124104572,
0.0016408685398329635,
0.0009144831923073489,
0.00025350100539647574,
0.0017591750329373364,
0.00031804252116191976,
0.0001262518093072395,
0.0012697357480810024,
0.001355883995726469,
0.0012137853725334648,
0.0015971670984205736,
0.0011491769963244054,
0.0017529415239556129,
0.0002131749135309461,
0.0002616486356144201,
0.001165022239140106,
0.0006522877365379728,
0.0019796430094749413,
0.0020054541595486267,
0.00031484234970781643,
0.0007566885370529475,
0.0004918472250813644,
0.00031656924290316833,
0.00019181482957171842,
0.0018281654495742937,
0.0011533893762334627,
0.000573868200442384,
0.0016659749560906868,
0.0013950729978351782,
0.000843183598262116,
0.0017493949644233264,
0.0010129267221811677,
6.439072500158456e-5,
0.0006685729945893569,
0.0004409789633562954,
0.0016334372077967502,
0.00030493354848487505,
0.0005789651959674655,
0.001747795285331049,
0.0003119653631793791,
0.001988098499744349,
0.0017476246594401673,
0.0016824754829753777,
0.0012848774510369068,
0.0009006683166698149,
0.0012325362256900504,
0.0019658544017702724,
0.0012941247574037855,
0.0019402010097263932,
0.0016387731283857294,
0.00014496480962367716,
0.001328883874751634,
0.0002792433022146127,
0.000376305368510139,
0.00010736626596517225,
8.259540018750177e-5,
0.0007992580246088681,
0.00032088777076662604,
3.985824803874624e-5,
0.0015451888196207516,
0.0011934036486552322,
0.0004210294516110514,
0.0006864543056921651,
0.00024333232282691163,
0.00031918990489049977,
0.000571110872716258,
0.0016054757738309207,
0.0018515935484422147,
0.0004901845807064295,
0.0004600335492554734,
1.2671378872671308e-5,
0.00037579870365639595,
0.0006298044929322319,
0.00011705465500488188,
0.00041294862899641334,
0.00024277390326480274,
0.0013710095892248576,
0.0013364057089451681,
0.0012616305209054977,
0.0019927698189057138,
0.0005029439582579911,
0.0012150947403005532,
0.0006972289637076968,
0.0002651860467732891,
0.0007848344764096253,
0.0012398392784771727,
0.001816756321462804,
0.0018212477466463433,
0.0014103512442337211,
0.0013910445834584976,
0.0012804276600197912,
0.0003367524254090376,
0.0016400211791981984,
3.6837641321005985e-5,
0.0011426299675142643,
0.001425156442004878,
0.001162529898799113,
0.00016334719263855923,
0.001575351135717264,
9.498761433684464e-5,
0.0003688646463673834,
0.00044287706497212934,
0.00043354217234459306,
0.00014669201483358195,
0.0009607279550424813,
0.001738835202931529,
0.0012199472384665801,
0.0004738602119541344,
0.00016289575921213655,
0.0008063382828032295,
0.001779077817158389,
0.0006471524372962566,
0.00027338187178560476,
0.0016323524600192045,
0.0014388215491637115,
0.001585801555985741,
2.5328526273778736e-5,
0.00013426449231340048,
0.0013789007716318844,
0.001609893469899675,
0.001533460641716875,
0.00015048739843229606,
0.00031377927215406196,
0.0013781532696152759,
0.0004337521854309176,
0.0009784178854301217,
6.389351495085058e-5,
0.0017343209699450133,
0.0006450202831107695,
0.0008304460533936122,
0.0015885184514635472,
0.0009978495355821711,
0.001749732382140415,
0.00031931940459775237,
0.0019816758314184645,
0.0008959832558809814,
0.0014934781964352022,
0.00010829948881218047,
0.0017701657059495635,
0.0007247033662284584,
0.001002068922849399,
0.0005018430944771262,
9.577764122143186e-6,
0.0014349311477589442,
0.00039969217871372177,
0.00020479528257467513,
0.00154984153453624,
0.0008047121059421737,
0.0014379935402231774,
0.0008314268695423717,
0.0018494702922728483,
5.5388868225643025e-5,
0.0005730011827168046,
0.00042864798350337004,
0.0009391079951738075,
0.001989028601238455,
0.0017895995351085332,
0.0005983481903174807,
0.0011878533857429224,
0.00020393934668435366,
0.0012864455166272802,
0.000562824793115754,
0.00138628158203756,
0.0018025534381784039,
0.00037380376188099587,
0.0004490093664112049,
0.000779116652782068,
0.00045773632695422057,
0.0012377337551298432,
0.001040499116876897,
0.0013641875035476179,
0.0019502556804008185,
0.0019199984329793473,
0.0017927793224415225,
0.000571685594815955,
0.00016766218491233738,
0.0008070420519448847,
0.0003220123349427838,
0.0011636744528969504,
0.001625718930061574,
0.0005844485829110754,
7.617805188105912e-5,
0.000797328841321287,
0.0018301997112668115,
0.0019135070457975015,
0.0008501915403179514,
0.0018565277516904611,
0.0012163484792412978,
0.001601380621208906,
0.0013594316090462181,
0.0004693338120918366,
0.0015519771990332647,
0.0005190205188878503,
0.0017951490266581132,
0.0003528093772249075,
0.001569504178738941,
0.001417234179221147,
0.0006113648819008943,
8.246104172956826e-5,
0.001521624922819974,
0.00014082752519119996,
0.0004888272304369288,
0.00036204116897148786,
0.00023552824586397633,
0.0010522476744806337,
0.0011330280675029847,
0.0011919006528931175,
0.0001999242665420746,
0.0012578578233769396,
6.815607671143248e-5,
5.620789726257587e-5,
0.0015560946958158304,
0.0006731689453142587,
0.0008932040197831552,
0.0008727023987390509,
0.0016405809678080824,
0.0003542943838104295,
0.00031876973809498227,
0.0015016443288919225,
6.64046721549373e-5,
0.000891289133798293,
0.001996669097434254,
0.00045847773958111103,
0.0019196527545255711,
0.00025326041151168725,
0.001354705629039968,
0.0014396999106363157,
0.0014860476583688012,
0.00044725616132155804,
0.0013144134092116545,
0.0003646379208481011,
0.0003645428211151425,
0.0007737989180765329,
3.740377795979647e-5,
0.00036235651224719126,
0.001039270081657853,
0.0004457645535051069,
0.0016583359570858725,
0.0018412152984692268,
0.001689787850913742,
0.0011384781128179933,
0.000842510281623745,
0.0004845750119682093,
0.0013109474933286733,
0.0006680410797171914,
0.0002648064957388955,
0.000579393903889324,
0.002007718548275753,
0.00025654639135301306,
0.0004880825102864211,
0.0019387048403958598,
0.0012624320628974207,
0.0001261007024837611,
0.00048226663811817816,
0.0006995913037606427,
0.001834383678229052,
0.0003561901300635259,
0.001579522917207466,
0.0018893666138931182,
0.0019625338055259205,
0.0004205441519813119,
0.0010034907050917796,
0.001639013993702655,
0.0018377004426333992,
0.0012565153476833694,
0.00022105302076073674,
0.0012662897328368343,
0.0009447584987617238,
0.0015937106377387747,
0.0009950529145076024,
0.0019337925463650666,
0.0012952637437018942,
0.001918610724193101,
0.0005639191091289963,
0.000865462741448591,
0.00014730437487612893,
0.000673903662647801,
0.0011341037287862694,
0.00030672135517598734,
0.0015342334902029772,
0.0019925652582115402,
0.000977302511105224,
0.0015492357835884926,
0.0018479187274705892,
0.0014108559492532996,
0.00164598134237,
0.0008047157678973852,
0.0017241047346962769,
0.00045557900048990777,
0.0013508716333908563,
0.0015656116682494523,
0.0007124721131508691,
0.000404193753710275,
0.0009747107070896817,
0.0009805196981766274,
0.0015187055944472837,
0.0005213656648771209,
0.0002791011237045265,
0.00034137742563721267,
0.0009675373320712843,
0.001478723372342432,
0.0016581719306024859,
3.710150004609358e-5,
0.001547608075976774,
0.00014640722437357095,
8.081030061841183e-5,
0.001555296229468474,
0.0018178149132461816,
0.0013271067862801749,
0.0005714133492219603,
0.0005346464517370385,
0.001885819936009064,
0.0013436307421278498,
0.0008328413061147517,
0.0009882818079607779,
0.0010543683117150138,
0.0011976491789970044,
0.0012467677311572322,
0.001039860632401848,
0.0013616088894481248,
0.0013867853993846878,
0.0010421560502447908,
0.0003830833198844097,
0.0012626049292066494,
0.0016019628206965608,
0.001919594023709137,
0.00117971050606888,
0.001724695636556548,
0.0010593556914296504,
8.871818927372937e-5,
0.0017516577453378305,
0.00102871653773293,
0.0005981717891280463,
0.0010555885245747175,
0.0002633587454674742,
0.0011528274283465706,
0.0010726325379164603,
0.0005611878824471102,
0.0014084581247227272,
0.0010461456493267138,
0.0019993921709536592,
0.0013971954119033484,
0.0013930684343242225,
0.001901970715949614,
0.000463725536257292,
0.00197831859171314,
2.5392714729764217e-5,
0.0019063488799318247,
2.3252078142854604e-5,
0.0009103916653270865,
0.001220650001823333,
0.0017075537014015047,
0.0004972853662566432,
0.0005267064927532542,
0.0010094241154711202,
0.0018142128899403733,
0.001115595446510315,
0.0010736329264253934,
0.0015270361456379417,
0.0014331997833764653,
0.001957819283746969,
0.0006303437567574473,
0.0003317276109203346,
0.0017975535908435064,
0.0007884329950958072,
0.0019432158157201762,
0.0006182627207636845,
0.0001300020242654055,
0.0012424343176546447,
0.001952271661234906,
0.0013528893741912098,
0.0009195349234926948,
0.0012686033203867684,
0.0012314490102978747,
0.002012104008332672,
0.00015331254720017817,
0.0009504312986883304,
0.0016553550424929814,
0.0004987754604531402,
1.8061486463855277e-5,
0.0006186729317476349,
0.0005920520896513595,
0.001908220880704972,
0.0002205032608706313,
0.0018846493276807917,
0.001649440915965421,
0.0015854866403236768,
0.00024155971592595816,
0.00013159894751684848,
0.0005767675778804164,
0.00045532304650933674,
0.000774867640861596,
0.0013286214401055142,
0.0010912789168198258,
0.0002858706440047982,
0.0015346431775552238,
0.0018419428211717877,
0.0012287136832596515,
0.001753949628630284,
0.0007762031382974182,
0.0018104781303813647,
0.0009756409493174418,
0.00010748106828959538,
0.0008496920310213392,
0.00014029860655662596,
0.0011047691241680084,
0.0015142689620110598,
0.00030226840836937105,
0.0011549217765643638,
6.691357444105232e-5,
0.0008031845510523045,
0.0014565307456891187,
0.0008335950334179378,
0.0002075976678965532,
0.001458188830492884,
0.0005148620190456636,
0.0005635429355703793,
0.0004260481579223233,
0.0013069070422511945,
0.0003599480035956056,
0.0013560425483786864,
0.0014572227938180558,
0.00032897057311142457,
0.0009189062551815262,
0.0019203412579034116,
0.0012864312191510016,
0.001246234357933473,
0.0018189977650187245,
0.001985475557849982,
7.712863003485625e-5,
0.001526665077040111,
0.0010598546672319238,
0.001548905811976593,
0.0009180178833333117,
0.0003760625016432371,
0.0017197834010995985,
0.0006928424407913459,
0.0010718750766168,
0.0007047609799274532,
0.0002853923978799791,
0.0005109054766633496,
0.002014129621533365,
0.001551209172388499,
0.0011191843449866474,
0.0012311684688555574,
0.001740236488281249,
0.0008078549881630432,
0.0008781331945545614,
0.0018000763577365384,
0.0007401337144514051,
0.0015147412295822803,
0.0012855806273901079,
0.0015782106466732365,
0.0013863637301773665,
0.0014540983513454877,
0.001260968528739991,
0.0003174544000699268,
0.0004658118481329658,
0.001131094203957778,
0.0014473127347056608,
0.0005915013798896377,
0.000694852692937216,
0.000285250530188164,
0.0007283791750059971,
2.655024688757442e-5,
0.0006445868347754402,
0.0003285744621252636,
0.00012551935528379508,
0.001117918678620318,
0.0009587671951387034,
0.0016780322824373414,
4.5751284991488846e-5,
0.0014225284272224648,
0.0003962523035992107,
0.0006524294026542709,
0.0008939870223426083,
0.0007728205279356846,
0.00122764257055061,
0.00033797197091777235,
0.0010361793960494705,
0.000992123714045731,
0.0016742616055592967,
0.0011418951907944564,
0.0011254883431375522,
0.001179608446550195,
0.0016875140131860581,
0.0008345614171749304,
0.0014612740385894377,
0.0006579101484055432,
0.0017453972197901554,
0.0008591072418907181,
0.0016995835150818166,
0.001050935437111457,
0.0003355205387860035,
0.0017483973302545085,
0.0006776494744414888,
0.001689232187550956,
0.0015432149580402548,
0.001978626101081817,
0.0007472894803923799,
0.0016030470673767873,
0.00070483871723674,
0.001716715350844819,
0.00037974340498987,
0.0007207856565364333,
0.0017245937614663992,
0.0008722295870600599,
0.000594535533205484,
0.0019286721973490804,
0.0012940450032369688,
0.0005992861184322387,
0.0002590184149128445,
0.0014556092736391882,
0.0011197899557537489,
0.0006903327551185822,
0.000990785296250843,
0.0008028233211045262,
0.000280443361344798,
0.0018508864718488457,
0.0009063589461567853,
0.0007300038314775519,
0.0013136146915517111,
0.001343523906957859,
0.00028693694715622856,
0.0014957120285918621,
0.0011322415118701944,
0.0007084862398687383,
0.001002741865109609,
0.001399918477182617,
0.002018370749854445,
0.0003578748158769567,
0.0015732415199227409,
0.0013346764240358593,
5.396261680760094e-5,
0.0019500250115741466,
0.00031836158169964236,
0.0018499414313903496,
0.00022451042768580615,
0.0006256693229971255,
0.0018925340189315668,
0.0008323695670568445,
0.0018494623234886884,
0.000552807486126806,
0.00132879241113889,
0.0008518481683624414,
0.0015655089795607799,
0.0014250894045590534,
0.001783692163353371,
7.399526833212774e-5,
0.0012244377578062855,
0.0019286690927553492,
0.0003682311081514411,
0.0010479700004166874,
0.0007664301070006473,
0.001277056081265333,
0.0014612319623016736,
0.0017219784239935218,
0.0013531995015198584,
0.0003904162539486604,
0.0011340563641726957,
0.00026465002221450943,
0.00015826303765471887,
0.0009384298771469406,
0.001155265294850032,
0.0006697931790130622,
0.0016512783748064345,
0.0016720763771262655,
0.00013004180745809362,
0.0006047328775929771,
0.001946368248105952,
0.001409714027540915,
0.0005939037542364399,
0.00034632862655473786,
0.0019092871315185584,
0.0014981525501766727,
0.0013033403381136708,
0.001361547810787959,
0.0006815375632990205,
0.0017006269702060084,
0.0010137999488354166,
0.0013065166713973357,
0.001370392566781917,
0.0012401227597347564,
0.0018888135957447066,
0.0005517863244821161,
0.0007704312937686098,
0.0015646785537852116,
0.001728890413619102,
0.0009074483845392689,
0.0003248930724330634,
0.00019230634219962728,
0.001973470635931501,
0.0010107996961906767,
0.000737934876827271,
0.0003613158094939992,
0.0011335960157876964,
0.001614070982763523,
0.0007282299027401834,
0.0017996319289349326,
0.0015951870246683874,
0.001715427718319075,
0.0017561477043858693,
0.0017910129040202998,
0.0007325280311288266,
0.0015511074667366404,
0.00045841661894668515,
2.5432505098777385e-5,
0.0013207136439377964,
0.00165969252229519,
0.0009271255364041134,
0.001080749239490286,
0.0019088534223778012,
0.0019282807110163178,
0.0014683232841605199,
0.0017977302969440744,
0.00013036903487359953,
0.0011219300676445856,
0.0017913484027570735,
0.0015638344872666934,
0.000395653806172464,
0.0009333043484360031,
0.0005055041606260419,
0.0014501790020865848,
0.001454928723558188,
0.0010803487925333684,
0.0011313013071538806,
0.0006647575058682692,
0.0017128620916011348,
0.0009361699798974006,
0.0013879663300257192,
0.0005926046565979877,
0.0006284582625589525,
0.001414953335848003,
0.000773095405142131,
0.00027551050818841303,
0.00106154914511734,
0.0005827753690396551,
0.0003866537660643205,
0.0013339118700010787,
0.001160126162635099,
0.0010522941738203208,
0.0016876660366618266,
5.855468014117563e-5,
0.0014131852713235129,
0.0002457437241907388,
0.0016884114139716906,
0.0009296868405973708,
0.0010451514216289063,
0.000981945129055207,
0.0005856081651124788,
0.0004090782311935998,
0.0016377105084429769,
0.0011236984027533457,
0.0012209825890820637,
0.0019562165129882974,
0.0018292073963402774,
0.001029459874106476,
0.001347834038210862,
0.0017603707975983656,
0.001437173127494183,
0.0012235012021432306,
0.0007213793235132028,
0.002014841251582976,
9.810387630298418e-5,
0.001858455742116247,
0.0007844749265170895,
0.0005994352749042694,
0.001027096545701293,
0.0009371179676303667,
0.0007996457899177598,
0.0019957539342193137,
0.0018763523693588217,
0.0011040637090242286,
0.000980089266561489,
0.0007691398527437723,
0.000685834663004848,
0.0007589893202310672,
0.0009280233205602851,
0.0004285296897158306,
0.001498217293152234,
0.000743218267528272,
0.00018516599060035868,
0.00023267751173075603,
0.0011666251061595002,
2.2665942565722386e-5,
0.0019071669934721633,
0.00037418629819165646,
0.00020150920366569788,
0.0011304088946170877,
0.00046052643817477245,
0.001202378125875249,
0.0016810337702529462,
0.0013289535823317012,
0.0003857169246900532,
0.0011586788569675946,
0.0019890163147620542,
0.001929094358315458,
0.0004001605567236408,
0.0019096902335865962,
0.000759341089977938,
0.001470311213897094,
0.0015152401796678834,
0.000499213662615058,
0.0007682495834347361,
0.00021590616907036684,
0.0005469989003399555,
0.00011693155464717196,
0.00019989046845705593,
0.0005446716630181928,
8.934933545423188e-5,
0.0013333512547114654,
0.0005332103662880643,
0.0008368459446764117,
0.0009621939090595851,
0.00026451237982613474,
0.0010716772595672581,
0.001878756582531658,
0.0002928340776875815,
0.000814312164517899,
0.0005982949852184072,
0.0014569410650794058,
0.0010959324823471893,
0.0007470813026640377,
0.0007827602984632407,
0.000499104637470343,
0.0013750007734560216,
3.925658194016414e-5,
0.001902401641790156,
0.0008353160853543923,
0.0006211047686528423,
0.0012379692373795782,
0.0012783079427912693,
0.0015145651096785894,
0.000795969262926615,
0.0007757629202647777,
0.0016694550404165794,
0.00024788446630303636,
0.0018742188008230725,
0.00014317882105535634,
0.0011185485432344175,
0.0017090405331053832,
0.0014204243522563144,
0.0009239315930590699,
0.0014475749274134935,
0.0004330811907587753,
0.0007101792254382494,
0.0013792401750647469,
0.0015940712766281027,
0.0006648787106813445,
0.0013288432113601435,
0.00031868689876046486,
0.0014226539814749624,
0.001966301103790762,
0.0007250559350463143,
0.001189455535276804,
0.0011957698284713238,
0.0004424594282405574,
0.000494502776362727,
0.0017749441837692822,
0.0012083916149457324,
0.0001676405150022681,
0.0005541379232360824,
1.64631957729582e-5,
0.0016218019980621136,
0.0003117763598950634,
0.0016146404702683916,
0.0009111376160185599,
3.7604978187244607e-6,
0.00015123004997405135,
0.0004344160169747531,
0.0013974610342235919,
0.0018782026167251163,
9.200358407586306e-6,
0.00011266371416083018,
0.001039673121867329,
0.0009695938154884677,
0.0013383150248064551,
0.0002651104755399292,
0.001153716997685415,
0.0004679809363111976,
0.0007590249565310004,
0.0015960405624639406,
0.00021563511250378167,
0.00046032693787769233,
0.0014504953430403418,
0.0017487777730677593,
0.0007876985550734688,
0.0019703179726274726,
0.0018971098268463888,
0.0010113349846182177,
0.00013256101536835625,
0.00029984202998392315,
0.00046104197604629986,
0.0014195171292221045,
0.0018029600737668981,
0.0014733640608195738,
0.0015199112129300797,
0.000980829833385202,
0.00036937510502010196,
0.0017294145690009294,
0.0003485112560155944,
0.0007082503342362335,
0.00032103664506282,
0.0012646977038660726,
0.001534702869862633,
0.0010527981724539357,
2.4795944514472953e-5,
0.0009964333759062936,
0.0016858422851070258,
0.0009232754569551512,
0.0004143097744450794,
0.0003701131293865166,
0.0011708980989401905,
0.000498785220028118,
0.0019365038759930058,
0.0008768664267706072,
0.0007215014261358946,
0.0019760846701154943,
0.0011045292030687664,
1.4337787408594012e-6,
0.0018381030735973658,
0.0004620639036261162,
0.001276142315366479,
0.001768116115405069,
0.0010893945701892333,
0.0004031206828913365,
0.001730181645064054,
0.00044084102326667383,
0.0016721122484691742,
0.001636662873672582,
0.0008324088788894996,
0.0013578952649775545,
0.0019036361472903668,
0.0017521584003386847,
0.0005736375724364423,
8.286399712245452e-5,
0.00039121249730725597,
0.0014120088370654586,
0.0014314200393833944,
0.0004146924507170186,
0.001040892661350361,
9.641352925229688e-5,
0.0019114324373618369,
0.0007714149171142609,
0.0005426876668595871,
0.00182668454739801,
0.0012482060712479105,
0.0014184431524961807,
0.0013506502217772258,
0.00015181753642590896,
0.0018834092517213726,
0.000510565189696364,
0.00019460615673719785,
0.0010486062760165307,
0.0003276673150114249,
0.0009851875659484762,
0.0007642926503108052,
0.0008856011541384882,
0.0004848669047557673,
0.00048539944314076255,
0.0011129450071102375,
0.00025462855911150906,
0.00024961318562032714,
0.0016961719047011942,
0.001368703869857434,
0.0005443570462233956,
0.0017257559503324833,
0.0012703934495955549,
2.3778649539447173e-5,
0.00196054552152457,
0.0003070412501279034,
0.00046004527882805224,
0.0008809731394040901,
0.0006942004235863704,
0.0014157258544305782,
0.0011997006709666986,
0.001866823581255689,
0.00040904051247965154,
0.0014243670320588178,
0.0013505144880792636,
0.0008180618947076032,
0.0005150098890171806,
0.0010787858685634962,
0.0003298982873940715,
0.0006389488872324987,
0.00017834543220831387,
0.0013029728502635873,
0.001527659701103652,
0.0014204690294174393,
0.0007221664755227925,
0.0014381850486792985,
6.607970848145124e-5,
0.0012900882674253993,
0.0013859500485891095,
0.0008854600150037082,
0.0007426618635993496,
0.0007564017018040365,
0.0010870258486126172,
0.0007593483607523456,
]
primal_true1 = 4.3758944410464604e-17
@test norm(res1[1] - x_true1) ≈ 0 atol = 1e-6
@test res1[3] ≈ primal_true1 atol = 1e-7
@test res1[5][end][1] <= 54
trajectory_adaptive = []
callback = build_callback(trajectory_adaptive)
x0 = deepcopy(x00)
res2 = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
trajectory=true,
callback=callback,
)
x_true2 = [
0.001422583298436932,
0.00027273619213263807,
0.0004982505954516348,
0.00016781414194964753,
0.0007277579866777386,
0.00022924464056524115,
0.0005862819582276917,
0.00016433101785554369,
0.0013573218913879833,
0.0017062956531315118,
0.001880519386637409,
0.0003660037194265856,
0.001425181673020117,
0.0016059379769033152,
0.0007985016372647361,
0.0007445621908502428,
0.001688102174812349,
1.2635658299699916e-5,
0.0005625744973508139,
0.0004956060654237624,
0.0008664564471334144,
0.0004691476292198133,
0.0007407375932988738,
5.8219185751327486e-5,
0.0016668042520459239,
0.0012301120930461491,
0.0014207383332020325,
0.00019629817246414512,
0.00023149816615342805,
0.0005457729620649364,
0.00046472742910844605,
0.0016567740433120327,
0.0006045563049609739,
6.794338511093809e-5,
0.0014508076551340596,
0.0009517078868957123,
0.001977751457938242,
0.001546932200578655,
0.001874171900483568,
0.0015432158965580597,
0.001436885697973832,
8.123783195490047e-5,
0.0017304521475545753,
0.0009952123505532783,
0.001435346934369604,
0.001704407444452622,
0.0013708999994775754,
0.0017276689804006057,
0.0017207386293186337,
0.0005881119999966264,
0.0015843187626965185,
0.0002248900005468801,
0.0010789356512070402,
0.0013330125500510962,
0.00041992272669491267,
0.0001663155483209697,
0.0016064306007644942,
0.0006240640136417282,
0.0014750988923257387,
0.0008635840117228274,
0.0005818681034150127,
0.0011220659002221156,
0.001599291798036956,
0.001058238610046571,
0.0019218317576815624,
0.0004358829009323019,
0.0015350408836077494,
0.0019150763101474454,
0.0011026000041810858,
1.552821592390492e-5,
0.0014681790112043998,
0.000105099754976968,
0.001396248297986154,
0.0005197180122391385,
0.00019855379679623088,
0.0018652938805804734,
0.0009494975453571945,
6.553689588068293e-5,
2.173143679411229e-5,
0.0005872042310431497,
0.0017695832489658418,
0.00154317807420678,
0.0019442827037914254,
0.00021954052231948132,
0.0006762506460557135,
7.177979881036352e-6,
0.00017203856745373142,
0.0018371863241565844,
0.0006645802958977139,
1.560677312329672e-5,
0.0004311625427945239,
0.0015824080871079422,
0.0001916669325429381,
0.0009058143759747405,
9.535097336617209e-5,
0.00024481621985804607,
0.000810507339679925,
0.00015599582913259713,
0.001488730799761298,
0.00014239762387376954,
0.0015252026281489237,
0.0004828291124104572,
0.0016408685398329635,
0.0009144831923073489,
0.00025350100539647574,
0.0017591750329373364,
0.00031804252116191976,
0.0001262518093072395,
0.0012697357480810024,
0.001355883995726469,
0.0012137853725334648,
0.0015971670984205736,
0.0011491769963244054,
0.0017529415239556129,
0.0002131749135309461,
0.0002616486356144201,
0.001165022239140106,
0.0006522877365379728,
0.0019796430094749413,
0.0020054541595486267,
0.00031484234970781643,
0.0007566885370529475,
0.0004918472250813644,
0.00031656924290316833,
0.00019181482957171842,
0.0018281654495742937,
0.0011533893762334627,
0.000573868200442384,
0.0016659749560906868,
0.0013950729978351782,
0.000843183598262116,
0.0017493949644233264,
0.0010129267221811677,
6.439072500158456e-5,
0.0006685729945893569,
0.0004409789633562954,
0.0016334372077967502,
0.00030493354848487505,
0.0005789651959674655,
0.001747795285331049,
0.0003119653631793791,
0.001988098499744349,
0.0017476246594401673,
0.0016824754829753777,
0.0012848774510369068,
0.0009006683166698149,
0.0012325362256900504,
0.0019658544017702724,
0.0012941247574037855,
0.0019402010097263932,
0.0016387731283857294,
0.00014496480962367716,
0.001328883874751634,
0.0002792433022146127,
0.000376305368510139,
0.00010736626596517225,
8.259540018750177e-5,
0.0007992580246088681,
0.00032088777076662604,
3.985824803874624e-5,
0.0015451888196207516,
0.0011934036486552322,
0.0004210294516110514,
0.0006864543056921651,
0.00024333232282691163,
0.00031918990489049977,
0.000571110872716258,
0.0016054757738309207,
0.0018515935484422147,
0.0004901845807064295,
0.0004600335492554734,
1.2671378872671308e-5,
0.00037579870365639595,
0.0006298044929322319,
0.00011705465500488188,
0.00041294862899641334,
0.00024277390326480274,
0.0013710095892248576,
0.0013364057089451681,
0.0012616305209054977,
0.0019927698189057138,
0.0005029439582579911,
0.0012150947403005532,
0.0006972289637076968,
0.0002651860467732891,
0.0007848344764096253,
0.0012398392784771727,
0.001816756321462804,
0.0018212477466463433,
0.0014103512442337211,
0.0013910445834584976,
0.0012804276600197912,
0.0003367524254090376,
0.0016400211791981984,
3.6837641321005985e-5,
0.0011426299675142643,
0.001425156442004878,
0.001162529898799113,
0.00016334719263855923,
0.001575351135717264,
9.498761433684464e-5,
0.0003688646463673834,
0.00044287706497212934,
0.00043354217234459306,
0.00014669201483358195,
0.0009607279550424813,
0.001738835202931529,
0.0012199472384665801,
0.0004738602119541344,
0.00016289575921213655,
0.0008063382828032295,
0.001779077817158389,
0.0006471524372962566,
0.00027338187178560476,
0.0016323524600192045,
0.0014388215491637115,
0.001585801555985741,
2.5328526273778736e-5,
0.00013426449231340048,
0.0013789007716318844,
0.001609893469899675,
0.001533460641716875,
0.00015048739843229606,
0.00031377927215406196,
0.0013781532696152759,
0.0004337521854309176,
0.0009784178854301217,
6.389351495085058e-5,
0.0017343209699450133,
0.0006450202831107695,
0.0008304460533936122,
0.0015885184514635472,
0.0009978495355821711,
0.001749732382140415,
0.00031931940459775237,
0.0019816758314184645,
0.0008959832558809814,
0.0014934781964352022,
0.00010829948881218047,
0.0017701657059495635,
0.0007247033662284584,
0.001002068922849399,
0.0005018430944771262,
9.577764122143186e-6,
0.0014349311477589442,
0.00039969217871372177,
0.00020479528257467513,
0.00154984153453624,
0.0008047121059421737,
0.0014379935402231774,
0.0008314268695423717,
0.0018494702922728483,
5.5388868225643025e-5,
0.0005730011827168046,
0.00042864798350337004,
0.0009391079951738075,
0.001989028601238455,
0.0017895995351085332,
0.0005983481903174807,
0.0011878533857429224,
0.00020393934668435366,
0.0012864455166272802,
0.000562824793115754,
0.00138628158203756,
0.0018025534381784039,
0.00037380376188099587,
0.0004490093664112049,
0.000779116652782068,
0.00045773632695422057,
0.0012377337551298432,
0.001040499116876897,
0.0013641875035476179,
0.0019502556804008185,
0.0019199984329793473,
0.0017927793224415225,
0.000571685594815955,
0.00016766218491233738,
0.0008070420519448847,
0.0003220123349427838,
0.0011636744528969504,
0.001625718930061574,
0.0005844485829110754,
7.617805188105912e-5,
0.000797328841321287,
0.0018301997112668115,
0.0019135070457975015,
0.0008501915403179514,
0.0018565277516904611,
0.0012163484792412978,
0.001601380621208906,
0.0013594316090462181,
0.0004693338120918366,
0.0015519771990332647,
0.0005190205188878503,
0.0017951490266581132,
0.0003528093772249075,
0.001569504178738941,
0.001417234179221147,
0.0006113648819008943,
8.246104172956826e-5,
0.001521624922819974,
0.00014082752519119996,
0.0004888272304369288,
0.00036204116897148786,
0.00023552824586397633,
0.0010522476744806337,
0.0011330280675029847,
0.0011919006528931175,
0.0001999242665420746,
0.0012578578233769396,
6.815607671143248e-5,
5.620789726257587e-5,
0.0015560946958158304,
0.0006731689453142587,
0.0008932040197831552,
0.0008727023987390509,
0.0016405809678080824,
0.0003542943838104295,
0.00031876973809498227,
0.0015016443288919225,
6.64046721549373e-5,
0.000891289133798293,
0.001996669097434254,
0.00045847773958111103,
0.0019196527545255711,
0.00025326041151168725,
0.001354705629039968,
0.0014396999106363157,
0.0014860476583688012,
0.00044725616132155804,
0.0013144134092116545,
0.0003646379208481011,
0.0003645428211151425,
0.0007737989180765329,
3.740377795979647e-5,
0.00036235651224719126,
0.001039270081657853,
0.0004457645535051069,
0.0016583359570858725,
0.0018412152984692268,
0.001689787850913742,
0.0011384781128179933,
0.000842510281623745,
0.0004845750119682093,
0.0013109474933286733,
0.0006680410797171914,
0.0002648064957388955,
0.000579393903889324,
0.002007718548275753,
0.00025654639135301306,
0.0004880825102864211,
0.0019387048403958598,
0.0012624320628974207,
0.0001261007024837611,
0.00048226663811817816,
0.0006995913037606427,
0.001834383678229052,
0.0003561901300635259,
0.001579522917207466,
0.0018893666138931182,
0.0019625338055259205,
0.0004205441519813119,
0.0010034907050917796,
0.001639013993702655,
0.0018377004426333992,
0.0012565153476833694,
0.00022105302076073674,
0.0012662897328368343,
0.0009447584987617238,
0.0015937106377387747,
0.0009950529145076024,
0.0019337925463650666,
0.0012952637437018942,
0.001918610724193101,
0.0005639191091289963,
0.000865462741448591,
0.00014730437487612893,
0.000673903662647801,
0.0011341037287862694,
0.00030672135517598734,
0.0015342334902029772,
0.0019925652582115402,
0.000977302511105224,
0.0015492357835884926,
0.0018479187274705892,
0.0014108559492532996,
0.00164598134237,
0.0008047157678973852,
0.0017241047346962769,
0.00045557900048990777,
0.0013508716333908563,
0.0015656116682494523,
0.0007124721131508691,
0.000404193753710275,
0.0009747107070896817,
0.0009805196981766274,
0.0015187055944472837,
0.0005213656648771209,
0.0002791011237045265,
0.00034137742563721267,
0.0009675373320712843,
0.001478723372342432,
0.0016581719306024859,
3.710150004609358e-5,
0.001547608075976774,
0.00014640722437357095,
8.081030061841183e-5,
0.001555296229468474,
0.0018178149132461816,
0.0013271067862801749,
0.0005714133492219603,
0.0005346464517370385,
0.001885819936009064,
0.0013436307421278498,
0.0008328413061147517,
0.0009882818079607779,
0.0010543683117150138,
0.0011976491789970044,
0.0012467677311572322,
0.001039860632401848,
0.0013616088894481248,
0.0013867853993846878,
0.0010421560502447908,
0.0003830833198844097,
0.0012626049292066494,
0.0016019628206965608,
0.001919594023709137,
0.00117971050606888,
0.001724695636556548,
0.0010593556914296504,
8.871818927372937e-5,
0.0017516577453378305,
0.00102871653773293,
0.0005981717891280463,
0.0010555885245747175,
0.0002633587454674742,
0.0011528274283465706,
0.0010726325379164603,
0.0005611878824471102,
0.0014084581247227272,
0.0010461456493267138,
0.0019993921709536592,
0.0013971954119033484,
0.0013930684343242225,
0.001901970715949614,
0.000463725536257292,
0.00197831859171314,
2.5392714729764217e-5,
0.0019063488799318247,
2.3252078142854604e-5,
0.0009103916653270865,
0.001220650001823333,
0.0017075537014015047,
0.0004972853662566432,
0.0005267064927532542,
0.0010094241154711202,
0.0018142128899403733,
0.001115595446510315,
0.0010736329264253934,
0.0015270361456379417,
0.0014331997833764653,
0.001957819283746969,
0.0006303437567574473,
0.0003317276109203346,
0.0017975535908435064,
0.0007884329950958072,
0.0019432158157201762,
0.0006182627207636845,
0.0001300020242654055,
0.0012424343176546447,
0.001952271661234906,
0.0013528893741912098,
0.0009195349234926948,
0.0012686033203867684,
0.0012314490102978747,
0.002012104008332672,
0.00015331254720017817,
0.0009504312986883304,
0.0016553550424929814,
0.0004987754604531402,
1.8061486463855277e-5,
0.0006186729317476349,
0.0005920520896513595,
0.001908220880704972,
0.0002205032608706313,
0.0018846493276807917,
0.001649440915965421,
0.0015854866403236768,
0.00024155971592595816,
0.00013159894751684848,
0.0005767675778804164,
0.00045532304650933674,
0.000774867640861596,
0.0013286214401055142,
0.0010912789168198258,
0.0002858706440047982,
0.0015346431775552238,
0.0018419428211717877,
0.0012287136832596515,
0.001753949628630284,
0.0007762031382974182,
0.0018104781303813647,
0.0009756409493174418,
0.00010748106828959538,
0.0008496920310213392,
0.00014029860655662596,
0.0011047691241680084,
0.0015142689620110598,
0.00030226840836937105,
0.0011549217765643638,
6.691357444105232e-5,
0.0008031845510523045,
0.0014565307456891187,
0.0008335950334179378,
0.0002075976678965532,
0.001458188830492884,
0.0005148620190456636,
0.0005635429355703793,
0.0004260481579223233,
0.0013069070422511945,
0.0003599480035956056,
0.0013560425483786864,
0.0014572227938180558,
0.00032897057311142457,
0.0009189062551815262,
0.0019203412579034116,
0.0012864312191510016,
0.001246234357933473,
0.0018189977650187245,
0.001985475557849982,
7.712863003485625e-5,
0.001526665077040111,
0.0010598546672319238,
0.001548905811976593,
0.0009180178833333117,
0.0003760625016432371,
0.0017197834010995985,
0.0006928424407913459,
0.0010718750766168,
0.0007047609799274532,
0.0002853923978799791,
0.0005109054766633496,
0.002014129621533365,
0.001551209172388499,
0.0011191843449866474,
0.0012311684688555574,
0.001740236488281249,
0.0008078549881630432,
0.0008781331945545614,
0.0018000763577365384,
0.0007401337144514051,
0.0015147412295822803,
0.0012855806273901079,
0.0015782106466732365,
0.0013863637301773665,
0.0014540983513454877,
0.001260968528739991,
0.0003174544000699268,
0.0004658118481329658,
0.001131094203957778,
0.0014473127347056608,
0.0005915013798896377,
0.000694852692937216,
0.000285250530188164,
0.0007283791750059971,
2.655024688757442e-5,
0.0006445868347754402,
0.0003285744621252636,
0.00012551935528379508,
0.001117918678620318,
0.0009587671951387034,
0.0016780322824373414,
4.5751284991488846e-5,
0.0014225284272224648,
0.0003962523035992107,
0.0006524294026542709,
0.0008939870223426083,
0.0007728205279356846,
0.00122764257055061,
0.00033797197091777235,
0.0010361793960494705,
0.000992123714045731,
0.0016742616055592967,
0.0011418951907944564,
0.0011254883431375522,
0.001179608446550195,
0.0016875140131860581,
0.0008345614171749304,
0.0014612740385894377,
0.0006579101484055432,
0.0017453972197901554,
0.0008591072418907181,
0.0016995835150818166,
0.001050935437111457,
0.0003355205387860035,
0.0017483973302545085,
0.0006776494744414888,
0.001689232187550956,
0.0015432149580402548,
0.001978626101081817,
0.0007472894803923799,
0.0016030470673767873,
0.00070483871723674,
0.001716715350844819,
0.00037974340498987,
0.0007207856565364333,
0.0017245937614663992,
0.0008722295870600599,
0.000594535533205484,
0.0019286721973490804,
0.0012940450032369688,
0.0005992861184322387,
0.0002590184149128445,
0.0014556092736391882,
0.0011197899557537489,
0.0006903327551185822,
0.000990785296250843,
0.0008028233211045262,
0.000280443361344798,
0.0018508864718488457,
0.0009063589461567853,
0.0007300038314775519,
0.0013136146915517111,
0.001343523906957859,
0.00028693694715622856,
0.0014957120285918621,
0.0011322415118701944,
0.0007084862398687383,
0.001002741865109609,
0.001399918477182617,
0.002018370749854445,
0.0003578748158769567,
0.0015732415199227409,
0.0013346764240358593,
5.396261680760094e-5,
0.0019500250115741466,
0.00031836158169964236,
0.0018499414313903496,
0.00022451042768580615,
0.0006256693229971255,
0.0018925340189315668,
0.0008323695670568445,
0.0018494623234886884,
0.000552807486126806,
0.00132879241113889,
0.0008518481683624414,
0.0015655089795607799,
0.0014250894045590534,
0.001783692163353371,
7.399526833212774e-5,
0.0012244377578062855,
0.0019286690927553492,
0.0003682311081514411,
0.0010479700004166874,
0.0007664301070006473,
0.001277056081265333,
0.0014612319623016736,
0.0017219784239935218,
0.0013531995015198584,
0.0003904162539486604,
0.0011340563641726957,
0.00026465002221450943,
0.00015826303765471887,
0.0009384298771469406,
0.001155265294850032,
0.0006697931790130622,
0.0016512783748064345,
0.0016720763771262655,
0.00013004180745809362,
0.0006047328775929771,
0.001946368248105952,
0.001409714027540915,
0.0005939037542364399,
0.00034632862655473786,
0.0019092871315185584,
0.0014981525501766727,
0.0013033403381136708,
0.001361547810787959,
0.0006815375632990205,
0.0017006269702060084,
0.0010137999488354166,
0.0013065166713973357,
0.001370392566781917,
0.0012401227597347564,
0.0018888135957447066,
0.0005517863244821161,
0.0007704312937686098,
0.0015646785537852116,
0.001728890413619102,
0.0009074483845392689,
0.0003248930724330634,
0.00019230634219962728,
0.001973470635931501,
0.0010107996961906767,
0.000737934876827271,
0.0003613158094939992,
0.0011335960157876964,
0.001614070982763523,
0.0007282299027401834,
0.0017996319289349326,
0.0015951870246683874,
0.001715427718319075,
0.0017561477043858693,
0.0017910129040202998,
0.0007325280311288266,
0.0015511074667366404,
0.00045841661894668515,
2.5432505098777385e-5,
0.0013207136439377964,
0.00165969252229519,
0.0009271255364041134,
0.001080749239490286,
0.0019088534223778012,
0.0019282807110163178,
0.0014683232841605199,
0.0017977302969440744,
0.00013036903487359953,
0.0011219300676445856,
0.0017913484027570735,
0.0015638344872666934,
0.000395653806172464,
0.0009333043484360031,
0.0005055041606260419,
0.0014501790020865848,
0.001454928723558188,
0.0010803487925333684,
0.0011313013071538806,
0.0006647575058682692,
0.0017128620916011348,
0.0009361699798974006,
0.0013879663300257192,
0.0005926046565979877,
0.0006284582625589525,
0.001414953335848003,
0.000773095405142131,
0.00027551050818841303,
0.00106154914511734,
0.0005827753690396551,
0.0003866537660643205,
0.0013339118700010787,
0.001160126162635099,
0.0010522941738203208,
0.0016876660366618266,
5.855468014117563e-5,
0.0014131852713235129,
0.0002457437241907388,
0.0016884114139716906,
0.0009296868405973708,
0.0010451514216289063,
0.000981945129055207,
0.0005856081651124788,
0.0004090782311935998,
0.0016377105084429769,
0.0011236984027533457,
0.0012209825890820637,
0.0019562165129882974,
0.0018292073963402774,
0.001029459874106476,
0.001347834038210862,
0.0017603707975983656,
0.001437173127494183,
0.0012235012021432306,
0.0007213793235132028,
0.002014841251582976,
9.810387630298418e-5,
0.001858455742116247,
0.0007844749265170895,
0.0005994352749042694,
0.001027096545701293,
0.0009371179676303667,
0.0007996457899177598,
0.0019957539342193137,
0.0018763523693588217,
0.0011040637090242286,
0.000980089266561489,
0.0007691398527437723,
0.000685834663004848,
0.0007589893202310672,
0.0009280233205602851,
0.0004285296897158306,
0.001498217293152234,
0.000743218267528272,
0.00018516599060035868,
0.00023267751173075603,
0.0011666251061595002,
2.2665942565722386e-5,
0.0019071669934721633,
0.00037418629819165646,
0.00020150920366569788,
0.0011304088946170877,
0.00046052643817477245,
0.001202378125875249,
0.0016810337702529462,
0.0013289535823317012,
0.0003857169246900532,
0.0011586788569675946,
0.0019890163147620542,
0.001929094358315458,
0.0004001605567236408,
0.0019096902335865962,
0.000759341089977938,
0.001470311213897094,
0.0015152401796678834,
0.000499213662615058,
0.0007682495834347361,
0.00021590616907036684,
0.0005469989003399555,
0.00011693155464717196,
0.00019989046845705593,
0.0005446716630181928,
8.934933545423188e-5,
0.0013333512547114654,
0.0005332103662880643,
0.0008368459446764117,
0.0009621939090595851,
0.00026451237982613474,
0.0010716772595672581,
0.001878756582531658,
0.0002928340776875815,
0.000814312164517899,
0.0005982949852184072,
0.0014569410650794058,
0.0010959324823471893,
0.0007470813026640377,
0.0007827602984632407,
0.000499104637470343,
0.0013750007734560216,
3.925658194016414e-5,
0.001902401641790156,
0.0008353160853543923,
0.0006211047686528423,
0.0012379692373795782,
0.0012783079427912693,
0.0015145651096785894,
0.000795969262926615,
0.0007757629202647777,
0.0016694550404165794,
0.00024788446630303636,
0.0018742188008230725,
0.00014317882105535634,
0.0011185485432344175,
0.0017090405331053832,
0.0014204243522563144,
0.0009239315930590699,
0.0014475749274134935,
0.0004330811907587753,
0.0007101792254382494,
0.0013792401750647469,
0.0015940712766281027,
0.0006648787106813445,
0.0013288432113601435,
0.00031868689876046486,
0.0014226539814749624,
0.001966301103790762,
0.0007250559350463143,
0.001189455535276804,
0.0011957698284713238,
0.0004424594282405574,
0.000494502776362727,
0.0017749441837692822,
0.0012083916149457324,
0.0001676405150022681,
0.0005541379232360824,
1.64631957729582e-5,
0.0016218019980621136,
0.0003117763598950634,
0.0016146404702683916,
0.0009111376160185599,
3.7604978187244607e-6,
0.00015123004997405135,
0.0004344160169747531,
0.0013974610342235919,
0.0018782026167251163,
9.200358407586306e-6,
0.00011266371416083018,
0.001039673121867329,
0.0009695938154884677,
0.0013383150248064551,
0.0002651104755399292,
0.001153716997685415,
0.0004679809363111976,
0.0007590249565310004,
0.0015960405624639406,
0.00021563511250378167,
0.00046032693787769233,
0.0014504953430403418,
0.0017487777730677593,
0.0007876985550734688,
0.0019703179726274726,
0.0018971098268463888,
0.0010113349846182177,
0.00013256101536835625,
0.00029984202998392315,
0.00046104197604629986,
0.0014195171292221045,
0.0018029600737668981,
0.0014733640608195738,
0.0015199112129300797,
0.000980829833385202,
0.00036937510502010196,
0.0017294145690009294,
0.0003485112560155944,
0.0007082503342362335,
0.00032103664506282,
0.0012646977038660726,
0.001534702869862633,
0.0010527981724539357,
2.4795944514472953e-5,
0.0009964333759062936,
0.0016858422851070258,
0.0009232754569551512,
0.0004143097744450794,
0.0003701131293865166,
0.0011708980989401905,
0.000498785220028118,
0.0019365038759930058,
0.0008768664267706072,
0.0007215014261358946,
0.0019760846701154943,
0.0011045292030687664,
1.4337787408594012e-6,
0.0018381030735973658,
0.0004620639036261162,
0.001276142315366479,
0.001768116115405069,
0.0010893945701892333,
0.0004031206828913365,
0.001730181645064054,
0.00044084102326667383,
0.0016721122484691742,
0.001636662873672582,
0.0008324088788894996,
0.0013578952649775545,
0.0019036361472903668,
0.0017521584003386847,
0.0005736375724364423,
8.286399712245452e-5,
0.00039121249730725597,
0.0014120088370654586,
0.0014314200393833944,
0.0004146924507170186,
0.001040892661350361,
9.641352925229688e-5,
0.0019114324373618369,
0.0007714149171142609,
0.0005426876668595871,
0.00182668454739801,
0.0012482060712479105,
0.0014184431524961807,
0.0013506502217772258,
0.00015181753642590896,
0.0018834092517213726,
0.000510565189696364,
0.00019460615673719785,
0.0010486062760165307,
0.0003276673150114249,
0.0009851875659484762,
0.0007642926503108052,
0.0008856011541384882,
0.0004848669047557673,
0.00048539944314076255,
0.0011129450071102375,
0.00025462855911150906,
0.00024961318562032714,
0.0016961719047011942,
0.001368703869857434,
0.0005443570462233956,
0.0017257559503324833,
0.0012703934495955549,
2.3778649539447173e-5,
0.00196054552152457,
0.0003070412501279034,
0.00046004527882805224,
0.0008809731394040901,
0.0006942004235863704,
0.0014157258544305782,
0.0011997006709666986,
0.001866823581255689,
0.00040904051247965154,
0.0014243670320588178,
0.0013505144880792636,
0.0008180618947076032,
0.0005150098890171806,
0.0010787858685634962,
0.0003298982873940715,
0.0006389488872324987,
0.00017834543220831387,
0.0013029728502635873,
0.001527659701103652,
0.0014204690294174393,
0.0007221664755227925,
0.0014381850486792985,
6.607970848145124e-5,
0.0012900882674253993,
0.0013859500485891095,
0.0008854600150037082,
0.0007426618635993496,
0.0007564017018040365,
0.0010870258486126172,
0.0007593483607523456,
]
primal_true2 = 7.203447848470618e-17
@test norm(res2[1] - x_true2) ≈ 0 atol = 1e-6
@test res2[3] ≈ primal_true2 atol = 1e-7
@test res2[5][end][1] <= 1001
trajectory_adaptiveLoc15 = []
callback = build_callback(trajectory_adaptiveLoc15)
x0 = deepcopy(x00)
res3 = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
lazy=true,
lazy_tolerance=1.5,
trajectory=true,
callback=callback,
)
x_true3 = [
0.0014225829730460406,
0.0002727361735116165,
0.0004982501651903341,
0.00016781398601594972,
0.0007277581309256461,
0.0002292449206084246,
0.0005862821533397214,
0.00016433060575714962,
0.0013573219010460233,
0.0017062956435587595,
0.0018805197883647654,
0.0003660038076244705,
0.001425181813671474,
0.0016059380704091962,
0.000798501671039316,
0.0007445625596063425,
0.0016881023461908604,
1.2635475909140066e-5,
0.000562574094355615,
0.0004956060564769523,
0.0008664562894326867,
0.00046914760462751375,
0.0007407378079141604,
5.8218822194937334e-5,
0.0016668039941558747,
0.0012301116787980235,
0.0014207383442840023,
0.0001962981270141889,
0.0002314979873064894,
0.0005457730474431673,
0.0004647273336386779,
0.0016567737335910703,
0.0006045563164859911,
6.794339459572641e-5,
0.0014508076389582202,
0.0009517077726464148,
0.001977751733888766,
0.0015469323005633249,
0.0018741722739530557,
0.0015432160147052986,
0.0014368860198032839,
8.123743467215695e-5,
0.0017304519789725767,
0.0009952125105147666,
0.0014353470783572723,
0.0017044076626425355,
0.0013708998019686532,
0.001727668987939484,
0.0017207388368696834,
0.0005881117499539749,
0.0015843186971210555,
0.0002248903229213117,
0.0010789359592982117,
0.0013330122603689787,
0.00041992282337013117,
0.0001663156687643658,
0.0016064302450049927,
0.0006240639188199575,
0.0014750986250990803,
0.0008635840037072724,
0.0005818680233667699,
0.0011220658679165101,
0.0015992917245841217,
0.0010582389510119567,
0.0019218317980402783,
0.00043588297771513727,
0.0015350408604649984,
0.0019150762482866995,
0.0011025998296227077,
1.5528186482981463e-5,
0.0014681788131228096,
0.00010509939968210721,
0.001396248352413093,
0.0005197183340575723,
0.0001985541909458362,
0.001865293983191023,
0.0009494974108929405,
6.553696174444253e-5,
2.1731312965250076e-5,
0.0005872042577192267,
0.0017695830803962388,
0.001543177645415488,
0.0019442830961391268,
0.00021954041176523088,
0.0006762506740378053,
7.1780013746314316e-6,
0.00017203878072929,
0.0018371860763694986,
0.000664579868221674,
1.5606578005622747e-5,
0.00043116222425725964,
0.0015824081352081344,
0.00019166722732790183,
0.0009058144516906132,
9.535138147622678e-5,
0.0002448162609127538,
0.0008105073282727994,
0.00015599543489588864,
0.0014887306604467485,
0.0001423973215195137,
0.0015252030585587266,
0.0004828290638859407,
0.0016408685431010374,
0.0009144831655538666,
0.0002535005883881061,
0.0017591754309978487,
0.0003180421614544413,
0.00012625190334340924,
0.0012697356818344762,
0.0013558842626487677,
0.0012137856177825283,
0.0015971668858305386,
0.0011491769535195147,
0.0017529417603683673,
0.00021317496893476115,
0.00026164867916450086,
0.0011650225279267396,
0.0006522880060712687,
0.001979643108288294,
0.0020054541838487724,
0.00031484235252384173,
0.0007566885856223963,
0.000491847242180652,
0.0003165696791963495,
0.0001918152241857664,
0.0018281654231546184,
0.0011533894998752316,
0.0005738681479825615,
0.00166597496324203,
0.0013950726440668645,
0.0008431838003353523,
0.0017493945387852296,
0.0010129266537133048,
6.439075659908888e-5,
0.0006685728351128336,
0.0004409786823886957,
0.001633436883782188,
0.0003049332690152809,
0.0005789650695132066,
0.0017477952840985135,
0.0003119653497504122,
0.0019880985065267335,
0.001747624412370978,
0.0016824754459002305,
0.0012848772892363502,
0.0009006681701473457,
0.0012325359189026264,
0.001965854230544348,
0.0012941244759660196,
0.001940201002868717,
0.0016387730962449257,
0.00014496440056020144,
0.0013288836229320964,
0.0002792432543722183,
0.00037630513475765773,
0.00010736630029467021,
8.259563397365461e-5,
0.0007992577045906409,
0.0003208877140578041,
3.985789866354383e-5,
0.0015451889774413883,
0.001193403384289817,
0.0004210297433688409,
0.0006864541973724735,
0.0002433322067467775,
0.0003191897080440743,
0.0005711111046978741,
0.0016054760747429904,
0.001851593601771869,
0.0004901844541270471,
0.00046003338932956966,
1.2671541375500064e-5,
0.0003757986739219367,
0.0006298045227971904,
0.00011705488289968619,
0.00041294868243742716,
0.00024277385948936065,
0.0013710095987801729,
0.0013364057797802661,
0.0012616304916264615,
0.001992769650982513,
0.0005029442221274618,
0.0012150950277796423,
0.000697228829351848,
0.000265186005269483,
0.0007848344962405061,
0.0012398392540877092,
0.001816756341346897,
0.001821247727818187,
0.0014103508635352224,
0.0013910443196070996,
0.0012804278070470897,
0.0003367524246530507,
0.0016400211738672578,
3.683761709612566e-5,
0.0011426299632942727,
0.0014251565816392716,
0.0011625295009150462,
0.00016334692237419138,
0.001575351103682853,
9.498766743597785e-5,
0.0003688648658734696,
0.00044287718173993576,
0.00043354211646342715,
0.00014669168247831538,
0.0009607276565943663,
0.0017388352028757021,
0.001219947001099208,
0.00047386021368008306,
0.00016289575362384272,
0.0008063383314695654,
0.0017790777161857103,
0.0006471525482133755,
0.00027338176828548233,
0.0016323523128125138,
0.001438821355085743,
0.0015858013991118924,
2.532868456060823e-5,
0.00013426485844894877,
0.0013789009952368057,
0.0016098933708412109,
0.0015334608696284792,
0.00015048736145953574,
0.0003137788471296785,
0.0013781531346678001,
0.0004337521318274236,
0.0009784180783885164,
6.389319185063426e-5,
0.0017343206169757258,
0.0006450202541802735,
0.0008304456678156312,
0.0015885185377060931,
0.0009978498818170789,
0.0017497325562603164,
0.0003193194826570022,
0.001981675589943018,
0.0008959836035160942,
0.0014934780676036034,
0.00010829940205261081,
0.001770165813771591,
0.0007247032533086565,
0.0010020688806680203,
0.0005018434398245297,
9.577497102008272e-6,
0.0014349312885973493,
0.0003996918237694241,
0.00020479530808956395,
0.001549841229698745,
0.0008047122963317646,
0.0014379937614384909,
0.0008314269469336961,
0.0018494703492149176,
5.538929078331372e-5,
0.0005730011336742409,
0.00042864776396104725,
0.0009391080320926034,
0.001989028502595364,
0.001789599639168707,
0.0005983484570292027,
0.001187853307400933,
0.00020393940281975738,
0.0012864452668815312,
0.0005628248610658845,
0.0013862815143628501,
0.0018025535732459136,
0.0003738041484940745,
0.000449009637955848,
0.0007791170165506314,
0.00045773656765150895,
0.001237733592657059,
0.0010404995336866696,
0.0013641876383263256,
0.0019502557033566966,
0.0019199985858994887,
0.0017927791836778184,
0.0005716852949329822,
0.00016766206959056856,
0.0008070420795654343,
0.00032201232548988927,
0.0011636743048166857,
0.0016257189561989871,
0.0005844488038264827,
7.617781346898724e-5,
0.0007973292440250798,
0.0018302000344227046,
0.001913506930051725,
0.0008501916623441335,
0.0018565277139347247,
0.0012163484141768392,
0.0016013806476768535,
0.0013594317737759152,
0.00046933399849166977,
0.0015519769607849722,
0.0005190206721993658,
0.001795149291947321,
0.0003528092132199632,
0.0015695041108411544,
0.0014172340999628003,
0.0006113649237333382,
8.246148079108989e-5,
0.001521624571751393,
0.00014082732357038652,
0.0004888271395880285,
0.00036204120207168747,
0.00023552808959648029,
0.0010522476331018416,
0.0011330280716005383,
0.0011919004397130182,
0.00019992391874983702,
0.001257857968409302,
6.815601011812947e-5,
5.620784574857185e-5,
0.0015560949140045698,
0.0006731689968779049,
0.0008932039805345564,
0.0008727023439034104,
0.0016405810213521131,
0.0003542943495582939,
0.00031876979125314904,
0.0015016443445999366,
6.640428294540815e-5,
0.0008912890950772499,
0.001996669313938609,
0.00045847806279802894,
0.001919652492893255,
0.0002532605478803054,
0.0013547056765608355,
0.0014396998863641648,
0.0014860477070635682,
0.00044725593676477385,
0.00131441343337048,
0.0003646375719716522,
0.00036454314973411296,
0.0007737989811079925,
3.740373591055079e-5,
0.0003623564364001635,
0.0010392698106895765,
0.0004457642760831042,
0.0016583359751702455,
0.001841215159264119,
0.0016897878512288195,
0.0011384783742525435,
0.0008425102377901483,
0.00048457504404272606,
0.0013109477147870655,
0.0006680411123107607,
0.0002648064520538787,
0.0005793940997347103,
0.0020077185951712937,
0.00025654655178576017,
0.0004880824264181901,
0.0019387045960776717,
0.0012624318319706634,
0.0001261008632509476,
0.0004822664235812697,
0.0006995910773698801,
0.0018343834531075358,
0.0003561897023081971,
0.0015795229724546358,
0.0018893664062599083,
0.0019625338445946852,
0.0004205438565826633,
0.0010034908901702907,
0.0016390143920189462,
0.001837700389575972,
0.001256515357333801,
0.00022105274195036918,
0.0012662897591367696,
0.000944758427087643,
0.001593710556526598,
0.0009950529496323393,
0.0019337923328209277,
0.0012952633206058212,
0.0019186107808949106,
0.0005639190579831728,
0.0008654626847098967,
0.00014730476081159998,
0.0006739036447458508,
0.001134103686620537,
0.0003067213577651392,
0.0015342332768154378,
0.0019925656642191016,
0.0009773026204108063,
0.0015492361548762104,
0.001847918975804444,
0.0014108561208180093,
0.001645981387876666,
0.0008047156526954987,
0.0017241046382864376,
0.0004555787704975113,
0.0013508718476620818,
0.0015656119637856999,
0.0007124724097072913,
0.00040419379444344973,
0.0009747104174308419,
0.0009805195734891752,
0.0015187054530035708,
0.0005213653302950916,
0.0002791009971222689,
0.00034137762357468545,
0.0009675376320049635,
0.0014787231446392816,
0.0016581717178318703,
3.710136351973019e-5,
0.0015476082870810627,
0.00014640694252069213,
8.080987370149107e-5,
0.0015552962229914268,
0.0018178149768679414,
0.0013271067161333505,
0.0005714134289259438,
0.0005346464121440747,
0.0018858202836389499,
0.0013436309443604709,
0.0008328413967651013,
0.000988281757421916,
0.0010543682615420627,
0.0011976491806031274,
0.001246767972204216,
0.001039860712349674,
0.0013616088220375845,
0.0013867854700375557,
0.0010421561188120284,
0.0003830833384758642,
0.001262604915142975,
0.001601962618039536,
0.001919594387480944,
0.0011797104425778709,
0.001724695397971011,
0.0010593555503999067,
8.871825270960429e-5,
0.0017516580071519554,
0.001028716271420104,
0.0005981716483281348,
0.0010555882490727209,
0.0002633587507869325,
0.0011528277490044805,
0.0010726325205101372,
0.0005611877947099686,
0.0014084585430185373,
0.0010461453629526903,
0.001999392352643132,
0.001397195602944308,
0.0013930685083218361,
0.0019019705245408292,
0.00046372564226406437,
0.001978318705716091,
2.5392701993188165e-5,
0.0019063486066088705,
2.3252116272025228e-5,
0.0009103915283039962,
0.0012206501588780231,
0.0017075537681009428,
0.0004972857495669815,
0.0005267065603385678,
0.0010094238417385434,
0.0018142128080662014,
0.0011155955158307395,
0.0010736326229710729,
0.0015270358863057412,
0.0014332001239127186,
0.001957819187083567,
0.0006303434584651864,
0.0003317276877216092,
0.0017975536586028152,
0.0007884331400489046,
0.0019432162533525625,
0.0006182625666595225,
0.00013000223994737425,
0.0012424343696091176,
0.001952271996773228,
0.0013528893305614369,
0.0009195345848022567,
0.0012686033338657728,
0.0012314487713181177,
0.002012104151045027,
0.0001533124265297493,
0.0009504315120062167,
0.0016553550310117158,
0.0004987751818643117,
1.806151918140486e-5,
0.0006186728445021576,
0.000592052189307217,
0.0019082208700683426,
0.00022050366222209355,
0.0018846492367249961,
0.0016494410453672986,
0.0015854863831491438,
0.00024155985894675652,
0.00013159895627175205,
0.0005767677264166407,
0.00045532285471352443,
0.000774867602513501,
0.0013286214449100104,
0.0010912788795405344,
0.0002858707909539598,
0.0015346429914603352,
0.0018419427112867147,
0.001228713684453091,
0.0017539494529952152,
0.0007762032520236194,
0.0018104781770448128,
0.0009756409770065,
0.00010748120405826295,
0.0008496918312617622,
0.00014029856333002392,
0.0011047690750757737,
0.001514268911552873,
0.00030226865455149814,
0.0011549217642299035,
6.691355788381487e-5,
0.0008031842798304786,
0.0014565305921916166,
0.0008335947467451423,
0.00020759794339954304,
0.0014581886342254049,
0.0005148620991201897,
0.0005635426424462665,
0.0004260479042600673,
0.001306907268220247,
0.0003599479734395143,
0.0013560425653915832,
0.001457222874868419,
0.00032897063996877577,
0.0009189062780080308,
0.0019203413142922382,
0.0012864312473556115,
0.0012462345074251964,
0.0018189975287601363,
0.0019854751881943373,
7.71285300140424e-5,
0.001526665411612948,
0.001059854603694981,
0.0015489054821608938,
0.0009180179720595878,
0.000376062711954727,
0.0017197834742872051,
0.0006928424579371541,
0.001071875002172082,
0.0007047606933892668,
0.0002853923996399942,
0.0005109056257599122,
0.002014129469745734,
0.0015512092488812648,
0.001119184345674655,
0.0012311684275182987,
0.0017402361322587856,
0.0008078549239400554,
0.0008781330733087867,
0.001800076170984548,
0.0007401333103765735,
0.0015147410388536946,
0.0012855806179004822,
0.0015782105958118112,
0.0013863636864374798,
0.0014540986189522176,
0.0012609685907181648,
0.00031745415263617665,
0.00046581161140549205,
0.0011310941474195764,
0.0014473128884779514,
0.0005915013928915794,
0.0006948530869125625,
0.00028525025535421495,
0.0007283789565812113,
2.6550435654007106e-5,
0.0006445866397123424,
0.0003285745006792089,
0.0001255192480614488,
0.0011179188092534699,
0.0009587672659742316,
0.001678032564368427,
4.5751585156982476e-5,
0.0014225283746896757,
0.00039625237867299843,
0.0006524293523410218,
0.0008939871377089451,
0.0007728206267285187,
0.0012276422864069948,
0.0003379720566790985,
0.0010361792111890774,
0.0009921233536838792,
0.0016742618740733758,
0.0011418951399399762,
0.0011254883718386805,
0.001179608099249651,
0.0016875139870566355,
0.0008345610878204003,
0.0014612737132504465,
0.0006579103197844391,
0.00174539701424441,
0.0008591074491749693,
0.001699583736852279,
0.0010509353322753058,
0.00033552068831001593,
0.0017483971225406543,
0.000677649528326339,
0.0016892321335958455,
0.0015432150515217809,
0.0019786259441726965,
0.0007472892889123138,
0.0016030467010230004,
0.0007048388586085087,
0.0017167153456132003,
0.00037974349498968985,
0.0007207856530787894,
0.0017245936758770652,
0.0008722300074721449,
0.0005945354024228717,
0.001928672314702892,
0.0012940446470528664,
0.0005992857383283286,
0.0002590181232359661,
0.0014556092896979096,
0.0011197898073995098,
0.000690332451644496,
0.0009907848943367865,
0.0008028236813853396,
0.0002804432815713677,
0.001850886418798066,
0.0009063591051971155,
0.000730004231130443,
0.0013136149501585417,
0.0013435237761695129,
0.0002869366572464932,
0.0014957120256823735,
0.001132241689199434,
0.0007084865891683017,
0.0010027418419484286,
0.0013999186552584293,
0.0020183704943568877,
0.00035787464434341716,
0.0015732415281073245,
0.001334676084998223,
5.396256556994437e-5,
0.0019500249869654667,
0.00031836142371524743,
0.001849941468449124,
0.00022451032493989574,
0.0006256693590356446,
0.0018925343900385182,
0.0008323693672295888,
0.001849461935129479,
0.0005528073761836094,
0.0013287922965703775,
0.0008518480749467748,
0.0015655089939836284,
0.0014250890093526383,
0.0017836921658786527,
7.399501644276165e-5,
0.0012244377532552857,
0.0019286687977442105,
0.0003682311005169258,
0.0010479702853031807,
0.0007664304037378822,
0.0012770558359352798,
0.001461231986924087,
0.0017219781762864439,
0.001353199546245605,
0.0003904160821721199,
0.0011340566355001404,
0.00026464997461494994,
0.00015826267022022667,
0.0009384294914228401,
0.0011552652957179308,
0.0006697931105832635,
0.0016512784105051392,
0.001672076129398905,
0.00013004175770290363,
0.000604732874935747,
0.0019463680636663209,
0.0014097141406545592,
0.0005939033730957691,
0.00034632845378032275,
0.0019092870029785833,
0.0014981523044618414,
0.001303340565368365,
0.0013615477094686937,
0.0006815375456323484,
0.0017006268282846067,
0.0010138000052868357,
0.00130651646265391,
0.0013703925270699682,
0.00124012283915108,
0.0018888139358888248,
0.0005517860770222685,
0.0007704313414618369,
0.0015646785276354123,
0.0017288904895376832,
0.0009074479774621745,
0.00032489270245585246,
0.00019230637725438802,
0.001973470578287785,
0.0010107999731054636,
0.000737935128083724,
0.0003613157491882445,
0.0011335961314710387,
0.0016140707903559942,
0.0007282297699769588,
0.0017996318670018695,
0.0015951867070396585,
0.001715427694905274,
0.0017561474113270384,
0.0017910129124369067,
0.0007325282046518082,
0.0015511073939265363,
0.00045841701709311487,
2.5432708485927426e-5,
0.0013207136799669608,
0.0016596925417597674,
0.0009271256460730964,
0.0010807490771596489,
0.0019088534451495197,
0.0019282809265553423,
0.0014683232458321338,
0.001797730526220544,
0.00013036911065799326,
0.001121929786633218,
0.0017913484241105688,
0.0015638342089843967,
0.000395653757627598,
0.0009333039082064583,
0.0005055040869582924,
0.001450178900467947,
0.001454929032637948,
0.0010803486361148096,
0.0011313009417276577,
0.0006647576383532729,
0.001712861931658794,
0.0009361701315437307,
0.0013879660215275454,
0.0005926049525266263,
0.0006284583072031477,
0.0014149537185999582,
0.0007730954541276618,
0.0002755105489254437,
0.0010615490449365549,
0.0005827754139062623,
0.0003866537866826537,
0.0013339122851391077,
0.0011601265781187985,
0.0010522942759215303,
0.001687666462543278,
5.855498258788399e-5,
0.001413185355396865,
0.00024574398288062225,
0.0016884114400477527,
0.000929686708099112,
0.0010451514907264272,
0.000981945013405011,
0.0005856080333355511,
0.00040907828919079653,
0.0016377108410448684,
0.0011236983380842128,
0.0012209825988025189,
0.0019562165606643992,
0.0018292076671629555,
0.001029459862561986,
0.0013478339106018902,
0.0017603706991385704,
0.001437172810963163,
0.0012235015931802947,
0.0007213793201822198,
0.002014841431782602,
9.810411543051678e-5,
0.0018584553385386459,
0.0007844749572706888,
0.0005994353594887506,
0.0010270968890780234,
0.000937118021955865,
0.0007996457465978006,
0.0019957537201492634,
0.0018763523203533799,
0.0011040638224177445,
0.0009800891664544537,
0.0007691398558456462,
0.0006858343018179541,
0.0007589891316904391,
0.0009280235123895792,
0.000428529367748073,
0.0014982170517540876,
0.0007432184713959207,
0.00018516594469772897,
0.00023267782868347577,
0.0011666249789230548,
2.2665924998125497e-5,
0.0019071669786732547,
0.00037418643622349736,
0.00020150915708639185,
0.0011304088640859146,
0.00046052641528392395,
0.0012023781012886745,
0.0016810337350683414,
0.0013289536261037078,
0.0003857169035978327,
0.001158678830300375,
0.0019890162704126594,
0.0019290945764850276,
0.0004001604395035497,
0.0019096902757736775,
0.0007593408429387869,
0.0014703115807810096,
0.0015152404236735996,
0.0004992136533963397,
0.0007682493960316498,
0.00021590614768385,
0.0005469991145650042,
0.00011693160317246425,
0.00019989032796155818,
0.0005446715604029582,
8.934944651099089e-5,
0.0013333510573597376,
0.0005332103407238076,
0.0008368455514357779,
0.0009621941862911005,
0.0002645127949997754,
0.0010716772786583532,
0.001878756357124902,
0.0002928341677560873,
0.0008143121727623034,
0.0005982950646874962,
0.0014569414245325964,
0.001095932633185667,
0.0007470813365407809,
0.0007827603047244712,
0.0004991047235357583,
0.0013750008299319146,
3.925615351574703e-5,
0.0019024015810387587,
0.0008353160402582735,
0.0006211049587265231,
0.0012379690307968024,
0.001278307658658544,
0.0015145648361351814,
0.0007959692144555214,
0.0007757628180782723,
0.0016694548141899684,
0.0002478845249789455,
0.0018742188203916506,
0.0001431792089604791,
0.0011185483574957882,
0.0017090405022962293,
0.0014204240341203645,
0.0009239312619721775,
0.0014475749273671083,
0.0004330816024698395,
0.0007101789644310696,
0.0013792399715583685,
0.0015940714678156411,
0.0006648787415037625,
0.0013288432166611295,
0.00031868692754756387,
0.0014226537393646373,
0.001966300828145862,
0.0007250562673816273,
0.0011894551267867131,
0.0011957698204312862,
0.0004424598139260511,
0.0004945024320623941,
0.0017749446042772128,
0.001208391626987191,
0.00016764046971078084,
0.0005541379204681514,
1.6463205322782954e-5,
0.001621801584320447,
0.000311776067159639,
0.0016146404179234151,
0.0009111375777024746,
3.760455581913668e-6,
0.00015122991436626249,
0.00043441581541682695,
0.0013974610002053037,
0.00187820250562127,
9.200579074916385e-6,
0.00011266403722508646,
0.0010396732333056967,
0.0009695938918524585,
0.0013383150166220972,
0.0002651101510102961,
0.0011537172264516576,
0.0004679810171893536,
0.000759024950887464,
0.0015960408677034021,
0.00021563499915297363,
0.00046032704016034967,
0.001450495692886544,
0.001748777829781285,
0.0007876988515534705,
0.001970317677974247,
0.0018971099754474523,
0.0010113348282702606,
0.00013256098433907053,
0.00029984165470211296,
0.0004610415496525072,
0.001419517160781018,
0.0018029601401574385,
0.0014733644096123774,
0.001519911268742315,
0.0009808294263699043,
0.00036937478069924544,
0.0017294142970461924,
0.0003485111085677326,
0.0007082503264791712,
0.00032103653206499533,
0.0012646978966006609,
0.0015347028876273947,
0.0010527982657331045,
2.4795948929252046e-5,
0.0009964336960875842,
0.001685841930526077,
0.0009232755278359127,
0.0004143100758282274,
0.00037011321905022505,
0.0011708980316420038,
0.0004987849524759044,
0.001936503879213869,
0.0008768666445541167,
0.0007215015258321235,
0.001976084910722642,
0.001104528821384065,
1.4340705899413656e-6,
0.0018381030136935027,
0.00046206412776766265,
0.0012761423675381122,
0.0017681161110252787,
0.001089394817773147,
0.00040312066794832797,
0.0017301820062408174,
0.00044084128166188574,
0.0016721122830982824,
0.001636662472850071,
0.0008324088328644644,
0.0013578952419124196,
0.0019036364198679154,
0.0017521586788246048,
0.0005736374496963604,
8.286423727325394e-5,
0.00039121227256263717,
0.0014120086359145714,
0.0014314196459529452,
0.0004146928614711022,
0.0010408926744469877,
9.641386340111979e-5,
0.001911432524422376,
0.0007714150810788611,
0.0005426877230335516,
0.0018266841634707875,
0.0012482059603147954,
0.0014184433494448267,
0.0013506498432520476,
0.00015181793006263387,
0.0018834088260167839,
0.0005105652389643137,
0.0001946064030945306,
0.0010486062249259423,
0.0003276669567590887,
0.0009851875895055037,
0.0007642923811760456,
0.0008856009052209912,
0.00048486733562035794,
0.0004853992817765065,
0.0011129448274077587,
0.00025462831083154373,
0.0002496131464998235,
0.0016961716252680023,
0.0013687042282413855,
0.0005443572022340504,
0.0017257559863903683,
0.0012703934437206287,
2.3778866261642623e-5,
0.001960545325161244,
0.0003070415009883762,
0.00046004530645866895,
0.0008809731519668607,
0.0006942007581020405,
0.0014157256643903876,
0.0011997004195277519,
0.0018668234204093702,
0.0004090409301539743,
0.0014243666624705006,
0.0013505142011395693,
0.0008180617478683388,
0.0005150098527750416,
0.0010787862842703457,
0.00032989795674491577,
0.0006389489204304177,
0.0001783454194102945,
0.0013029725022748885,
0.0015276601330230055,
0.0014204690859230752,
0.0007221662406929099,
0.0014381851490532411,
6.607962124277904e-5,
0.0012900885531799146,
0.0013859504352621073,
0.0008854596701842393,
0.0007426617078459545,
0.0007564014674420621,
0.0010870259212616771,
0.0007593487660018056,
]
primal_true3 = 2.6251493517155233e-22
@test norm(res3[1] - x_true3) ≈ 0 atol = 1e-6
@test res3[3] ≈ primal_true3 atol = 1e-7
@test res3[5][end][1] <= 245
trajectory_adaptiveLoc2 = []
callback = build_callback(trajectory_adaptiveLoc2)
x0 = deepcopy(x00)
res4 = FrankWolfe.away_frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.AdaptiveZerothOrder(),
print_iter=k / 10,
memory_mode=FrankWolfe.InplaceEmphasis(),
verbose=false,
lazy=true,
lazy_tolerance=2.0,
trajectory=true,
callback=callback,
)
x_true4 = [
0.0014225829743613801,
0.000272736173996018,
0.000498250165831316,
0.00016781398554943354,
0.00072775813146555,
0.0002292449202426735,
0.0005862821530843032,
0.0001643306055169377,
0.0013573219006879095,
0.0017062956436836038,
0.0018805197874835302,
0.0003660038077978794,
0.0014251818140146684,
0.001605938068923276,
0.0007985016725487092,
0.0007445625603927066,
0.0016881023466537102,
1.2635475724475553e-5,
0.000562574095568668,
0.0004956060570255119,
0.0008664562894744202,
0.00046914760457638114,
0.0007407378071786069,
5.821882193699442e-5,
0.001666803993656077,
0.00123011167859317,
0.0014207383445683846,
0.00019629812799978554,
0.00023149798777808285,
0.0005457730486299619,
0.0004647273337730131,
0.001656773734069498,
0.0006045563170401263,
6.794339462138083e-5,
0.0014508076394514607,
0.0009517077721306749,
0.0019777517344431823,
0.0015469323007022016,
0.0018741722747931267,
0.0015432160152742112,
0.0014368860197693472,
8.123743440886098e-5,
0.0017304519791178402,
0.0009952125111017378,
0.0014353470785758355,
0.0017044076619427073,
0.0013708998004870608,
0.0017276689882641063,
0.0017207388356776598,
0.0005881117488058579,
0.0015843186969192976,
0.0002248903237833871,
0.001078935958458411,
0.0013330122605765007,
0.0004199228220201521,
0.0001663156675470417,
0.001606430244990594,
0.0006240639181408853,
0.0014750986261760403,
0.000863584004860852,
0.000581868023711474,
0.0011220658675557128,
0.0015992917240908245,
0.0010582389507293578,
0.0019218317980981483,
0.0004358829764286742,
0.0015350408594638867,
0.0019150762489926843,
0.0011025998283368834,
1.5528185904185334e-5,
0.001468178813378891,
0.0001050994009242023,
0.0013962483519435885,
0.000519718334090666,
0.0001985541910458595,
0.0018652939839128675,
0.0009494974105756847,
6.553696257329348e-5,
2.1731313314788548e-5,
0.0005872042587158826,
0.0017695830812739257,
0.0015431776457107524,
0.0019442830967836484,
0.00021954041220413462,
0.0006762506743217778,
7.178001165806828e-6,
0.00017203878069421658,
0.001837186077251007,
0.0006645798689381575,
1.5606577383442706e-5,
0.00043116222473323074,
0.0015824081361996295,
0.00019166722717940552,
0.0009058144514101568,
9.5351382373054e-5,
0.0002448162607554125,
0.0008105073287103949,
0.00015599543397726637,
0.001488730661022864,
0.00014239732001793666,
0.0015252030575713226,
0.0004828290653092653,
0.0016408685435819591,
0.000914483165991301,
0.000253500588767749,
0.001759175430397863,
0.0003180421619069388,
0.00012625190418500334,
0.0012697356806205939,
0.001355884261372317,
0.0012137856168086833,
0.0015971668847455179,
0.0011491769542650036,
0.0017529417599897246,
0.00021317496838981563,
0.00026164867986317754,
0.0011650225280888176,
0.0006522880052438455,
0.0019796431101899324,
0.002005454182557133,
0.0003148423513809371,
0.000756688584809881,
0.0004918472412240939,
0.00031656967773826676,
0.00019181522488887756,
0.0018281654219729536,
0.0011533894996359952,
0.000573868149653978,
0.0016659749625753677,
0.0013950726448913096,
0.0008431837997220913,
0.0017493945390915748,
0.0010129266527799678,
6.439075553306764e-5,
0.000668572834884264,
0.00044097868323395364,
0.0016334368853140658,
0.0003049332694276901,
0.0005789650690452452,
0.0017477952841964165,
0.0003119653513163414,
0.001988098506502258,
0.0017476244131827694,
0.0016824754450684449,
0.0012848772880272503,
0.0009006681706024953,
0.0012325359193402204,
0.001965854231509105,
0.00129412447699196,
0.0019402010036756237,
0.0016387730959317205,
0.00014496440142884893,
0.0013288836221757529,
0.0002792432549349746,
0.00037630513480751396,
0.00010736630010853174,
8.259563445376793e-5,
0.0007992577038599008,
0.0003208877138878062,
3.985789854760635e-5,
0.0015451889763125838,
0.0011934033839913125,
0.0004210297437225692,
0.0006864541976811623,
0.00024333220735851208,
0.00031918970730587993,
0.0005711111056232229,
0.0016054760747839874,
0.0018515936008412352,
0.0004901844536450356,
0.00046003338830552987,
1.2671541438680889e-5,
0.0003757986730181749,
0.0006298045233660889,
0.00011705488219648358,
0.00041294868193184997,
0.0002427738585411833,
0.0013710095981569318,
0.0013364057793367,
0.001261630492528896,
0.0019927696513545303,
0.0005029442209008169,
0.0012150950270621063,
0.0006972288285883109,
0.0002651860064748677,
0.0007848344948549431,
0.001239839254131712,
0.0018167563395917708,
0.0018212477276998496,
0.0014103508636003183,
0.0013910443202007174,
0.00128042780724268,
0.00033675242398948713,
0.0016400211744223298,
3.68376181357699e-5,
0.0011426299625396086,
0.0014251565812141063,
0.00116252950199895,
0.00016334692359759657,
0.001575351103939826,
9.498766696429888e-5,
0.00036886486571151235,
0.0004428771805886527,
0.0004335421169776525,
0.0001466916832290079,
0.0009607276564445671,
0.0017388352034844424,
0.0012199470006213889,
0.0004738602138812364,
0.0001628957542877022,
0.0008063383317262218,
0.001779077717596706,
0.0006471525491245427,
0.0002733817685709841,
0.0016323523132421092,
0.0014388213552368886,
0.0015858014004030924,
2.532868352101213e-5,
0.0001342648575988372,
0.0013789009945380352,
0.0016098933709894753,
0.00153346087002594,
0.00015048736182124022,
0.0003137788469503525,
0.0013781531355136613,
0.00043375213068073433,
0.0009784180786536999,
6.389319114342543e-5,
0.001734320616100325,
0.0006450202541310004,
0.0008304456685944308,
0.0015885185382386185,
0.0009978498817717087,
0.0017497325540255162,
0.00031931948097993593,
0.001981675589418221,
0.0008959836037222737,
0.0014934780671322092,
0.00010829940312059653,
0.0017701658149106827,
0.000724703253177454,
0.0010020688796792087,
0.0005018434401916616,
9.577497676237218e-6,
0.0014349312893834124,
0.00039969182434888617,
0.000204795307190071,
0.0015498412287730905,
0.0008047122956043288,
0.0014379937613982336,
0.0008314269475613681,
0.0018494703492179815,
5.538929056013065e-5,
0.0005730011341899886,
0.00042864776483930625,
0.0009391080328750178,
0.001989028501903022,
0.001789599639603134,
0.0005983484552052464,
0.001187853308007518,
0.00020393940288195643,
0.001286445266535235,
0.0005628248608644395,
0.0013862815146080806,
0.001802553573050983,
0.0003738041489251905,
0.0004490096387660368,
0.0007791170172844092,
0.0004577365672700371,
0.0012377335937531404,
0.0010404995326007444,
0.0013641876384759386,
0.0019502557016056697,
0.0019199985862760976,
0.0017927791832200214,
0.0005716852958088965,
0.00016766206836545607,
0.00080704207898579,
0.00032201232616694615,
0.0011636743050449276,
0.001625718955748887,
0.0005844488048006496,
7.617781503977878e-5,
0.0007973292438651179,
0.001830200033627992,
0.001913506930569833,
0.0008501916623421857,
0.0018565277158399081,
0.0012163484152146655,
0.0016013806480427901,
0.0013594317746386396,
0.0004693339995964559,
0.0015519769602145494,
0.000519020673103851,
0.0017951492930113277,
0.00035280921350307876,
0.0015695041101933564,
0.001417234100888031,
0.0006113649242096904,
8.246148008844793e-5,
0.0015216245714154142,
0.00014082732244412644,
0.0004888271390014202,
0.00036204120077105355,
0.00023552809035447153,
0.0010522476337602056,
0.0011330280715826093,
0.0011919004392672884,
0.00019992391877173267,
0.0012578579678087017,
6.815600914688783e-5,
5.620784616662826e-5,
0.001556094912988073,
0.0006731689970422193,
0.0008932039793010616,
0.0008727023438011555,
0.001640581021940967,
0.00035429434956647874,
0.0003187697919504385,
0.0015016443445988949,
6.640428244876718e-5,
0.0008912890953780515,
0.001996669313259677,
0.0004584780633099148,
0.0019196524923161084,
0.00025326054782796344,
0.0013547056753897618,
0.001439699885299712,
0.0014860477067131178,
0.0004472559370658492,
0.001314413432884611,
0.0003646375725082844,
0.00036454314929335225,
0.0007737989815212527,
3.74037357863891e-5,
0.0003623564357779934,
0.0010392698090549352,
0.00044576427588351934,
0.0016583359741707087,
0.0018412151583045103,
0.001689787851964972,
0.0011384783745623445,
0.000842510236615873,
0.0004845750441787759,
0.0013109477153793294,
0.0006680411131631454,
0.000264806452184733,
0.000579394099443048,
0.002007718595486164,
0.0002565465516353984,
0.00048808242702767714,
0.001938704595457111,
0.0012624318318808733,
0.00012610086399958558,
0.00048226642548033865,
0.0006995910785431576,
0.0018343834529186399,
0.00035618970255054235,
0.0015795229724701301,
0.0018893664071608003,
0.0019625338448661703,
0.00042054385793522704,
0.0010034908898554024,
0.0016390143919013747,
0.0018377003907206705,
0.001256515358001122,
0.0002210527435909527,
0.0012662897594645703,
0.0009447584259677195,
0.0015937105560847977,
0.0009950529493674082,
0.0019337923335927003,
0.0012952633183137662,
0.0019186107814266845,
0.0005639190587637043,
0.0008654626837744172,
0.0001473047604049234,
0.0006739036440493413,
0.0011341036866350234,
0.0003067213579926474,
0.0015342332758675418,
0.0019925656639270166,
0.0009773026205330275,
0.0015492361541649604,
0.0018479189762490487,
0.0014108561214793748,
0.0016459813881221726,
0.000804715654508759,
0.0017241046393281746,
0.00045557876983841615,
0.0013508718486200959,
0.0015656119648591036,
0.0007124724091091019,
0.0004041937932403125,
0.0009747104180559817,
0.0009805195722783276,
0.0015187054519698344,
0.0005213653300607815,
0.00027910099605214913,
0.00034137762326234025,
0.0009675376323910399,
0.0014787231438540948,
0.0016581717181906638,
3.710136238145156e-5,
0.0015476082871798025,
0.000146406942866602,
8.0809872748954e-5,
0.0015552962239854951,
0.00181781497851156,
0.0013271067161916839,
0.0005714134280392898,
0.000534646412204368,
0.0018858202831664762,
0.0013436309435119697,
0.0008328413965610076,
0.0009882817570105822,
0.0010543682621333421,
0.001197649180216008,
0.0012467679710929417,
0.0010398607126054196,
0.0013616088220380674,
0.0013867854699567618,
0.0010421561202561874,
0.00038308333979167786,
0.001262604915061136,
0.001601962619465934,
0.0019195943864742638,
0.001179710441906709,
0.0017246953955855624,
0.001059355550057439,
8.871825207949434e-5,
0.0017516580064714626,
0.0010287162705973783,
0.0005981716484118286,
0.001055588248894337,
0.000263358750047743,
0.0011528277488584804,
0.0010726325205259978,
0.0005611877957161242,
0.0014084585433071005,
0.0010461453623148598,
0.0019993923530083444,
0.001397195602379254,
0.0013930685074526647,
0.0019019705235412613,
0.00046372564223904234,
0.00197831870542454,
2.5392703456896812e-5,
0.0019063486080497572,
2.3252115745991246e-5,
0.0009103915284317418,
0.001220650159167466,
0.0017075537667786275,
0.0004972857478740333,
0.0005267065592563007,
0.0010094238431439754,
0.0018142128078463408,
0.0011155955152607972,
0.001073632623842354,
0.0015270358854319798,
0.001433200123727438,
0.0019578191857436943,
0.0006303434571130885,
0.0003317276881724935,
0.0017975536586489083,
0.000788433141573668,
0.0019432162532642338,
0.0006182625659409961,
0.00013000223975298233,
0.0012424343703838236,
0.0019522719982407618,
0.0013528893298744456,
0.0009195345843482069,
0.001268603333017817,
0.0012314487714647087,
0.002012104151859878,
0.00015331242733147463,
0.0009504315110885182,
0.0016553550314976997,
0.000498775183258594,
1.806151804736757e-5,
0.0006186728437531724,
0.0005920521883281334,
0.0019082208703994276,
0.00022050366118348826,
0.0018846492357138625,
0.0016494410444926283,
0.0015854863831549068,
0.00024155985915107168,
0.00013159895734046677,
0.0005767677253476309,
0.0004553228541746362,
0.0007748676023254044,
0.0013286214453185545,
0.0010912788786810502,
0.000285870791159695,
0.0015346429908061495,
0.0018419427115880043,
0.001228713684724666,
0.0017539494526544865,
0.000776203251624186,
0.0018104781784081384,
0.0009756409762371242,
0.00010748120502558938,
0.0008496918323148599,
0.00014029856318985837,
0.0011047690748457741,
0.0015142689121638905,
0.00030226865576140927,
0.001154921763296334,
6.691355688057577e-5,
0.0008031842790644451,
0.0014565305925468587,
0.0008335947468451876,
0.00020759794420702811,
0.0014581886347829782,
0.0005148620992547831,
0.0005635426420552098,
0.00042604790412428204,
0.001306907267907408,
0.00035994797239940183,
0.001356042565923325,
0.001457222875934587,
0.00032897063833332456,
0.0009189062776433463,
0.0019203413137390357,
0.0012864312485684117,
0.0012462345070798917,
0.0018189975274214975,
0.0019854751877465167,
7.712853033290691e-5,
0.0015266654119894395,
0.0010598546040677453,
0.0015489054823257724,
0.000918017970940277,
0.00037606271113756716,
0.001719783473312611,
0.0006928424578080787,
0.0010718750026328765,
0.0007047606949027395,
0.0002853923973740528,
0.0005109056245024545,
0.002014129468490133,
0.0015512092475095912,
0.0011191843455769042,
0.0012311684261315263,
0.001740236132368535,
0.0008078549245037896,
0.0008781330731924002,
0.0018000761704981005,
0.0007401333101269685,
0.0015147410403680349,
0.0012855806173144608,
0.0015782105977119637,
0.0013863636866640883,
0.0014540986185465341,
0.0012609685897785154,
0.000317454152785981,
0.0004658116100686292,
0.001131094145268392,
0.001447312888603683,
0.0005915013932561248,
0.0006948530873601405,
0.0002852502549980423,
0.0007283789564658175,
2.655043554709008e-5,
0.0006445866375752935,
0.00032857450097425133,
0.00012551924765138132,
0.0011179188080312637,
0.0009587672647547522,
0.0016780325624859728,
4.575158319886076e-5,
0.0014225283756930088,
0.0003962523785313272,
0.0006524293522775,
0.0008939871378274416,
0.000772820627755313,
0.0012276422877772956,
0.00033797205427438384,
0.0010361792116512511,
0.000992123354987925,
0.0016742618749505556,
0.0011418951390279747,
0.0011254883724142566,
0.001179608099190592,
0.0016875139882042889,
0.000834561087054174,
0.0014612737141933515,
0.0006579103189494162,
0.001745397014474383,
0.0008591074503117063,
0.0016995837354385763,
0.0010509353343937987,
0.00033552068847955783,
0.001748397122559458,
0.0006776495272146955,
0.0016892321344516566,
0.0015432150515318566,
0.00197862594442962,
0.0007472892887145442,
0.0016030467017993176,
0.0007048388590286642,
0.0017167153468123182,
0.00037974349426059565,
0.000720785653888937,
0.001724593676736147,
0.0008722300070226204,
0.000594535402246172,
0.001928672314621123,
0.0012940446486137593,
0.0005992857394526842,
0.0002590181224669547,
0.0014556092896888058,
0.0011197898080715378,
0.0006903324514067347,
0.0009907848942334854,
0.0008028236812343426,
0.0002804432828722659,
0.0018508864188630284,
0.0009063591053537663,
0.0007300042308663796,
0.0013136149502167259,
0.0013435237753761924,
0.0002869366575419192,
0.0014957120265130669,
0.0011322416907284915,
0.0007084865894077216,
0.001002741841725643,
0.0013999186553729573,
0.0020183704943737856,
0.00035787464465853873,
0.0015732415280537372,
0.0013346760844266314,
5.396256627344144e-5,
0.0019500249861086894,
0.0003183614249889892,
0.0018499414683377834,
0.00022451032482761997,
0.0006256693603691175,
0.0018925343920570378,
0.0008323693668985606,
0.0018494619348564314,
0.0005528073759827736,
0.0013287922949995253,
0.0008518480751265364,
0.001565508994317163,
0.0014250890095858395,
0.0017836921660101545,
7.399501699934387e-5,
0.0012244377540895765,
0.0019286687990100345,
0.00036823110137633637,
0.0010479702850274039,
0.0007664304026677379,
0.0012770558362473813,
0.0014612319869219048,
0.0017219781766151523,
0.0013531995441721438,
0.00039041608200581683,
0.0011340566343704997,
0.0002646499735399049,
0.00015826266968005254,
0.0009384294918556608,
0.001155265294306961,
0.0006697931107998621,
0.0016512784120552306,
0.0016720761302965572,
0.00013004175935147198,
0.0006047328747478288,
0.0019463680649288732,
0.0014097141407316777,
0.0005939033732745605,
0.0003463284530704335,
0.0019092870027523307,
0.0014981523034308928,
0.001303340566277852,
0.0013615477099551787,
0.0006815375466615005,
0.0017006268278421154,
0.001013800004381689,
0.001306516461697429,
0.0013703925257482084,
0.0012401228396451724,
0.0018888139370437272,
0.0005517860754411934,
0.0007704313418466249,
0.0015646785277437143,
0.0017288904883525948,
0.0009074479778793613,
0.0003248927007886848,
0.00019230637606246583,
0.0019734705781951295,
0.0010107999724885228,
0.0007379351272214866,
0.0003613157492297475,
0.0011335961312022352,
0.00161407079196687,
0.0007282297708721836,
0.0017996318676904498,
0.0015951867078717228,
0.0017154276951455972,
0.0017561474102506314,
0.0017910129124869055,
0.0007325282052693366,
0.0015511073935576217,
0.0004584170175352366,
2.5432707102691337e-5,
0.0013207136804810208,
0.001659692541376127,
0.0009271256444950645,
0.0010807490773711078,
0.0019088534459592076,
0.001928280928390022,
0.00146832324707375,
0.0017977305279475101,
0.00013036911094390524,
0.0011219297873999317,
0.001791348424482151,
0.0015638342083806938,
0.0003956537561378301,
0.0009333039078388182,
0.0005055040863224017,
0.0014501788993518275,
0.0014549290313619527,
0.0010803486358663343,
0.0011313009413717542,
0.0006647576380586238,
0.001712861932184127,
0.0009361701313528355,
0.0013879660201112033,
0.0005926049515498218,
0.0006284583063885408,
0.0014149537183501236,
0.0007730954538772678,
0.0002755105486249854,
0.0010615490463193188,
0.0005827754142596496,
0.0003866537866436917,
0.0013339122848530205,
0.0011601265791961915,
0.0010522942748497058,
0.0016876664621923497,
5.8554981623653655e-5,
0.001413185354911879,
0.00024574398285129084,
0.0016884114399479378,
0.0009296867068058089,
0.0010451514906287826,
0.0009819450132960248,
0.0005856080316104397,
0.00040907828962369157,
0.0016377108423700588,
0.0011236983382310513,
0.0012209825979506415,
0.001956216559764966,
0.0018292076669189613,
0.0010294598635311374,
0.001347833909348008,
0.0017603706981459103,
0.0014371728104730604,
0.001223501592822976,
0.0007213793204057284,
0.002014841432042811,
9.81041150618283e-5,
0.0018584553365004368,
0.0007844749559485189,
0.0005994353590246947,
0.0010270968886547918,
0.0009371180223607318,
0.0007996457462792682,
0.0019957537193183343,
0.001876352320447595,
0.0011040638228819605,
0.0009800891659251286,
0.0007691398541560135,
0.0006858343027756589,
0.000758989130889994,
0.0009280235119726452,
0.0004285293666280806,
0.0014982170534200718,
0.0007432184706879318,
0.00018516594398765667,
0.0002326778288474738,
0.0011666249777615865,
2.26659258202934e-5,
0.0019071669785700226,
0.00037418643542377146,
0.00020150915704746677,
0.0011304088655371327,
0.0004605264146603664,
0.0012023780995992226,
0.0016810337338745685,
0.001328953626233166,
0.0003857169031810155,
0.0011586788313971358,
0.001989016268431761,
0.0019290945769247596,
0.00040016043817543565,
0.0019096902743947436,
0.0007593408441959973,
0.001470311581698988,
0.0015152404244659918,
0.0004992136529168048,
0.0007682493962336363,
0.00021590614946372889,
0.0005469991129184686,
0.00011693160363296751,
0.00019989032901005549,
0.0005446715587211916,
8.934944591621952e-5,
0.0013333510574198514,
0.0005332103410453205,
0.0008368455514708842,
0.0009621941863704083,
0.00026451279446145767,
0.0010716772775013865,
0.0018787563576277667,
0.000292834167411912,
0.00081431217336405,
0.0005982950657805128,
0.0014569414238517076,
0.001095932633737282,
0.0007470813373254887,
0.0007827603050527227,
0.000499104723543889,
0.001375000829757557,
3.925615365283902e-5,
0.001902401580303642,
0.0008353160403061752,
0.0006211049577703393,
0.0012379690306810497,
0.0012783076601676714,
0.0015145648373589464,
0.0007959692135331035,
0.0007757628181029654,
0.001669454815730218,
0.00024788452368348094,
0.0018742188204974542,
0.00014317920829194522,
0.0011185483570329271,
0.0017090405023217911,
0.0014204240344167032,
0.0009239312623995638,
0.0014475749285327315,
0.00043308160281984036,
0.0007101789654727326,
0.0013792399713411067,
0.0015940714678223916,
0.0006648787422288034,
0.0013288432157188466,
0.000318686927405049,
0.0014226537398333813,
0.001966300827507352,
0.0007250562667700273,
0.0011894551242318866,
0.0011957698198062543,
0.0004424598126379026,
0.0004945024323395611,
0.0017749446041587652,
0.0012083916282584265,
0.00016764046974862703,
0.0005541379197676405,
1.6463205860436565e-5,
0.0016218015833325832,
0.000311776067337024,
0.0016146404190939014,
0.0009111375785329119,
3.760456040528737e-6,
0.00015122991291213379,
0.0004344158146977866,
0.001397461000105207,
0.001878202506294056,
9.200578945632454e-6,
0.00011266403633295871,
0.0010396732331887102,
0.0009695938916887818,
0.0013383150172126084,
0.0002651101501146812,
0.0011537172252120032,
0.0004679810157643291,
0.0007590249507857386,
0.0015960408684172166,
0.00021563499907006762,
0.0004603270399262137,
0.0014504956933646955,
0.0017487778281325863,
0.0007876988522645781,
0.0019703176784247435,
0.0018971099757045934,
0.0010113348278924898,
0.0001325609851140469,
0.0002998416530093345,
0.00046104154914333354,
0.0014195171612397658,
0.0018029601405211942,
0.00147336440855345,
0.0015199112681347983,
0.0009808294258288083,
0.0003693747803138458,
0.0017294142969839674,
0.00034851110887885344,
0.0007082503256913047,
0.00032103653268398695,
0.0012646978979240435,
0.001534702887697676,
0.0010527982652945762,
2.479594962808107e-5,
0.000996433694697435,
0.0016858419316192516,
0.0009232755275145045,
0.00041431007719392886,
0.00037011321943109773,
0.001170898032566598,
0.0004987849524328245,
0.0019365038797533617,
0.000876866644305634,
0.0007215015256256535,
0.001976084911335036,
0.0011045288210154108,
1.4340706238113907e-6,
0.0018381030130720458,
0.00046206412762438045,
0.0012761423663147098,
0.0017681161116551872,
0.0010893948171453705,
0.00040312066751078577,
0.0017301820069000058,
0.000440841282547788,
0.0016721122836217779,
0.0016366624724453427,
0.0008324088329372005,
0.0013578952419382746,
0.0019036364197364414,
0.0017521586790464321,
0.0005736374504310119,
8.286423745170061e-5,
0.00039121227157652607,
0.0014120086345669268,
0.0014314196469674366,
0.00041469286021667906,
0.001040892674972926,
9.64138653647309e-5,
0.0019114325260008288,
0.0007714150817021108,
0.0005426877234005207,
0.0018266841653205561,
0.0012482059611694557,
0.0014184433495449482,
0.0013506498432095705,
0.00015181793090970937,
0.0018834088247311734,
0.0005105652394763917,
0.00019460640266754875,
0.0010486062246763805,
0.0003276669576784625,
0.0009851875895813653,
0.000764292380576851,
0.0008856009046689323,
0.00048486733534480037,
0.00048539928157188166,
0.0011129448265769799,
0.00025462831098997635,
0.0002496131465257627,
0.0016961716249092472,
0.0013687042277097934,
0.0005443572030120984,
0.0017257559877021306,
0.001270393444154944,
2.377886697243377e-5,
0.0019605453240807845,
0.00030704150256771745,
0.00046004530767524055,
0.0008809731525996349,
0.000694200757760702,
0.0014157256649321736,
0.0011997004201582107,
0.0018668234203242503,
0.00040904093033612997,
0.0014243666627202132,
0.001350514201412394,
0.0008180617481802913,
0.0005150098526307086,
0.001078786284967522,
0.0003298979577640719,
0.0006389489213686306,
0.00017834542012123194,
0.0013029725015504634,
0.0015276601334745221,
0.0014204690860052163,
0.0007221662409647902,
0.001438185150153501,
6.607961980571957e-5,
0.001290088552710114,
0.0013859504365260078,
0.0008854596699312695,
0.0007426617067464929,
0.0007564014682609096,
0.0010870259209510857,
0.0007593487645926848,
]
primal_true4 = 4.517288607495588e-22
@test norm(res4[1] - x_true4) <= 1e-6
@test res4[3] ≈ primal_true4 atol = 1e-7
@test res4[5][end][1] <= 279
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 41833 | using FrankWolfe
using LinearAlgebra
using Test
using ReverseDiff
n = Int(1e3);
k = 1e3
const xp = [
0.0018327730915495884,
0.0015937445400959808,
0.0009003382186464693,
0.00127674793046702,
0.0006658776107376128,
0.0009205191029860242,
0.00027120179250720086,
0.0009568842164119253,
0.00017141310989939967,
0.001347806785639984,
0.0003756549468906054,
0.0007789830301650535,
0.001595951059883138,
0.0017491871177131065,
0.0009094333338028251,
0.00032279243212319814,
0.0013569096800504516,
0.001677147584151164,
0.0015391601930021873,
0.0012807239501508665,
0.0019255304798025477,
0.00023696519116144844,
0.0006740990642088303,
0.0008992907160919711,
0.00095870146293443,
0.0006020079336399129,
0.0010793591147014374,
0.001864192678347287,
0.0002308616941410699,
0.0008644771563767688,
0.00011160498970751212,
0.001457799362289775,
0.0013792778071976559,
0.0004811695430442883,
0.00034652238673556646,
0.00046014305343247284,
0.0015200893325180345,
0.0002301285029006331,
0.0008702304234927531,
0.0012559598183726735,
0.0011129546632819363,
0.0005924988153445136,
4.029384857735469e-6,
0.0004709756145071431,
0.001964605871887013,
0.0019007658592948712,
0.0003175280568686617,
0.00039519359524807865,
0.0018984336958403536,
0.00027524051594478207,
0.0011443101479584885,
0.0003446994490265905,
0.0008851891434967485,
0.0005551756905603518,
0.0018906802245579875,
0.00127509121720447,
0.00023109190134164496,
0.0011141821288208186,
0.0018872937629987984,
0.0009656897039301153,
0.0009532709255962198,
0.0018637789347380547,
0.001567190536468948,
0.001422748584770761,
0.0015038111175217637,
0.001470223281296216,
0.0006692664383454796,
0.0007199826094187467,
0.0019426711913402464,
0.0008483592078579399,
0.0008659318305379398,
0.000615960609169843,
0.0003876017221507564,
0.001979247539067491,
0.0001842352837771119,
0.0011614929182100495,
0.00043021373329181663,
0.00022434235551424179,
0.0013566339830943827,
0.00112751490494151,
0.0004441973280647759,
0.0004523257699007264,
0.001995937554057902,
0.0013376248691849492,
0.00015724480210718667,
0.0006843396921256714,
5.149177140935245e-5,
0.0019135234282829678,
0.001423223867003027,
0.0006690575109012296,
0.00043940829722780174,
0.0015482987671160563,
0.000991235623826253,
0.0010451879323598004,
0.0019721353656970766,
0.001590537575435224,
0.00036036301467069667,
0.0005176089802895095,
0.0010964623938275284,
0.0011604195508755576,
0.001963154346838054,
0.0008010390363287148,
0.0009462694088848839,
0.0004487482167006418,
0.001067704128654275,
0.0009187332598713647,
0.001224663566414967,
0.000581728212569191,
0.0011368643516045912,
0.00024573840310845727,
0.0016702918025943037,
5.641405301041516e-5,
0.0005167751816708099,
0.001279793338713246,
0.0007453637256759483,
0.0008758581662037049,
0.0006068813117986329,
0.0008160383784232987,
0.0011990616276158746,
0.000611394554624924,
0.0016351307828542825,
0.0006295201546188641,
0.0010249124806352876,
0.001528135509295967,
0.001134372045321598,
0.0014853708145065292,
0.0006835751262166197,
0.00017557291210234296,
0.0015858504246131675,
0.001072957085286627,
0.0007879608107194755,
0.0013573604649446678,
0.00024909955148385253,
8.599468740495325e-5,
0.001183363772711265,
0.00041115642853549656,
0.0016427071795206498,
0.0007850228455109578,
0.000882246807024765,
0.001657972127389477,
0.0002545493704343697,
0.0013542503275953003,
0.0002754785733604482,
0.0008402610320146713,
0.0013554538850161736,
0.00026437286516741316,
0.0012896209175443083,
0.00024335878706301038,
0.0006212177218613426,
0.0010692529838315853,
0.001859173765777184,
0.00045723538152473456,
0.0011965370852645295,
0.001989156509834248,
0.0016587458139964203,
0.0018819703658640914,
0.0009040276708432154,
0.00100556922903474,
0.0005708785341158682,
0.00011432643737059414,
0.0009428388537883419,
0.0009730278255207023,
0.00031013209589278326,
0.0018638085143026968,
0.0002542934827502082,
0.0008811444669717845,
0.001715865848796056,
0.000434684515180993,
0.0006618322680616472,
0.0009768754962879852,
0.0017403821107680089,
0.0017408714391316086,
0.00042231619868889785,
0.0011296323060238076,
0.0006896512905358444,
0.000892203979687179,
0.0004799202336923233,
4.120695301449753e-5,
0.00029747866685352645,
0.0013970894468810448,
0.0018488734714588605,
0.00026144166803006953,
0.00012472565360705865,
0.001336100105033711,
0.00027304137640162755,
0.0009954333529294166,
0.0007635781298635778,
0.0019404585702107204,
9.417181338508956e-5,
0.0013061086848206894,
0.0018599745118614143,
0.0014184356327043514,
0.0018847774134689165,
0.00198057265992906,
0.0013899996374345273,
0.001033418090673071,
0.001172126183766991,
0.0002491786408107791,
0.0005316957443559164,
0.0006581696066886157,
0.0003111388677669472,
0.0013364036523598078,
0.0010094442574075531,
0.0018497795791833848,
0.0007323593213486288,
0.0003055285971263878,
0.0013538279134556262,
9.486425007325548e-5,
0.0014637604377913654,
0.0001212269616937176,
0.001172059377299153,
0.001014748257755874,
0.0005763212815496139,
0.00010146351070545468,
0.0007448504926006604,
0.0008578913284180479,
0.0013317184488653815,
0.00011830847887435931,
0.001848310085883006,
0.0013499328132704855,
0.00019597389916035896,
0.0007566890546595535,
0.00193254794702912,
0.0003974847588399935,
0.0003780810792390995,
0.0014499682416200073,
0.0002497113831378613,
0.0009073444954380593,
0.0006941328804333382,
0.0012640877423129933,
0.000956649843209072,
0.0013484310578948753,
0.0004053245252322041,
0.0009670794712490947,
0.0012668876492248867,
0.001619080719097944,
0.0005214918544308543,
0.0011020109049342662,
0.0016483535866867157,
0.0018949856236975067,
0.0012733752297767944,
0.000655909883713231,
0.001872033168679548,
0.001386767453616496,
0.000324304586025684,
0.0010195007157271303,
0.0016783078026951603,
0.001575541373452696,
0.0007927853201302792,
0.0013969059422181385,
6.615768882254124e-5,
0.0014878756983712294,
0.0005875526142880978,
0.0005297963171169012,
0.0012498806378430454,
0.0005758184096768597,
0.0019419526045771737,
0.0009012191764821094,
6.75978463586831e-5,
0.0011630860329974583,
0.0007236986389638974,
0.001476215932609905,
0.0005086352610106773,
0.0016077714105984552,
0.0006951187838680796,
0.0013837315552207522,
0.000502193416509755,
0.0005580479763147728,
0.00048295234148723766,
0.0015666666260128485,
0.0006769227398960468,
0.001985142955532955,
0.00014267315129373005,
0.001902027829023448,
0.0012042027553697252,
0.00035670565654386823,
0.0006346847709761202,
0.00091952046224069,
0.0005176537762145475,
0.0016748877821021774,
0.0003978806450037573,
0.0006035334678798834,
0.0017219568486774594,
0.0009018821122855186,
0.001619653379346616,
0.001022433562073428,
0.001072698094039503,
0.0002038033359344979,
5.9798836285713143e-5,
0.00026374530352058515,
0.0018102475893269315,
0.00027553830387046344,
0.0009659885159881312,
0.0007561721143300964,
0.000788532484485178,
0.0010799488789369346,
0.0014724053628774657,
0.00031993817917332936,
0.0006177208319393205,
0.001817700677353197,
7.907170625981359e-5,
1.5573454383827163e-5,
0.00013866026421001314,
0.0017151636564962322,
0.0006552577530620876,
0.0019485177145897557,
0.001190339592661393,
0.0006808124346052569,
0.0005954759845031083,
0.0007985123103411901,
0.0004487716911070913,
0.0017200724960854817,
0.0017804603634335539,
0.0002765942521047776,
0.0016635828139130629,
0.0014743178504765277,
0.0015799378616438004,
0.0018315487485899213,
0.0002695490107889182,
0.0004531941431932836,
0.0013073678046168643,
0.0017611931961439794,
0.0009474400441979527,
0.0013257051128023254,
0.0010488265848314314,
0.0018716499251161885,
0.0015751416901875258,
0.001616065148123465,
0.0002485613086217679,
0.0013331056261160481,
0.0005963315192220173,
0.001379667879961323,
6.110827617394757e-5,
0.0015390710272743698,
0.0019288923575271632,
0.0010907948751852027,
0.00045825506794575533,
0.0005299259336476291,
0.0006541212128494624,
0.0007215258425467768,
0.001860011774737959,
0.0016031137007219795,
0.0006464400832404255,
0.001337677862036801,
0.0004881065606806423,
6.31421441759367e-5,
0.0016567198686779677,
0.0013610922427106382,
0.0005926783572242435,
0.001644571659827756,
0.0010494173981636069,
0.0014636575992381337,
0.0009066449485358799,
0.0015347892848303927,
0.00045542685141215187,
0.0003213560593230796,
0.001374283359636623,
0.0012785091435204832,
0.0003967449594011047,
0.0019454388715377015,
0.00023242901737008408,
0.0009423731928932567,
0.0010383219002757925,
0.001159227837391761,
0.00043874465016032144,
0.0004115595071388711,
0.00039375096066401427,
0.00032506183525874907,
0.0010207819688146569,
0.0015098348186148034,
0.001905914555518725,
0.0007735547422465331,
0.0007814356326174461,
0.0018113445797775924,
0.001041894131565221,
0.0008234594071261897,
0.0012830657307808776,
0.0007129334698624155,
0.00037139060224222585,
0.000803227267789403,
0.0014041081256167703,
1.5115266428794456e-5,
0.0009473538554703247,
0.0006720052663610818,
0.0009975645074246971,
0.001740678355869544,
0.0008318298921779738,
0.00019558339975096585,
0.0019556291686982116,
0.00057989682779768,
0.0001810619870975473,
0.001929890078977231,
0.001585444128828578,
0.0014466400010199392,
0.0002578676668168679,
0.00021370788420704937,
0.00025616866541825324,
0.001656862362405254,
0.0006624098851719846,
0.000488856922385659,
0.0007550544332957089,
0.0007819209255393643,
0.001188378606226741,
0.0009103461638397347,
0.00033993681025744707,
0.001775785231958221,
0.0015927372059838405,
0.0010072642203522364,
0.0015663218484591947,
0.0018377982520048507,
0.0010905951969243956,
0.00014769911241636265,
0.0009457940869536025,
0.000952939124557402,
0.00015558729138893403,
0.00035680989959007374,
0.001010041550483024,
0.0013790180501538133,
7.802661175271037e-5,
0.0014470730889533099,
0.0006764473444719864,
0.0013680396936119864,
0.0007693620294454979,
0.0019140342734339936,
0.00029998689797259805,
0.00019114086762915333,
0.001219494007900234,
0.0004976267897593667,
0.00170295549282911,
0.0019115982055067124,
0.0014759907540537077,
0.0009268002976558138,
0.0007942730585019111,
0.0007367326016035645,
0.0014649228101122934,
0.00015546969007001736,
0.0010327516215610697,
0.0007823597072905682,
0.00014691349516334442,
0.001245579612762418,
0.0012786862771840485,
0.00026684789160527747,
0.0010638069764506988,
0.0018297511062183812,
0.0017225147118992356,
0.0007248274739058347,
0.0011179385716630138,
0.0018209636507223034,
0.0015592566390118473,
0.0005909402616593415,
0.00022673588707267515,
0.00032818850151754763,
0.0006990863186125467,
0.001330417292136972,
0.0015288810903385307,
9.659083792112202e-5,
0.0002467595466102719,
0.0018691626524305267,
0.0003327680377894402,
0.0006728248645943384,
0.0006878252387040834,
0.0014801229392313985,
6.050024855478439e-5,
0.0004934161850992555,
0.00024186508107116626,
0.0013026045224702257,
0.001729280198300807,
0.0010612921637790688,
0.0018477841502465614,
0.00034739151174714646,
0.000514703481587503,
4.680165159905593e-5,
0.00026048516380227396,
0.0014591920580435773,
0.0009241194510978197,
0.0011134645001587605,
0.0019788248722242075,
0.0005708904371330058,
0.001183232824004749,
0.0008989131869314823,
0.000508697824295855,
0.0019707837972992165,
0.0019698774911707313,
0.0010600395092951556,
0.0010310344513264004,
0.001989637628077925,
0.0006447386615129625,
0.0012610054525879983,
0.0007609677170144002,
0.00017209698499650293,
0.0009924697621285857,
0.0003417824257821324,
0.0008380097781683315,
0.0007091561820366599,
0.00164100413367772,
0.0016507235595240861,
0.0007399674864961309,
0.0009511923987000143,
0.001576376484942097,
0.0019396844316881957,
0.0006232944417178602,
0.00036548031758296167,
0.00108412611917197,
0.0018005076506736246,
0.0008195832730431881,
0.0007834579740707772,
0.00115251872513119,
0.0018146600856659273,
0.0005610582076963469,
0.0003992005615304087,
0.0018395995819174328,
0.0013684936835912495,
0.0015639647900724033,
0.0008705811945658376,
0.00024415743695937905,
0.00034829983742813573,
0.0014980360651382647,
0.0019360937653995006,
0.00012202998944119299,
0.0006449676582695361,
0.0008098166298812683,
0.0005430125895007128,
0.0006024776260324192,
0.0014606536379434315,
0.0002734577802465653,
0.0015253026979302373,
0.0014506490933473236,
0.0009053434479656874,
0.00024572429640966825,
0.0017261423450467225,
0.0006634173125104148,
0.00020460005338718054,
0.0010525111257583064,
0.0011755345781089518,
0.0009628201144621855,
0.0018500696986080785,
0.0013465030432382894,
0.00044069758400812375,
2.8918450831516968e-5,
0.0005368905502858166,
0.0004212772954105924,
0.00015935697197428205,
0.0015575191232223477,
0.001969106260254529,
0.0014523394370467837,
0.0005143581758083439,
0.001672614261106492,
0.0003699072419913848,
0.0005614157712179695,
0.001443997282866257,
0.0010924593046373545,
0.0018438330886678704,
0.0009172935921157529,
0.0003334533180769076,
0.0006053163936255821,
0.0006975127051629411,
0.0006447215855192593,
0.0009038559384362273,
0.0002851791737987819,
0.0011100476801227251,
0.0013818662120346737,
0.0017274041637532517,
0.00034973363028089824,
0.00018254166991585696,
0.0012421183189664415,
0.0009404069996998386,
0.00040059486716694756,
0.0006761796808415352,
0.0007879149566179274,
0.0007036014935187577,
0.001662460181387039,
0.0013470682662865248,
0.0008292356276266305,
0.0009362777275760239,
0.0001705735597972123,
7.368511260263812e-5,
0.0008504500507358879,
0.001670104248747959,
0.0013701465452743377,
0.0011001260809050519,
0.000707958148483138,
0.0010920697390678362,
0.0017173305597642078,
0.0016707517326501149,
0.0011916614402770495,
0.00014950608258317054,
0.0009999296822657462,
0.0019265502401814149,
0.0018866771155574614,
0.0006901364742675106,
0.0008116640346814735,
0.0013824012324552197,
0.00011988968352039541,
6.724820191962071e-6,
0.000541109474743525,
0.0016004250972272815,
0.0013925414647899105,
5.0928854808417786e-5,
0.0014858906573357426,
0.0008402977780814168,
0.00030705891469881737,
0.0016622968358201938,
0.0018576382398660578,
0.0011286422361889267,
0.001680487391637096,
0.0018481482216813154,
0.0005887932985531036,
0.0006238451623384198,
0.0002941429468529822,
0.0018505281380446997,
0.0007705752172602122,
0.000521506971472071,
0.001439169135086595,
0.00022954255152772709,
0.00016345214486571723,
0.0005412805293540016,
0.0009543096200045798,
0.00030526309485633276,
0.0004423504153004842,
0.001331896818369305,
0.00045537794071123165,
0.0011494035415358244,
0.0018559525354102475,
0.0001617324331920188,
7.404623539455066e-5,
0.0007576313297505555,
0.0010321230933840729,
0.001125546423213475,
0.0018491309553563813,
0.0018047208197580816,
0.001596928518166632,
0.0009474773204987148,
0.0013455193636407782,
0.0004945025688660931,
0.0016401142815766915,
0.001461158510663254,
0.0010801425312820174,
0.00117543449937538,
0.0001409859989388047,
0.0014024237478710807,
0.0010732135150098888,
8.853927265193118e-5,
0.0002292957339488554,
0.00048564337909409705,
0.0016791010259568423,
0.0018404565027268429,
0.0012256716819134595,
0.0018977742433093328,
0.0012193539431702405,
0.0011129418826290895,
0.0004300373551459786,
0.0003096322110989376,
0.0002937406996688144,
0.0017445632310413364,
0.0014698238963586933,
0.0011637274665354054,
0.00029988012187886907,
0.0014078373638790641,
0.0010920443388229288,
0.0007616799501800092,
0.0014784583110823103,
0.0010369180317939433,
0.0005315182434241679,
0.0009443679112887697,
0.0015379516725051836,
0.0017899008573258213,
0.0001264327161521128,
0.000614104790564224,
0.0005140137534280678,
0.0019544467247925154,
0.0003481060897639085,
0.0011950184367434272,
0.0006704325730648348,
5.7789679651911883e-5,
0.0008260463562314218,
0.0004461525535082876,
0.0017253165770362438,
0.0004880111859461991,
0.0012328442207703526,
0.0012243847529723791,
0.0010727209085667655,
0.0015127088395774772,
0.001705599984036084,
0.001904262997230351,
0.00046307896123850336,
0.0006228713612049173,
0.0016114970380151144,
0.00028438852731265535,
0.00011085157564455476,
0.0006127371097982747,
0.000865327118624887,
0.00024375652128201108,
0.0003125392182457938,
0.0006581294516106818,
0.001101645022209513,
0.0010680663868787405,
0.00024341940847275002,
0.0007552071409940589,
0.0002834719113987055,
0.0015661662392179644,
0.0004631422222631197,
0.0009792865755230726,
0.0019579247610371137,
0.0016829964735991447,
0.0017244751150614112,
0.0017897389000213332,
0.0008556092437764926,
0.0007279064425182991,
0.00048655245053037734,
0.0012572693657413958,
0.0010797783765996727,
0.0008970205588488278,
0.0014175272869761339,
0.0013290864629511726,
0.0005245496865571544,
0.0009049967099332472,
0.00043558140742005385,
0.0011275812094613358,
0.00017273450978678079,
0.0012550804002917006,
0.0012781743532617365,
0.001573706848638644,
0.0013420731679475095,
0.0014892458739846888,
0.0008398246235935519,
0.00011504468581753147,
0.00039446185221038004,
0.0012376437036031238,
0.0018295550910136938,
0.0019546773576131814,
0.0015676052058229864,
0.001506851497019354,
0.001575197683338677,
0.0013763306886183757,
0.0017616294821065815,
0.0017435248930320643,
0.0018050603700472292,
0.0007503651034278091,
0.0009299828674809712,
0.0008756522416130647,
0.0006362927222849365,
0.00022210154903832706,
0.001844332500822328,
0.0013248403743752145,
0.0012559998892230895,
0.0018209525933688072,
0.0007335271183528885,
0.0014829191233771614,
0.0018678613135984172,
0.0011420653343152806,
0.0006605953396670363,
0.0008870568846896466,
0.0004900459822860427,
0.00025643224529566655,
0.001421495117363536,
0.001280223271089306,
0.00023855521270485226,
0.0012122575989886315,
0.0009627510945446007,
5.285953329532391e-5,
0.0009454499005818052,
0.0003700377574380651,
9.077339687952929e-7,
0.0014411222217378642,
0.0014173964830437181,
0.001226758073013107,
0.0015510199657714305,
0.001068549766336118,
0.001481795750543556,
0.000862743240234657,
0.0018364178627223657,
0.001297810444631,
0.0017288638263618468,
0.0014850128893871433,
0.0003876118061773179,
0.0006174093115518869,
0.0001558241106405434,
0.0017592029211481186,
0.0005700169392640262,
0.0007240705416604883,
0.0011116298082459834,
0.00013388249901906122,
0.0009231516835718252,
0.0007453818027215918,
0.001902893165074062,
0.0019350538421895446,
0.0007527871635143145,
0.0010257000169197053,
0.0009903603971969308,
4.4285426144378676e-5,
0.001564381934935309,
0.0015462480555508624,
0.00029899868944819523,
0.0015440779480220149,
0.0007418648975127938,
0.0019386004696501469,
0.0019131630292562234,
0.0015039026288142562,
0.00019896075715630912,
0.001293929283024881,
0.0010641333867957457,
0.0015197477936118194,
0.0012564938842911909,
0.0007840135152147756,
0.0015727679647529198,
0.0010820083599456722,
3.8300252164584965e-5,
0.001852308356736721,
0.0011578408985434623,
0.0018838742452490691,
0.0006827104598831953,
0.0004317043082294299,
0.001255847208881049,
0.001909609312654367,
0.00028111392236356047,
0.0012567089728115664,
0.00035089323655110733,
0.001591847528483122,
0.0010543319691625778,
0.0015210227188409,
0.0006187872451775554,
0.0006461464176754111,
0.0012521503243518503,
0.0010858832604493784,
0.0019696825709546763,
0.0004918204594470025,
0.0014651421292231155,
1.4381467369199035e-5,
0.0019798021556332902,
0.000621799009119485,
0.001234777757265796,
0.0013084057940826379,
0.0007577985064971946,
0.00048504609549452905,
0.0006107784742234016,
0.0005802471497523196,
0.00046874808725753584,
0.0006532405213221228,
6.264346279392007e-5,
0.0012680170832670627,
0.0009316962372604156,
0.0017697198580174584,
0.001508387782426762,
0.00041306458511965015,
0.00026087438719267617,
0.0011261602064797887,
0.0019850451621984005,
0.00023939598199659615,
0.0017541385937419633,
0.0013440822232875104,
0.0010770467943507596,
0.0018078683636017262,
0.0015231183627278455,
6.869221710248355e-5,
0.00035195006157333456,
0.0013762995791557688,
0.0008072149205532919,
0.0011353841005312634,
0.0014865730965501383,
0.0019307441257809916,
0.0011667277507501342,
0.0004294030938637975,
0.00111365615933646,
0.0014069834158223595,
4.8710162869939384e-5,
0.001436450945346649,
0.0017242135369256516,
0.00041730866559616447,
0.0009829065577903772,
0.001167055962634375,
0.001508796966308683,
0.0017893897976293015,
0.001287771363148189,
0.001997137544134502,
0.0002145244269098374,
0.001662766333988747,
0.00036868657263025025,
0.0007381648336162118,
0.0013742760119370514,
0.00011619435884379533,
0.0010922699701567502,
0.0014294553617263336,
0.0008149134535309198,
0.0011517173279784858,
0.0005618245613695095,
0.000921903951793312,
0.0009024406687822501,
0.0009017809865759639,
0.0008223481994507508,
0.0004962383638437895,
0.0017603447995208604,
0.000163248469761568,
0.0011429136963764706,
0.0018522434293814756,
0.0002356312964772626,
0.0010112992495719833,
0.0014210738528094217,
0.0010234170375453978,
0.0012090556341396276,
0.0015497166977694698,
0.00032572146086334153,
0.0011398813376043847,
0.0015589966071929637,
0.001902743947117522,
0.0003739076464881413,
0.0005822386500208485,
0.000860476817346138,
0.00041490200286679993,
0.0016411990778428178,
0.00032836239341761924,
0.0014958156778162395,
0.0012197218589056907,
0.0018146597016257785,
0.0014317525498898555,
0.0018016245765188758,
0.0006937041548007459,
0.00033402346803317474,
0.001406396085933951,
0.0008651945073745998,
0.0010878408091477782,
0.0011322785846400354,
0.0014529747440973576,
0.00041560645703940513,
0.001497228336849063,
0.0015424355185953238,
0.001869207847744262,
0.0012428300004407441,
0.0010937160906464953,
0.0012007892623604646,
0.0004721948120057884,
0.000414959864788396,
0.00062360561149615,
0.00041807456438264527,
0.0010052715695913102,
0.0013384843013248635,
0.0017928187389229999,
0.001913993790030471,
0.00023245030676397385,
0.0014580749126802976,
0.0004470042941235724,
0.0011436280459967535,
0.0011303445744775037,
0.0012753735267050843,
0.0016568858262784372,
0.0017566569095932968,
0.0005535250070063169,
0.0009223820466287302,
0.0008220756788574233,
0.0011116760097243385,
0.0014117799294308883,
0.00087495129826821,
0.0008111549551058168,
0.0004048409662543526,
0.000925904294106518,
0.001359317625777248,
0.0008899768972427336,
0.001818912222220616,
0.00105708599008006,
0.0009376529134939358,
0.001982571585694777,
0.0018797434748223426,
0.00046847491132920164,
0.00015401643870465188,
0.001882013352925305,
0.0014891448179153227,
0.0009715307625831949,
0.0014754496527844365,
0.0017764998980493963,
0.001798214544781652,
0.0017438490621810002,
0.00020540323451424944,
0.0009377724441468718,
0.0011041741045957185,
0.0009708990424034792,
0.00044236028038968064,
0.00037532641918069996,
0.0014276455734683763,
0.00018132726839262513,
0.0002564970819513468,
0.0006011127603836982,
0.0008406696828283911,
0.000263973972249628,
0.0005468165821273978,
0.00021476152125868216,
0.0003268425577002223,
0.0005780972992596821,
0.0018720112477446783,
0.0013828436790080526,
0.0018673680178595189,
0.0017363376985923286,
0.0014766123499324088,
0.0009136250184811881,
0.0014356085455390168,
0.0009559040137781322,
0.0007535310369443493,
0.0006742417823838604,
0.0016826807157711873,
0.0015410007790954772,
0.0009228700085840383,
0.000684659986697446,
]
@testset "Nonconvex Lasso" begin
f(x) = 2 * norm(x - xp)^3 - norm(x)^2
grad!(storage, x) = ReverseDiff.gradient!(storage, f, x)
lmo = FrankWolfe.ProbabilitySimplexOracle(1.0)
x0 = collect(FrankWolfe.compute_extreme_point(lmo, zeros(n)))
res = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
x0,
max_iteration=k,
line_search=FrankWolfe.Nonconvex(),
print_iter=k / 10,
verbose=false,
)
x_true = [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0032135880125713457,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00018516859804417726,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.006969188491359922,
0.0056815531539352315,
0.0,
0.0,
0.010176917272823348,
0.0,
0.0,
0.0,
0.0,
0.0,
0.02497013305042179,
0.0,
0.0,
0.0,
0.0016736801452988358,
0.0,
0.0,
0.0027281478733080303,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.024440222424345428,
0.0,
0.0,
0.0,
0.0,
0.0038530911472075794,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.014663370095865949,
0.0,
0.0,
0.0,
0.0,
0.007668232242457311,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.009257913756320776,
0.0,
0.0,
0.0,
0.0,
0.0,
0.020372781914532914,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.028408622282667544,
0.0,
0.0020357868035761253,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0002052828127294368,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00434028659960034,
0.0,
0.0,
0.0,
0.0,
0.00831818605260279,
0.014107079016793556,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0035639712105067535,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0025091858915269175,
0.0,
0.0,
0.018437396385970566,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.002673292094469775,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00350462263228815,
0.0,
0.0022693707270134045,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.005005370084094529,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0005338245730249912,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.01737316561449022,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.009871321544713584,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.006942084588314515,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.005593883716777582,
0.0,
0.0,
0.011803424931840265,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0019500739528989222,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0011400559223338504,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0007228936963650297,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.004236419618989145,
0.0,
0.0,
0.0,
0.0,
0.015512718361240276,
0.018805457372579944,
0.0,
0.0,
0.02325487476395467,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0060555153949940176,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.023160291066307348,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00470954218788022,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.03189188326685658,
0.006214742198205494,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0302683076052642,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.01666497968574187,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.015536991862228424,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.003990711114431177,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.007555239590432756,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.027091239380948737,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0010229362419501592,
0.0016230770642670785,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.010776728233836094,
0.014180606406681152,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0004846083939801903,
0.0,
0.0,
0.0,
0.0017525633832993605,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.030349931926964724,
0.0,
0.0,
0.0,
0.013579202318466358,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.008553560562398952,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.005225344578416675,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.33935548951829697,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0018635600585753555,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.000653473729923748,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.004698420875116127,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.01269961364132544,
0.009146813384144064,
0.0,
0.0,
0.0015114518587757443,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0202881787824224,
0.0,
0.00012235625801301618,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
]
primal_true = -0.039257619800701055
@test norm(res[1] - x_true) ≈ 0 atol = 1e-6
@test res[3] ≈ primal_true
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | code | 1943 | using FrankWolfe
using Test
using LinearAlgebra
@testset "Open-loop FW on polytope" begin
n = Int(1e2)
k = Int(1e4)
xp = ones(n)
f(x) = norm(x - xp)^2
function grad!(storage, x)
@. storage = 2 * (x - xp)
end
lmo = FrankWolfe.KSparseLMO(40, 1.0)
x0 = FrankWolfe.compute_extreme_point(lmo, zeros(n))
res_2 = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
copy(x0),
max_iteration=k,
line_search=FrankWolfe.Agnostic(2),
print_iter=k / 10,
epsilon=1e-5,
verbose=true,
trajectory=true,
)
res_10 = FrankWolfe.frank_wolfe(
f,
grad!,
lmo,
copy(x0),
max_iteration=k,
line_search=FrankWolfe.Agnostic(10),
print_iter=k / 10,
epsilon=1e-5,
verbose=true,
trajectory=true,
)
@test res_2[4] ≤ 0.004799839951985518
@test res_10[4] ≤ 0.02399919272834694
# strongly convex set
xp2 = 10 * ones(n)
diag_term = 100 * rand(n)
covariance_matrix = zeros(n,n) + LinearAlgebra.Diagonal(diag_term)
lmo2 = FrankWolfe.EllipsoidLMO(covariance_matrix)
f2(x) = norm(x - xp2)^2
function grad2!(storage, x)
@. storage = 2 * (x - xp2)
end
x0 = FrankWolfe.compute_extreme_point(lmo2, randn(n))
res_2 = FrankWolfe.frank_wolfe(
f2,
grad2!,
lmo2,
copy(x0),
max_iteration=k,
line_search=FrankWolfe.Agnostic(2),
print_iter=k / 10,
epsilon=1e-5,
verbose=true,
trajectory=true,
)
res_10 = FrankWolfe.frank_wolfe(
f2,
grad2!,
lmo2,
copy(x0),
max_iteration=k,
line_search=FrankWolfe.Agnostic(10),
print_iter=k / 10,
epsilon=1e-5,
verbose=true,
trajectory=true,
)
@test length(res_10[end]) <= 8
@test length(res_2[end]) <= 73
end
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 2011 | # Noteworthy changes from v0.3 to v0.4
- Changed `tt` to `step_type` everywhere, including as a type in the `CallbackState` object.
- `FrankWolfe.st` is now `FrankWolfe.steptype_string`
- all step types were renamed to clearly appear as constants, with a naming convention `ST_NAME`.
# Noteworthy changes from v0.1 to v0.2
- clean up `active_set.jl` by renaming `compute_active_set_iterate` to `get_active_set_iterate` and merging `find_minmax_direction` and `active_set_argminmax` [PR258](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/258)
- change keyword argument `K` to `lazy_tolerance` in all algorithms [PR255](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/255)
- remove L1ballDense [PR276](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/276)
- add `perform_line_search` function to all step size strategies and a workspace to line searches (to store intermediate arrays) [PR259](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/259)
- add type `MemoryEmphasis` and subtypes `InplaceEmphasis` and `OutplaceEmphasis` [PR277](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/277)- use `GenericSchur` to have type stable eigenvalues and compute min and max eigenvalues
- remove heavy dependencies, notably Plots.jl [PR245](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/245). The plotting functions are now in `examples/plot_utils.jl` and must be included separately.
- add step counter feature [PR301](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/301)
- call `@memory_mode` from within a function so new methods can easily be implemented [PR302](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/302)
- add struct `CallbackStructure` for state of callbacks. Callbacks can now return `false` to terminate the FW algorithm.
- add unified callback for verbose printcallback, user given stop criteria and trajectory tracking with counters [PR313](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/313)
- start with `t=1` and pass `t` instead of `t-1` in callbacks [PR333](https://github.com/ZIB-IOL/FrankWolfe.jl/pull/333)
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 4922 | # Contributing to FrankWolfe
First, thanks for taking the time to contribute.
Contributions in any form, such as documentation, bug fix, examples or algorithms, are appreciated and welcome.
We list below some guidelines to help you contribute to the package.
## Community Standards
Interactions on this repository must follow the Julia [Community Standards](https://julialang.org/community/standards/) including Pull Requests and issues.
## Where can I get an overview?
Check out the [paper](https://arxiv.org/abs/2104.06675) presenting the package
for a high-level overview of the feature and algorithms and
the [documentation](https://zib-iol.github.io/FrankWolfe.jl/dev/) for more details.
## I just have a question
If your question is related to Julia, its syntax or tooling, the best places to get help will be tied to the Julia community,
see [the Julia community page](https://julialang.org/community/) for a number of communication channels (Slack, Zulip, and Discourse being the most active).
For now, the best way to ask a question is to file an issue or reach out to [Mathieu Besançon](https://github/matbesancon) or [Sebastian Pokutta](https://github.com/pokutta).
You can also ask your question on [discourse.julialang.org](https://discourse.julialang.org) in the optimization topic or on the Julia Slack
on `#mathematical-optimization`, see [the Julia community page](https://julialang.org/community/) to gain access.
## How can I file an issue?
If you found a bug or want to propose a feature, we track our issues within the [GitHub repository](https://github.com/ZIB-IOL/FrankWolfe.jl/issues).
Once opened, you can edit the issue or add new comments to continue the conversation.
If you encounter a bug, send the stack trace (the lines appearing after the error occurred containing some source files)
and ideally a Minimal Working Example (MWE), a small program that reproduces the bug.
## How can I contribute
Contributing to the repository will likely be made in a Pull Request (PR).
You will need to:
1. Fork the repository
2. Clone it on your machine to perform the changes
3. Create a branch for your modifications, based on the branch you want to merge on (typically master)
4. Push to this branch on your fork
5. The GitHub web interface will then automatically suggest opening a PR onto the original repository.
See the GitHub [guide to creating PRs](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request) for more help on workflows using Git and GitHub.
A PR should do a single thing to reduce the amount of code that must be reviewed.
Do not run the formatter on the whole repository except if your PR is specifically about formatting.
### Improve the documentation
The documentation can be improved by changing the files in `docs/src`,
for example to add a section in the documentation, expand a paragraph or add a plot.
The documentation attached to a given type of function can be modified in the source files directly, it appears above the function / type / thingy you try to document
with three double quotation marks like this:
```julia
"""
This explains what the function `f` does, it supports markdown.
"""
function f(x)
# ...
end
```
### Provide a new example or test
If you fix a bug, one would typically expect to add a test that validates that the bug is gone.
A test would be added in a file in the `test/` folder, for which the entry point is `runtests.jl`.
The `examples/` folder features several examples covering different problem settings and algorithms.
The examples are expected to run with the same environment and dependencies as the tests using
[TestEnv](https://github.com/JuliaTesting/TestEnv.jl).
If the example is lightweight enough, it can be added to the `docs/src/examples/` folder which generates
pages for the documentation based on Literate.jl.
### Provide a new feature
Contributions bringing new features are also welcome.
If the feature is likely to impact performance, some benchmarks should be run with `BenchmarkTools` on several
of the examples to assert the effect at different problem sizes.
If the feature should only be active in some cases, a keyword should be added to the main algorithms to support it.
Some typical features to implement are:
1. A new Linear Minimization Oracle (LMO)
2. A new step size
3. A new algorithm (less frequent) following the same API.
### Code style
We try to follow the [Julia documentation guidelines](https://docs.julialang.org/en/v1/manual/documentation/).
We run [`JuliaFormatter.jl`](https://github.com/domluna/JuliaFormatter.jl) on the repo in the way set in the `.JuliaFormatter.toml` file, which enforces a number of conventions.
This contribution guide was inspired by [ColPrac](https://github.com/SciML/ColPrac) and the one in [Manopt.jl](https://github.com/JuliaManifolds/Manopt.jl).
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 4222 | # FrankWolfe.jl
[](https://github.com/ZIB-IOL/FrankWolfe.jl/actions)
[](https://zib-iol.github.io/FrankWolfe.jl/dev/)
[](https://zib-iol.github.io/FrankWolfe.jl/stable/)
[](https://codecov.io/gh/ZIB-IOL/FrankWolfe.jl)
[](https://doi.org/10.5281/zenodo.12720673)
This package is a toolbox for Frank-Wolfe and conditional gradients algorithms.
## Overview
Frank-Wolfe algorithms were designed to solve optimization problems of the form $\min_{x ∈ C} f(x)$, where `f` is a differentiable convex function and `C` is a convex and compact set.
They are especially useful when we know how to optimize a linear function over `C` in an efficient way.
A paper presenting the package with mathematical explanations and numerous examples can be found here:
> [FrankWolfe.jl: A high-performance and flexible toolbox for Frank-Wolfe algorithms and Conditional Gradients](https://arxiv.org/abs/2104.06675).
## Installation
The most recent release is available via the julia package manager, e.g., with
```julia
using Pkg
Pkg.add("FrankWolfe")
```
or the master branch:
```julia
Pkg.add(url="https://github.com/ZIB-IOL/FrankWolfe.jl", rev="master")
```
## Getting started
Let's say we want to minimize the Euclidian norm over the probability simplex `Δ`. Using `FrankWolfe.jl`, this is what the code looks like (in dimension 3):
```julia
julia> using FrankWolfe
julia> f(p) = sum(abs2, p) # objective function
julia> grad!(storage, p) = storage .= 2p # in-place gradient computation
# # function d ⟼ argmin ⟨p,d⟩ st. p ∈ Δ
julia> lmo = FrankWolfe.ProbabilitySimplexOracle(1.)
julia> p0 = [1., 0., 0.]
julia> p_opt, _ = frank_wolfe(f, grad!, lmo, p0; verbose=true);
Vanilla Frank-Wolfe Algorithm.
MEMORY_MODE: FrankWolfe.InplaceEmphasis() STEPSIZE: Adaptive EPSILON: 1.0e-7 MAXITERATION: 10000 TYPE: Float64
MOMENTUM: nothing GRADIENTTYPE: Nothing
[ Info: In memory_mode memory iterates are written back into x0!
-------------------------------------------------------------------------------------------------
Type Iteration Primal Dual Dual Gap Time It/sec
-------------------------------------------------------------------------------------------------
I 1 1.000000e+00 -1.000000e+00 2.000000e+00 0.000000e+00 Inf
Last 24 3.333333e-01 3.333332e-01 9.488992e-08 1.533181e+00 1.565373e+01
-------------------------------------------------------------------------------------------------
julia> p_opt
3-element Vector{Float64}:
0.33333334349923327
0.33333332783841896
0.3333333286623478
```
Note that active-set based methods like Away Frank-Wolfe and Blended Pairwise Conditional Gradient also include a post processing step.
In post-processing all values are recomputed and in particular the dual gap is computed at the current FW vertex, which might be slightly larger than the best dual gap observed as the gap is not monotonic. This is expected behavior.
## Documentation and examples
To explore the content of the package, go to the [documentation](https://zib-iol.github.io/FrankWolfe.jl/dev/).
Beyond those presented in the documentation, many more use cases are implemented in the `examples` folder.
To run them, you will need to activate the test environment, which can be done simply with [TestEnv.jl](https://github.com/JuliaTesting/TestEnv.jl) (we recommend you install it in your base Julia).
```julia
julia> using TestEnv
julia> TestEnv.activate()
"/tmp/jl_Ux8wKE/Project.toml"
# necessary for plotting
julia> include("examples/plot_utils.jl")
julia> include("examples/linear_regression.jl")
...
```
If you need the plotting utilities in your own code, make sure Plots.jl is included in your current project and run:
```julia
using Plots
using FrankWolfe
include(joinpath(dirname(pathof(FrankWolfe)), "../examples/plot_utils.jl"))
``` | FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 369 | ---
name: Bug report
about: Help us track down bugs in FrankWolfe.jl
---
Welcome to FrankWolfe.jl!
Be sure to include as much relevant information as possible, including a minimal reproducible example.
See https://help.github.com/articles/basic-writing-and-formatting-syntax/ for background on how to format text and code on GitHub issues.
Thanks for contributing!
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 633 | ---
name: Feature request
about: Suggest an idea for FrankWolfe.jl
---
You can use this Github issue to suggest a new feature or enhancement.
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 16839 | # Advanced features
## Multi-precision
All algorithms can run in various precisions modes: `Float16, Float32, Float64, BigFloat` and also for rationals based on various integer types `Int32, Int64, BigInt` (see e.g., the approximate Carathéodory example)
## Step size computation
For all Frank-Wolfe algorithms, a step size must be determined to move from the current iterate to the next one.
This step size can be determined by exact line search or any other rule represented by a subtype of [`FrankWolfe.LineSearchMethod`](@ref), which must implement [`FrankWolfe.perform_line_search`](@ref).
Multiple line search and step size determination rules are already available.
See [Pedregosa, Negiar, Askari, Jaggi (2020)](https://arxiv.org/abs/1806.05123) and [Pokutta (2023)](https://arxiv.org/abs/2311.05313) for the adaptive step size and [Carderera, Besançon, Pokutta (2021)](https://openreview.net/forum?id=rq_UD6IiBpX) for the monotonic step size.
## Callbacks
All top-level algorithms can take an optional `callback` argument, which must be a function taking a [`FrankWolfe.CallbackState`](@ref) struct and additional arguments:
```julia
callback(state::FrankWolfe.CallbackState, args...)
```
The callback can be used to log additional information or store some values of interest in an external array. If a callback is passed, the `trajectory` keyword is ignored since it is a special case of callback pushing the 5 first elements of the state to an array returned from the algorithm.
## Custom extreme point types
For some feasible sets, the extreme points of the feasible set returned by
the LMO possess a specific structure that can be represented in an efficient
manner both for storage and for common operations like scaling and addition with an iterate.
See for example [`FrankWolfe.ScaledHotVector`](@ref) and [`FrankWolfe.RankOneMatrix`](@ref).
## Active set
The active set represents an iterate as a convex combination of atoms (also referred to as extreme points or vertices).
It maintains a vector of atoms, the corresponding weights, and the current iterate.
Note: the weights in the active set are currently defined as `Float64` in the algorithm.
This means that even with vertices using a lower precision, the iterate `sum_i(lambda_i * v_i)` will be upcast to `Float64`.
One reason for keeping this as-is for now is the higher precision required by the computation of iterates from their barycentric decomposition.
## Extra-lazification with a vertex storage
One can pass the following keyword arguments to some active set-based Frank-Wolfe algorithms:
```julia
add_dropped_vertices=true,
use_extra_vertex_storage=true,
extra_vertex_storage=vertex_storage,
```
`add_dropped_vertices` activates feeding discarded vertices to the storage while `use_extra_vertex_storage`
determines whether vertices from the storage are used in the algorithm.
See [Extra-lazification](@ref) for a complete example.
## Specialized active set for quadratic functions
If the objective function is quadratic, a considerable speedup can be obtained by using the structure `ActiveSetQuadratic`.
It relies on the storage of various scalar products to efficiently determine the best (and worst for `blended_pairwise_conditional_gradient`) atom in the active set without the need of computing many scalar products in each iteration.
The user should provide the Hessian matrix `A` as well as the linear part `b` of the function, such that:
```math
\nabla f(x)=Ax+b.
```
If the Hessian matrix `A` is simply a scaled identity (for a distance function for instance), `LinearAlgebra.I` or any `LinearAlgebra.UniformScaling` can be given.
Note that these parameters can also be automatically detected, but the precision of this detection (which basically requires solving a linear system) soon becomes insufficient for practical purposes when the dimension increases.
See the examples `quadratic.jl` and `quadratic_A.jl` for the exact syntax.
## Miscellaneous
- Emphasis: All solvers support emphasis (parameter `Emphasis`) to either exploit vectorized linear algebra or be memory efficient, e.g., for large-scale instances
- Various caching strategies for the lazy implementations. Unbounded cache sizes (can get slow), bounded cache sizes as well as early returns once any sufficient vertex is found in the cache.
- Optionally all algorithms can be endowed with gradient momentum. This might help convergence especially in the stochastic context.
Coming soon: when the LMO can compute dual prices, then the Frank-Wolfe algorithms will return dual prices for the (approximately) optimal solutions (see [Braun, Pokutta (2021)](https://arxiv.org/abs/2101.02087)).
## Rational arithmetic
Example: `examples/approximateCaratheodory.jl`
We can solve the approximate Carathéodory problem with rational arithmetic to obtain rational approximations; see [Combettes, Pokutta 2019](https://arxiv.org/abs/1911.04415) for some background about approximate Carathéodory and Conditioanl Gradients. We consider the simple instance of approximating the `0` over the probability simplex here:
```math
\min_{x \in \Delta(n)} \|x\|^2
```
with n = 100.
```
Vanilla Frank-Wolfe Algorithm.
EMPHASIS: blas STEPSIZE: rationalshortstep EPSILON: 1.0e-7 max_iteration: 100 TYPE: Rational{BigInt}
───────────────────────────────────────────────────────────────────────────────────
Type Iteration Primal Dual Dual Gap Time
───────────────────────────────────────────────────────────────────────────────────
I 0 1.000000e+00 -1.000000e+00 2.000000e+00 1.540385e-01
FW 10 9.090909e-02 -9.090909e-02 1.818182e-01 2.821186e-01
FW 20 4.761905e-02 -4.761905e-02 9.523810e-02 3.027964e-01
FW 30 3.225806e-02 -3.225806e-02 6.451613e-02 3.100331e-01
FW 40 2.439024e-02 -2.439024e-02 4.878049e-02 3.171654e-01
FW 50 1.960784e-02 -1.960784e-02 3.921569e-02 3.244207e-01
FW 60 1.639344e-02 -1.639344e-02 3.278689e-02 3.326185e-01
FW 70 1.408451e-02 -1.408451e-02 2.816901e-02 3.418239e-01
FW 80 1.234568e-02 -1.234568e-02 2.469136e-02 3.518750e-01
FW 90 1.098901e-02 -1.098901e-02 2.197802e-02 3.620287e-01
Last 1.000000e-02 1.000000e-02 0.000000e+00 4.392171e-01
───────────────────────────────────────────────────────────────────────────────────
0.600608 seconds (3.83 M allocations: 111.274 MiB, 12.97% gc time)
Output type of solution: Rational{BigInt}
```
The solution returned is rational as we can see and in fact the exactly optimal solution:
```
x = Rational{BigInt}[1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100, 1//100]
```
## Large-scale problems
Example: `examples/large_scale.jl`
The package is built to scale well, for those conditional gradients variants that can scale well. For example, Away-Step Frank-Wolfe and Pairwise Conditional Gradients do in most cases _not scale well_ because they need to maintain active sets and maintaining them can be very expensive. Similarly, line search methods might become prohibitive at large sizes. However if we consider scale-friendly variants, e.g., the vanilla Frank-Wolfe algorithm with the agnostic step size rule or short step rule, then these algorithms can scale well to extreme sizes esentially only limited by the amount of memory available. However even for these methods that tend to scale well, allocation of memory itself can be very slow when you need to allocate gigabytes of memory for a single gradient computation.
The package is build to support extreme sizes with a special memory efficient emphasis `emphasis=FrankWolfe.memory`, which minimizes expensive memory allocations and performs as many operations in-place as possible.
Here is an example of a run with 1e9 variables. Each gradient is around 7.5 GB in size. Here is the output of the run broken down into pieces:
```
Size of single vector (Float64): 7629.39453125 MB
Testing f... 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:00:23
Testing grad... 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:00:23
Testing lmo... 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:00:29
Testing dual gap... 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:00:46
Testing update... (Emphasis: blas) 100%|███████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:01:35
Testing update... (Emphasis: memory) 100%|█████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:00:58
──────────────────────────────────────────────────────────────────────────
Time Allocations
────────────────────── ───────────────────────
Tot / % measured: 278s / 31.4% 969GiB / 30.8%
Section ncalls time %tot avg alloc %tot avg
──────────────────────────────────────────────────────────────────────────
update (blas) 10 36.1s 41.3% 3.61s 149GiB 50.0% 14.9GiB
lmo 10 18.4s 21.1% 1.84s 0.00B 0.00% 0.00B
grad 10 12.8s 14.6% 1.28s 74.5GiB 25.0% 7.45GiB
f 10 12.7s 14.5% 1.27s 74.5GiB 25.0% 7.45GiB
update (memory) 10 5.00s 5.72% 500ms 0.00B 0.00% 0.00B
dual gap 10 2.40s 2.75% 240ms 0.00B 0.00% 0.00B
──────────────────────────────────────────────────────────────────────────
```
The above is the optional benchmarking of the oracles that we provide to understand how fast crucial parts of the algorithms are, mostly notably oracle evaluations, the update of the iterate and the computation of the dual gap. As you can see if you compare `update (blas)` vs. `update (memory)`, the normal update when we use BLAS requires an additional 14.9GB of memory on top of the gradient etc whereas the `update (memory)` (the memory emphasis mode) does not consume any extra memory. This is also reflected in the computational times: the BLAS version requires 3.61 seconds on average to update the iterate, while the memory emphasis version requires only 500ms. In fact none of the crucial components in the algorithm consume any memory when run in memory efficient mode. Now let us look at the actual footprint of the whole algorithm:
```
Vanilla Frank-Wolfe Algorithm.
EMPHASIS: memory STEPSIZE: agnostic EPSILON: 1.0e-7 MAXITERATION: 1000 TYPE: Float64
MOMENTUM: nothing GRADIENTTYPE: Nothing
WARNING: In memory emphasis mode iterates are written back into x0!
─────────────────────────────────────────────────────────────────────────────────────────────────
Type Iteration Primal Dual Dual Gap Time It/sec
─────────────────────────────────────────────────────────────────────────────────────────────────
I 0 1.000000e+00 -1.000000e+00 2.000000e+00 8.783523e+00 0.000000e+00
FW 100 1.326732e-02 -1.326733e-02 2.653465e-02 4.635923e+02 2.157068e-01
FW 200 6.650080e-03 -6.650086e-03 1.330017e-02 9.181294e+02 2.178342e-01
FW 300 4.437059e-03 -4.437064e-03 8.874123e-03 1.372615e+03 2.185609e-01
FW 400 3.329174e-03 -3.329180e-03 6.658354e-03 1.827260e+03 2.189070e-01
FW 500 2.664003e-03 -2.664008e-03 5.328011e-03 2.281865e+03 2.191190e-01
FW 600 2.220371e-03 -2.220376e-03 4.440747e-03 2.736387e+03 2.192672e-01
FW 700 1.903401e-03 -1.903406e-03 3.806807e-03 3.190951e+03 2.193703e-01
FW 800 1.665624e-03 -1.665629e-03 3.331253e-03 3.645425e+03 2.194532e-01
FW 900 1.480657e-03 -1.480662e-03 2.961319e-03 4.099931e+03 2.195159e-01
FW 1000 1.332665e-03 -1.332670e-03 2.665335e-03 4.554703e+03 2.195533e-01
Last 1000 1.331334e-03 -1.331339e-03 2.662673e-03 4.559822e+03 2.195261e-01
─────────────────────────────────────────────────────────────────────────────────────────────────
4560.661203 seconds (7.41 M allocations: 112.121 GiB, 0.01% gc time)
```
As you can see the algorithm ran for about 4600 secs (single-thread run) allocating 112.121 GiB of memory throughout. So how does this average out to the per-iteration cost in terms of memory: `112.121 / 7.45 / 1000 = 0.0151` so about 15.1MiB per iteration which is much less than the size of the gradient and in fact only stems from the reporting here.
**NB.** This example highlights also one of the great features of first-order methods and conditional gradients in particular: we have dimension-independent convergence rates. In fact, we contract the primal gap as `2LD^2 / (t+2)` (for the simple agnostic rule) and, e.g., if the feasible region is the probability simplex with `D = sqrt(2)` and the function has bounded Lipschitzness, e.g., the function `|| x - xp ||^2` has `L = 2`, then the convergence rate is completely independent of the input size. The only thing that limits scaling is how much memory you have available and whether you can stomach the (linear) per-iteration cost.
## Iterate and atom expected interface
Frank-Wolfe can work on iterate beyond plain vectors, for example with any array-like object. Broadly speaking, the iterate type is assumed
to behave as the member of a Hilbert space and optionally be mutable. Assuming the iterate type is `IT`, some methods must be implemented, with their usual semantics:
```julia
Base.similar(::IT)
Base.similar(::IT, ::Type{T})
Base.collect(::IT)
Base.size(::IT)
Base.eltype(::IT)
Base.copyto!(dest::IT, src::IT)
Base.:+(x1::IT, x2::IT)
Base.:*(scalar::Real, x::IT)
Base.:-(x1::IT, x2::IT)
LinearAlgebra.dot(x1::IT, x2::IT)
LinearAlgebra.norm(::IT)
```
For methods using an [`FrankWolfe.ActiveSet`](@ref), the atoms or individual extreme points of the feasible region are not necessarily
of the same type as the iterate. They are assumed to be immutable, must implement `LinearAlgebra.dot` with a gradient object.
See for example [`FrankWolfe.RankOneMatrix`](@ref) or [`FrankWolfe.ScaledHotVector`](@ref).
The iterate type `IT` must be a broadcastable mutable object or implement [`FrankWolfe.compute_active_set_iterate!`](@ref):
```julia
FrankWolfe.compute_active_set_iterate!(active_set::FrankWolfe.ActiveSet{AT, R, IT}) where {AT, R}
```
which recomputes the iterate from the current convex decomposition and the following methods
[`FrankWolfe.active_set_update_scale!`](@ref) and [`FrankWolfe.active_set_update_iterate_pairwise!`](@ref):
```julia
FrankWolfe.active_set_update_scale!(x::IT, lambda, atom)
FrankWolfe.active_set_update_iterate_pairwise!(x::IT, lambda, fw_atom, away_atom)
```
## Symmetry reduction
Example: `examples/reynolds.jl`
Suppose that there is a group $G$ acting on the underlying vector space and such that for all $x\in\mathcal{C}$ and $g\in G$
```math
f(g\cdot x)=f(x)\quad\text{and}\quad g\cdot x\in\mathcal{C}.
```
Then, the computations can be performed in the subspace invariant under $G$.
This subspace is the image of the Reynolds operator defined by
```math
\mathcal{R}(x)=\frac{1}{|G|}\sum_{g\in G}g\cdot x.
```
In practice, the type `SymmetricLMO` allows the user to provide the Reynolds operator $\mathcal{R}$ as well as its adjoint $\mathcal{R}^\ast$.
The gradient is symmetrised with $\mathcal{R}^\ast$, then passed to the non-symmetric LMO, and the resulting output is symmetrised with $\mathcal{R}$.
In many cases, the gradient is already symmetric so that `reynolds_adjoint(gradient, lmo) = gradient` is a fast and valid choice.
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 5024 | # How does it work?
`FrankWolfe.jl` contains generic routines to solve optimization problems of the form
```math
\min_{x \in \mathcal{C}} f(x)
```
where $\mathcal{C}$ is a compact convex set and $f$ is a differentiable function.
These routines work by solving a sequence of linear subproblems:
```math
\min_{x \in \mathcal{C}} \langle d_k, x \rangle \quad \text{where} \quad d_k = \nabla f(x_k)
```
## Linear Minimization Oracles
The Linear Minimization Oracle (LMO) is a key component, which is called at each iteration of the FW algorithm. Given a direction $d$, it returns an optimal vertex of the feasible set:
```math
v \in \arg \min_{x\in \mathcal{C}} \langle d,x \rangle.
```
### Custom LMOs
To be used by the algorithms provided here, an LMO must be a subtype of [`FrankWolfe.LinearMinimizationOracle`](@ref) and implement the following method:
```julia
compute_extreme_point(lmo::LMO, direction; kwargs...) -> v
```
This method should minimize $v \mapsto \langle d, v \rangle$ over the set $\mathcal{C}$ defined by the LMO.
Note that this means the set $\mathcal{C}$ doesn't have to be represented explicitly: all we need is to be able to minimize a linear function over it, even if the minimization procedure is a black box.
### Pre-defined LMOs
If you don't want to define your LMO manually, several common implementations are available out-of-the-box:
- Simplices: unit simplex, probability simplex
- Balls in various norms
- Polytopes: K-sparse, Birkhoff
You can use an oracle defined via a Linear Programming solver (e.g. `SCIP` or `HiGHS`) with `MathOptInferface`: see [`FrankWolfe.MathOptLMO`](@ref).
Finally, we provide wrappers to combine oracles easily, for example in a product.
See [Combettes, Pokutta (2021)](https://arxiv.org/abs/2101.10040) for references on most LMOs implemented in the package and their comparison with projection operators.
## Optimization algorithms
The package features several variants of Frank-Wolfe that share the same basic API.
Most of the algorithms listed below also have a lazified version: see [Braun, Pokutta, Zink (2016)](https://arxiv.org/abs/1610.05120).
### Standard Frank-Wolfe (FW)
It is implemented in the [`frank_wolfe`](@ref) function.
See [Jaggi (2013)](http://proceedings.mlr.press/v28/jaggi13.html) for an overview.
This algorithm works both for convex and non-convex functions (use step size rule `FrankWolfe.Nonconvex()` in the second case).
### Away-step Frank-Wolfe (AFW)
It is implemented in the [`away_frank_wolfe`](@ref) function.
See [Lacoste-Julien, Jaggi (2015)](https://arxiv.org/abs/1511.05932) for an overview.
### Stochastic Frank-Wolfe (SFW)
It is implemented in the [`FrankWolfe.stochastic_frank_wolfe`](@ref) function.
### Blended Conditional Gradients (BCG)
It is implemented in the [`blended_conditional_gradient`](@ref) function, with a built-in stability feature that temporarily increases accuracy.
See [Braun, Pokutta, Tu, Wright (2018)](https://arxiv.org/abs/1805.07311).
### Pairwise Frank-Wolfe (PFW)
It is implemented in the [`pairwise_frank_wolfe`](@ref) function.
See [Lacoste-Julien, Jaggi (2015)](https://arxiv.org/abs/1511.05932) for an overview.
### Blended Pairwise Conditional Gradients (BPCG)
It is implemented in the [`FrankWolfe.blended_pairwise_conditional_gradient`](@ref) function, with a minor [modification](https://hackmd.io/@spokutta/B14MTMsLF) to improve sparsity.
See [Tsuji, Tanaka, Pokutta (2021)](https://arxiv.org/abs/2110.12650)
### Comparison
The following table compares the characteristics of the algorithms presented in the package:
| Algorithm | Progress/Iteration | Time/Iteration | Sparsity | Numerical Stability | Active Set | Lazifiable |
| :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| **FW** | Low | Low | Low | High | No | Yes |
| **AFW** | Medium | Medium-High | Medium | Medium-High | Yes | Yes |
| **B(P)CG** | High | Medium-High | High | Medium | Yes | By design |
| **SFW** | Low | Low | Low | High | No | No |
While the standard Frank-Wolfe algorithm can only move _towards_ extreme points of the compact convex set $\mathcal{C}$, Away-step Frank-Wolfe can move _away_ from them. The following figure from our paper illustrates this behaviour:
.
Both algorithms minimize a quadratic function (whose contour lines are depicted) over a simple polytope (the black square). When the minimizer lies on a face, the standard Frank-Wolfe algorithm zig-zags towards the solution, while its Away-step variant converges more quickly.
### Block-Coordinate Frank-Wolfe (BCFW)
It is implemented in the [`FrankWolfe.block_coordinate_frank_wolfe`](@ref) function.
See [Lacoste-Julien, Jaggi, Schmidt, Pletscher (2013)](https://arxiv.org/abs/1207.4747)
and [Beck, Pauwels, Sabach (2015)](https://arxiv.org/abs/1502.03716) for more details about different variants of Block-Coordinate Frank-Wolfe.
### Alternating Linear Minimization (ALM)
It is implemented in the [`FrankWolfe.alternating_linear_minimization`](@ref) function.
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 105 | # API Reference
The pages in this section reference the documentation for specific types and functions.
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 1594 | # Algorithms
This section contains all main algorithms of the package. These are the ones typical users will call.
The typical signature for these algorithms is:
```julia
my_algorithm(f, grad!, lmo, x0)
```
## Standard algorithms
```@autodocs
Modules = [FrankWolfe]
Pages = ["fw_algorithms.jl"]
```
```@docs
FrankWolfe.block_coordinate_frank_wolfe
```
## Active-set based methods
The following algorithms maintain the representation of the iterates
as a convex combination of vertices.
### Away-step
```@autodocs
Modules = [FrankWolfe]
Pages = ["afw.jl"]
```
### Pairwise Frank-Wolfe
```@autodocs
Modules = [FrankWolfe]
Pages = ["pairwise.jl"]
```
### Blended Conditional Gradient
```@autodocs
Modules = [FrankWolfe]
Pages = ["blended_cg.jl"]
```
### Blended Pairwise Conditional Gradient
```@autodocs
Modules = [FrankWolfe]
Pages = ["blended_pairwise.jl"]
```
## Alternating Methods
Problems over intersections of convex sets, i.e.
```math
\min_{x \in \bigcap_{i=1}^n P_i} f(x),
```
pose a challenge as one has to combine the information of two or more LMOs.
[`FrankWolfe.alternating_linear_minimization`](@ref) converts the problem into a series of subproblems over single sets. To find a point within the intersection, one minimizes both the distance to the iterates of the other subproblems and the original objective function.
[`FrankWolfe.alternating_projections`](@ref) solves feasibility problems over intersections of feasible regions.
```@autodocs
Modules = [FrankWolfe]
Pages = ["alternating_methods.jl"]
```
## Index
```@index
Pages = ["2_algorithms.md"]
```
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 1282 | # Linear Minimization Oracles
The Linear Minimization Oracle (LMO) is a key component called at each iteration of the FW algorithm. Given ``d\in \mathcal{X}``, it returns a vertex of the feasible set:
```math
v\in \argmin_{x\in \mathcal{C}} \langle d,x \rangle.
```
See [Combettes, Pokutta 2021](https://arxiv.org/abs/2101.10040) for references on most LMOs
implemented in the package and their comparison with projection operators.
## Interface and wrappers
```@docs
FrankWolfe.LinearMinimizationOracle
```
All of them are subtypes of [`FrankWolfe.LinearMinimizationOracle`](@ref) and implement the following method:
```@docs
compute_extreme_point
```
We also provide some meta-LMOs wrapping another one with extended behavior:
```@docs
FrankWolfe.CachedLinearMinimizationOracle
FrankWolfe.ProductLMO
FrankWolfe.SingleLastCachedLMO
FrankWolfe.MultiCacheLMO
FrankWolfe.VectorCacheLMO
```
## Norm balls
```@autodocs
Modules = [FrankWolfe]
Pages = ["norm_oracles.jl"]
```
## Simplex
```@autodocs
Modules = [FrankWolfe]
Pages = ["simplex_oracles.jl"]
```
## Polytope
```@autodocs
Modules = [FrankWolfe]
Pages = ["polytope_oracles.jl"]
```
## MathOptInterface
```@autodocs
Modules = [FrankWolfe]
Pages = ["moi_oracle.jl"]
```
## Index
```@index
Pages = ["1_lmo.md"]
```
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 2131 | # Utilities and data structures
## Active set
```@autodocs
Modules = [FrankWolfe]
Pages = ["active_set.jl"]
```
## Functions and gradients
```@autodocs
Modules = [FrankWolfe]
Pages = ["function_gradient.jl"]
```
## Callbacks
```@docs
FrankWolfe.CallbackState
```
## Custom vertex storage
## Custom extreme point types
For some feasible sets, the extreme points of the feasible set returned by
the LMO possess a specific structure that can be represented in an efficient
manner both for storage and for common operations like scaling and addition with an iterate. They are presented below:
```@docs
FrankWolfe.ScaledHotVector
FrankWolfe.RankOneMatrix
```
```@autodocs
Modules = [FrankWolfe]
Pages = ["types.jl"]
```
## Utils
```@autodocs
Modules = [FrankWolfe]
Pages = ["utils.jl"]
```
## Oracle counting trackers
The following structures are wrapping given oracles to behave similarly but additionally track the number of calls.
```@docs
FrankWolfe.TrackingObjective
FrankWolfe.TrackingGradient
FrankWolfe.TrackingLMO
```
Also see the example [Tracking, counters and custom callbacks for Frank Wolfe](@ref).
## Update order for block-coordinate methods
Block-coordinate methods can be run with different update orders. All update orders are subtypes of [`FrankWolfe.BlockCoordinateUpdateOrder`](@ref). They have to implement the method [`FrankWolfe.select_update_indices`](@ref) which selects which blocks to update in what order.
```@docs
FrankWolfe.BlockCoordinateUpdateOrder
FrankWolfe.select_update_indices
FrankWolfe.FullUpdate
FrankWolfe.CyclicUpdate
FrankWolfe.StochasticUpdate
```
## Update step for block-coordinate Frank-Wolfe
Block-coordinate Frank-Wolfe (BCFW) can run different FW algorithms on different blocks. All update steps are subtypes of [`FrankWolfe.UpdateStep`](@ref) and implement [`FrankWolfe.update_iterate`](@ref) which defines one iteration of the corresponding method.
```@docs
FrankWolfe.UpdateStep
FrankWolfe.update_iterate
FrankWolfe.FrankWolfeStep
FrankWolfe.BPCGStep
```
## Block vector
```@docs
FrankWolfe.BlockVector
```
## Index
```@index
Pages = ["3_backend.md"]
```
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 0.4.1 | 6efeb9baf0fbec3f91d1cb985b8a7eb4151c446f | docs | 1585 | # Line search and step size settings
The step size dictates how far one traverses along a local descent direction.
More specifically, the step size $\gamma_t$ is used at each iteration to determine
how much the next iterate moves towards the new vertex:
```math
x_{t+1} = x_t - \gamma_t (x_t - v_t).
```
``\gamma_t = 1`` implies that the next iterate is exactly the vertex,
a zero $\gamma_t$ implies that the iterate is not moving.
The following are step size selection rules for Frank Wolfe algorithms.
Some methodologies (e.g. `FixedStep` and `Agnostic`) depend only on the iteration number and induce series $\gamma_t$
that are independent of the problem data,
while others (e.g. `GoldenSearch` and `Adaptive`) change according
to local information about the function; the adaptive methods
often require extra function and/or gradient computations. The
typical options for convex optimization are `Agnostic` or `Adaptive`.
All step size computation strategies are subtypes of [`FrankWolfe.LineSearchMethod`](@ref).
The key method they have to implement is [`FrankWolfe.perform_line_search`](@ref)
which is called at every iteration to compute the step size gamma.
```@docs
FrankWolfe.LineSearchMethod
FrankWolfe.perform_line_search
```
```@autodocs
Modules = [FrankWolfe]
Pages = ["linesearch.jl"]
```
See [Pedregosa, Negiar, Askari, Jaggi (2020)](https://arxiv.org/abs/1806.05123)
for the adaptive step size,
[Carderera, Besançon, Pokutta (2021)](https://openreview.net/forum?id=rq_UD6IiBpX)
for the monotonic step size.
## Index
```@index
Pages = ["4_linesearch.md"]
```
| FrankWolfe | https://github.com/ZIB-IOL/FrankWolfe.jl.git |
|
[
"MIT"
] | 1.1.0 | a54a7925b96f109de91094ef83e2ebd3f72a593a | code | 12684 | module WoodburyFactorizations
using LinearAlgebra
using LinearAlgebra: checksquare
include("util.jl")
# IDEA: can optimize threshold constant c which makes Woodbury Identity computationally advantageous over direct factorization
using LazyInverses
const AbstractMatOrFac{T} = Union{AbstractMatrix{T}, Factorization{T}}
const DTYPE = Float64 # default data type
export Woodbury, WoodburyFactorization
# represents A + αUCV
# things that prevent C from being a scalar: checkdims, factorize, ...
# the α is beneficial to preserve p.s.d.-ness during inversion (see inverse)
struct WoodburyFactorization{T, AT, UT, CT, VT, F, L, TT} <: Factorization{T}
A::AT
U::UT
C::CT
V::VT
α::F # scalar, TODO: test if not ±1
logabsdet::L
temporaries::TT
end
const Woodbury = WoodburyFactorization
function Woodbury(A::AbstractMatOrFac, U::AbstractMatOrFac,
C::AbstractMatOrFac, V::AbstractMatOrFac,
α::Real = 1, logabsdet::Union{NTuple{2, Real}, Nothing} = nothing,
temporaries = allocate_temporaries(U, V);
check::Bool = true)
(α == 1 || α == -1) || throw(DomainError("α ≠ ±1 not yet tested: α = $α"))
check && checkdims(A, U, C, V)
T = promote_type(typeof(α), eltype.((A, U, C, V))...) # check promote_type
F = typeof(α)
AT, UT, CT, VT, LT = typeof.((A, U, C, V, logabsdet))
TT = typeof(temporaries)
Woodbury{T, AT, UT, CT, VT, F, LT, TT}(A, U, C, V, α, logabsdet, temporaries)
end
function Woodbury(A::AbstractMatOrFac, U::AbstractVector,
C::Real, V::Adjoint{<:Any, <:AbstractVector}, α::Real = 1,
logabsdet::Union{NTuple{2, Real}, Nothing} = nothing,
temporaries = allocate_temporaries(U, V);
check::Bool = true)
(α == 1 || α == -1) || throw(DomainError("α ≠ ±1 not yet tested: α = $α"))
check && checkdims(A, U, C, V)
T = promote_type(typeof(α), eltype.((A, U, C, V))...) # check promote_type
F = typeof(α)
AT, UT, CT, VT, LT = typeof.((A, U, C, V, logabsdet))
TT = typeof(temporaries)
Woodbury{T, AT, UT, CT, VT, F, LT, TT}(A, U, C, V, α, logabsdet, temporaries)
end
const RankOneCorrection = Woodbury{<:Any, <:Any, <:AbstractVector, <:Any, <:Adjoint{<:Any, <:AbstractVector}}
# casts all inputs to an equivalent Matrix
matrix(x::Real) = fill(x, (1, 1)) # could in principle extend Matrix
matrix(x::AbstractVector) = reshape(x, (:, 1))
matrix(x::Adjoint{<:Any, <:AbstractVector}) = reshape(x, (1, :))
matrix(x::AbstractMatOrFac) = x
function Woodbury(A, U, C, V, α::Real = 1, abslogdet = nothing)
Woodbury(matrix.((A, U, C, V))..., α, abslogdet)
end
# low rank correction
# NOTE: cannot rid of type restriction on A without introducing ambiguities
function Woodbury(A::AbstractMatOrFac, U::AbstractVector, V::Adjoint = U',
α::Real = 1, logabsdet = nothing)
T = eltype(A)
Woodbury(A, U, one(T), V, α, logabsdet)
end
function Woodbury(A::AbstractMatOrFac, U::AbstractMatrix, V::AbstractMatrix = U',
α::Real = 1, logabsdet = nothing)
T = eltype(A)
Woodbury(A, U, (one(T)*I)(size(U, 2)), V, α, logabsdet)
end
# function Woodbury(A, L::LowRank, α::Real = 1, logabsdet = nothing)
# Woodbury(A, L.U, 1.0I(size(L.U, 2)), L.V, α, logabsdet)
# end
function Woodbury(A, C::CholeskyPivoted, α::Real = 1, logabsdet = nothing)
U = C.U[1:C.rank, invperm(C.p)]
Woodbury(A, U', U, α, logabsdet)
end
LinearAlgebra.checksquare(::Number) = 1 # since size(::Number, ::Int) = 1
# checks if the dimensions of A, U, C, V are consistent to form a Woodbury factorization
function checkdims(A, U, C, V)
n, m = A isa Number ? (1, 1) : size(A)
k, l = C isa Number ? (1, 1) : size(C)
s = "is inconsistent with A ($(size(A))) and C ($(size(C)))"
!(size(U, 1) == n && size(U, 2) == k) && throw(DimensionMismatch("Size of U ($(size(U))) "*s))
!(size(V, 1) == l && size(V, 2) == m) && throw(DimensionMismatch("Size of V ($(size(V))) "*s))
return true
end
# pseudo-constructor?
# c is used to set threshold for conversion to Matrix
function woodbury(A, U, C, V, α = 1, c::Real = 1)
W = Woodbury(A, U, C, V, α)
# only return Woodbury if it is efficient
if size(W.C, 1) ≥ c * size(W.U, 1) || size(W.C, 2) ≥ c * size(W.V, 2)
W = Matrix(W)
end
return W
end
################################## Base ########################################
Base.size(W::Woodbury) = size(W.A)
Base.size(W::Woodbury, d) = size(W.A, d)
Base.eltype(W::Woodbury{T}) where {T} = T
function Base.AbstractMatrix(W::Woodbury)
Matrix(W.A) + W.α * *(W.U, W.C, W.V)
end
Base.Matrix(W::Woodbury) = AbstractMatrix(W)
function Base.copy(W::Woodbury)
U = copy(W.U)
V = W.U ≡ W.V' ? U' : copy(W.V)
t = tuple(copy.(W.temporaries)...)
Woodbury(copy(W.A), U, copy(W.C), V, W.α, W.logabsdet, t)
end
function Base.deepcopy(W::Woodbury)
U = deepcopy(W.U)
V = W.U ≡ W.V' ? U' : deepcopy(W.V)
t = tuple(deepcopy.(W.temporaries)...)
Woodbury(deepcopy(W.A), U, deepcopy(W.C), V, W.α, W.logabsdet, t)
end
Base.inv(W::Woodbury) = inv(factorize(W))
function Base.isequal(W1::Woodbury, W2::Woodbury)
W1.A == W2.A && W1.U == W2.U && W1.C == W2.C && W1.V == W2.V && W1.α == W2.α
end
# sufficient but not necessary condition, useful for quick check
_ishermitian(A::Union{Real, AbstractMatOrFac}) = ishermitian(A)
function _ishermitian(W::Woodbury)
try
(W.U ≡ W.V' || W.U == W.V') && _ishermitian(W.A) && _ishermitian(W.C)
catch e
return false
end
end
# if efficiently-verifiable sufficient condition fails, check matrix
LinearAlgebra.ishermitian(W::Woodbury) = _ishermitian(W) || ishermitian(Matrix(W))
LinearAlgebra.issymmetric(W::Woodbury) = eltype(W) <: Real && ishermitian(W)
function LinearAlgebra.isposdef(W::Woodbury)
W.logabsdet isa Nothing ? isposdef(factorize(W)) : (W.logabsdet[2] > 0)
end
function LinearAlgebra.adjoint(W::Woodbury)
ishermitian(W) ? W : Woodbury(W.A', W.V', W.C', W.U', W.α, W.logabsdet)
end
function LinearAlgebra.transpose(W::Woodbury)
issymmetric(W) ? W : Woodbury(transpose.((W.A, W.V, W.C, W.U))..., W.α, W.logabsdet)
end
# indexed by two integers returns scalar
function Base.getindex(W::Woodbury, i, j)
Ui = i isa Integer ? W.U[i, :]' : W.U[i, :]
W.A[i, j] + W.α * *(Ui, W.C, W.V[:, j])
end
# indexed by two vectors other, returns woodbury
function Base.getindex(W::Woodbury, i::AbstractVector, j::AbstractVector)
A = W.A[i, j]
U = W.U[i, :]
V = W.U ≡ W.V' && i == j ? U' : W.V[:, j]
return Woodbury(A, U, W.C, V, W.α, nothing)
end
# WARNING: result of view references existing temporaries and is therefore not thread-safe
function Base.view(W::Woodbury, i, j)
A = view(W.A, i, j)
U = view(W.U, i, :)
V = W.U ≡ W.V' && i == j ? U' : view(W.V, :, j)
return Woodbury(A, U, W.C, V, W.α, nothing, W.temporaries)
end
function LinearAlgebra.tr(W::Woodbury)
n = checksquare(W)
trace_UCV = zero(eltype(W))
for i in 1:n
ui = @view W.U[i, :]
vi = @view W.V[:, i]
trace_UCV += dot(ui, W.C, vi)
end
return tr(W.A) + W.α * trace_UCV
end
######################## Linear Algebra primitives #############################
# IDEA: have efficient methods of hermitian WoodburyFactorization
Base.:*(a::Number, W::Woodbury) = Woodbury(a * W.A, W.U, a * W.C, W.V, W.α) # IDEA: could take over logabsdet efficiently
Base.:*(W::Woodbury, a::Number) = a * W
Base.:\(a::Number, W::Woodbury) = W / a # IDEA: could take over logabsdet efficiently
Base.:/(W::Woodbury, a::Number) = Woodbury(W.A / a, W.U, W.C / a, W.V, W.α)
Base.:*(W::Woodbury, x::AbstractVecOrMat) = mul!(zero(x), W, x)
Base.:*(B::AbstractMatrix, W::Woodbury) = adjoint(W'*B')
function LinearAlgebra.mul!(y::AbstractVector, W::Woodbury, x::AbstractVector, α::Real = 1, β::Real = 0)
s, t = get_temporaries(W, x)
mul!!(y, W, x, α, β, s, t)
end
function LinearAlgebra.mul!(y::AbstractMatrix, W::Woodbury, x::AbstractMatrix, α::Real = 1, β::Real = 0)
s, t = get_temporaries(W, x)
mul!!(y, W, x, α, β, s, t) # Pre-allocate!
end
# allocates s, t arrays for multiplication if not pre-allocated in W
function allocate_temporaries(W::Woodbury, T::DataType = eltype(W))
allocate_temporaries(W.U, W.V, T)
end
function allocate_temporaries(W::Woodbury, n::Int, T::DataType = eltype(W))
allocate_temporaries(W.U, W.V, n, T)
end
function allocate_temporaries(U, V, T::DataType = promote_type(eltype(U), eltype(V)))
allocate_temporaries(size(U, 2), size(V, 1), T)
end
function allocate_temporaries(U, V, n::Int, T::DataType = promote_type(eltype(U), eltype(V)))
allocate_temporaries(size(U, 2), size(V, 1), n, T)
end
function allocate_temporaries(nu::Int, nv::Int, T::DataType = DTYPE)
s = zeros(T, nv)
t = zeros(T, nu)
return s, t
end
function allocate_temporaries(nu::Int, nv::Int, n::Int, T::DataType = DTYPE)
s = zeros(T, nv, n)
t = zeros(T, nv, n)
return s, t
end
function get_temporaries(W::Woodbury, x::AbstractVector)
T = promote_type(eltype(x), eltype(W))
W.temporaries isa Tuple{<:AbstractVector{T}} ? W.temporaries : allocate_temporaries(W, eltype(x))
end
function get_temporaries(W::Woodbury, X::AbstractMatrix)
T = promote_type(eltype(X), eltype(W))
W.temporaries isa Tuple{<:AbstractMatrix{T}} ? W.temporaries : allocate_temporaries(W, size(X, 2), eltype(X))
end
function mul!!(y::AbstractVecOrMat, W::Woodbury, x::AbstractVecOrMat, α::Real, β::Real, s, t)
mul!(s, W.V, x)
mul!(t, W.C, s)
mul!(y, W.U, t, α * W.α, β)
mul!(y, W.A, x, α, 1) # this allocates if D is diagonal due to broadcasting mechanism
end
# special case: rank one correction does not need additional temporaries for MVM
function LinearAlgebra.mul!(y::AbstractVector, W::RankOneCorrection, x::AbstractVector, α::Real = 1, β::Real = 0)
s = dot(W.V', x)
t = W.C * s
@. y = (α * W.α) * W.U * t + β * y
mul!(y, W.A, x, α, 1)
end
# ternary dot
function LinearAlgebra.dot(x::AbstractVecOrMat, W::Woodbury, y::AbstractVector)
Ux = W.U'x # memory allocation can be avoided (with lazy arrays?)
Vy = (x ≡ y && W.U ≡ W.V') ? Ux : W.V*y
dot(x, W.A, y) + W.α * dot(Ux, W.C, Vy)
end
# ternary mul
function Base.:*(x::AbstractMatrix, W::Woodbury, y::AbstractVecOrMat)
xU = x*W.U
Vy = (x ≡ y' && W.U ≡ W.V') ? xU' : W.V*y
*(x, W.A, y) + W.α * *(xU, W.C, Vy) # can avoid two temporaries
end
Base.:(\)(W::Woodbury, B::AbstractVector) = factorize(W)\B
Base.:(\)(W::Woodbury, B::AbstractMatrix) = factorize(W)\B
Base.:(/)(B::AbstractMatrix, W::Woodbury) = B/factorize(W)
function LinearAlgebra.diag(W::Woodbury)
n = checksquare(W)
d = zeros(eltype(W), n)
for i in 1:n
d[i] = W[i, i]
end
return d
end
########################## Matrix inversion lemma ##############################
# figure out constant c for which woodbury is most efficient
# could implement this in WoodburyMatrices and PR
function LinearAlgebra.factorize(W::Woodbury, c::Real = 1,
compute_logdet::Val{T} = Val(true)) where T
checksquare(W)
if size(W.U, 1) < c*size(W.U, 2)
return factorize(AbstractMatrix(W))
else # only use Woodbury identity when it is beneficial to do so
A = factorize(W.A)
A⁻¹ = inverse(A)
A⁻¹U = A⁻¹ * W.U
VA⁻¹ = (W.U ≡ W.V' && ishermitian(A⁻¹)) ? A⁻¹U' : W.V * A⁻¹
D = factorize_D(W, W.V*A⁻¹U)
if T
l, s = _logabsdet(A, W.C, D, W.α)
W_logabsdet = (-l, s) # -l since the result is packaged in an inverse
else
W_logabsdet = nothing
end
α = -W.α # switch sign
return inverse(Woodbury(A⁻¹, A⁻¹U, inverse(D), VA⁻¹, α, W_logabsdet))
end
end
##################### conveniences for D = C⁻¹ ± V*A⁻¹*U ########################
compute_D(W::Woodbury) = compute_D!(W, *(W.V, inverse(W.A), W.U))
function compute_D!(W::Woodbury, VAU)
invC = inv(W.C) # because we need the dense inverse matrix
@. VAU = invC + W.α * VAU # could be made more efficient with 5 arg mul
end
compute_D!(W::Woodbury, VAU::Real) = inv(W.C) + W.α * VAU
factorize_D(W::Woodbury) = factorize_D(W, *(W.V, inverse(W.A), W.U))
function factorize_D(W::Woodbury, VAU)
D = compute_D!(W, VAU)
if size(D) == (1, 1)
return D
elseif _ishermitian(W)
try return cholesky(Hermitian(D)) catch end
end
return factorize(D)
end
######################## Matrix determinant lemma ##############################
# if W.A = W.C = I, this is Sylvesters determinant theorem
# Determinant lemma for A + α*(UCV)
function LinearAlgebra.det(W::Woodbury)
l, s = logabsdet(W)
exp(l) * s
end
function LinearAlgebra.logdet(W::Woodbury)
l, s = logabsdet(W)
return s > 0 ? l : throw(DomainError("determinant negative: $(exp(l) * s)"))
end
function LinearAlgebra.logabsdet(W::Woodbury)
W.logabsdet == nothing ? logabsdet(factorize(W)) : W.logabsdet
end
function _logabsdet(A, C, D, α::Real)
n, m = checksquare(A), checksquare(D)
la, sa = logabsdet(A)
lc, sc = logabsdet(C)
ld, sd = logabsdet(D)
sα = (α == -1) && isodd(m) ? -1 : 1
return +(la, lc, ld), *(sa, sc, sd, sα)
end
end # WoodburyFactorizations
| WoodburyFactorizations | https://github.com/SebastianAment/WoodburyFactorizations.jl.git |
|
[
"MIT"
] | 1.1.0 | a54a7925b96f109de91094ef83e2ebd3f72a593a | code | 477 | function Base.Matrix(F::BunchKaufman)
U = F.U[:, F.ipiv]
*(U, F.D, U')
end
Base.AbstractMatrix(F::BunchKaufman) = Matrix(F)
function LinearAlgebra.rdiv!(X::AbstractMatrix, F::BunchKaufman)
# ldiv!(F, X')' # doesn't work since X' does not count as strided vector (requirement for ldiv!)
X .= adjoint(F \ X')
end
LinearAlgebra.logdet(B::Bidiagonal) = logabsdet(B)[1]
function LinearAlgebra.logabsdet(B::Bidiagonal)
d = @view B[diagind(B)]
D = Diagonal(d)
logabsdet(D)
end
| WoodburyFactorizations | https://github.com/SebastianAment/WoodburyFactorizations.jl.git |
|
[
"MIT"
] | 1.1.0 | a54a7925b96f109de91094ef83e2ebd3f72a593a | code | 1936 | module WoodburyBenchmarks
using LinearAlgebra
using BenchmarkTools
using WoodburyFactorizations
using WoodburyFactorizations: Woodbury
# TODO: benchmark factorize against factorize without logdet computation
# TODO: figure out parameter c in WoodburyFactorizations, which
# TODO: benchmark pre-allocated solve, mul!
function judge_allocated_multiply(n = 64, m = 3)
suite = BenchmarkGroup()
U = randn(n, m)
W = Woodbury(I(n), U, I(m), U')
# factorization
x = randn(n)
F = factorize(W)
# suite["solve"] = @benchmarkable $F \ $x
suite["multiply"] = @benchmarkable $W * $x
# suite["ternary dot"] = @benchmarkable dot($x, $W, $x)
return suite
end
# controls when the Woodbury representation is more efficient than dense
function woodbury(n = 64, m = 3)
suite = BenchmarkGroup()
U = randn(n, m)
W = Woodbury(I(n), U, I(m), U')
# factorization
suite["factorize"] = @benchmarkable factorize($W)
x = randn(n)
F = factorize(W)
suite["solve"] = @benchmarkable $F \ $x
suite["multiply"] = @benchmarkable $W * $x
suite["ternary dot"] = @benchmarkable dot($x, $W, $x)
suite["logdet"] = @benchmarkable logdet($W)
return suite
end
######## to compare
function dense(n = 64, m = 3)
suite = BenchmarkGroup()
U = randn(n, m)
W = Woodbury(I(n), U, I(m), U')
MW = Matrix(W)
suite["factorize"] = @benchmarkable factorize($MW)
MWF = factorize(MW)
x = randn(n)
suite["solve"] = @benchmarkable $MWF \ $x
suite["multiply"] = @benchmarkable $MW * $x
suite["ternary dot"] = @benchmarkable dot($x, $MW, $x)
suite["logdet"] = @benchmarkable logdet($MW)
return suite
end
# comparing Woodbury identity to dense matrix algebra
function wood_vs_dense(n = 64, m = 3)
wsuite = woodbury(n, m)
wr = run(wsuite)
dsuite = dense(n, m)
dr = run(dsuite)
judge(minimum(wr), minimum(dr))
end
end # WoodburyBenchmarks
| WoodburyFactorizations | https://github.com/SebastianAment/WoodburyFactorizations.jl.git |
|
[
"MIT"
] | 1.1.0 | a54a7925b96f109de91094ef83e2ebd3f72a593a | code | 5267 | module TestWoodburyFactorizations
using WoodburyFactorizations
using LazyInverses
using LinearAlgebra
using Test
function getW(n, m; diagonal = true, symmetric = false)
A = diagonal ? Diagonal(exp.(.1randn(n))) + I(n) : randn(n, n)
A = symmetric && !diagonal ? A'A : A
U = randn(n, m)
C = diagonal ? Diagonal(exp.(.1randn(m))) + I(m) : randn(m, m)
C = symmetric && !diagonal ? C'C : C
V = symmetric ? U' : randn(m, n)
W = Woodbury(A, U, C, V)
end
Base.AbstractMatrix(F::BunchKaufman) = Symmetric(Matrix(F))
@testset "Woodbury" begin
n = 5
m = 2
W = getW(n, m, symmetric = true)
MW = Matrix(W)
@test size(W) == (n, n)
x = randn(size(W, 2))
# multiplication
@test W*x ≈ MW*x
@test x'W ≈ x'MW
@test dot(x, W, x) ≈ dot(x, MW*x)
X = randn(size(W, 2), 3)
@test W*X ≈ MW*X
@test X'*W ≈ X'*MW
@test W == copy(W) # testing isequal and copy
@test W == deepcopy(W) # testing isequal and deepcopy
# in-place multiplication
y = randn(size(W, 1)) # with vector
α, β = randn(2)
b = α*(W*x) + β*y
mul!(y, W, x, α, β)
@test y ≈ b
Y = randn(size(W, 1), size(X, 2)) # with matrix
α, β = randn(2)
B = α*(W*X) + β*Y
mul!(Y, W, X, α, β)
@test Y ≈ B
@test α*W isa Woodbury
@test Matrix(α * W) ≈ α * Matrix(W) # with scalar
@test Matrix(W * α) ≈ Matrix(W) * α # with scalar
@test Matrix(W / α) ≈ Matrix(W) / α # with scalar
@test Matrix(α \ W) ≈ α \ Matrix(W) # with scalar
@test logdet(abs(α)*W) ≈ logdet(abs(α)*Matrix(W)) # checking that logdet works correctly
@test eltype(W) == Float64
@test issymmetric(W)
@test ishermitian(W)
# @test ishermitian(MW)
# @test ishermitian(Woodbury(W.A, W.U, W.C, copy(W.U)')) # testing edge case
@test !issymmetric(getW(n, m))
@test !ishermitian(getW(n, m))
# test solves
@test W\(W*x) ≈ x
@test (x'*W)/W ≈ x'
# factorization
n = 1024
m = 3
W = getW(n, m, symmetric = true)
MW = Matrix(W)
F = factorize(W)
@test F isa Inverse
x = randn(n)
@test W \ x ≈ F \ x
@test MW \ x ≈ F \ x
n = 4
m = 3
W = getW(n, m, symmetric = true)
MW = Matrix(W)
## determinant
@test det(W) ≈ det(MW)
@test logdet(W) ≈ logdet(MW)
@test logabsdet(W)[1] ≈ logabsdet(MW)[1]
@test logabsdet(W)[2] ≈ logabsdet(MW)[2]
@test det(inverse(W)) ≈ det(Inverse(W))
@test det(inverse(W)) ≈ det(inv(MW))
@test logdet(inverse(W)) ≈ logdet(Inverse(W))
@test logdet(inverse(W)) ≈ logdet(inv(MW))
@test all(logabsdet(inverse(W)) .≈ logabsdet(Inverse(W)))
@test all(logabsdet(inverse(W)) .≈ logabsdet(inv(MW)))
# indexing
for i in 1:n, j in 1:n
@test W[i, j] ≈ MW[i, j]
end
i = 1:2
j = 3:3
Wij = W[i, j]
@test Wij isa Woodbury
@test Wij[1, 1] == W[1, 3]
Wij = @view W[i, j]
@test Wij isa Woodbury
@test Wij.U isa SubArray
# trace
@test tr(W) ≈ tr(MW)
# factorize
F = factorize(W)
@test Matrix(inverse(F)) ≈ inv(MW)
@test inv(W) ≈ inv(MW)
@test logdet(F) ≈ logdet(MW)
@test isposdef(F)
# factorize and logdet after factorization
F = factorize(W)
@test logabsdet(F)[1] ≈ logabsdet(MW)[1]
@test logabsdet(F)[2] ≈ logabsdet(MW)[2]
@test logdet(F) ≈ logdet(MW)
@test Matrix(inverse(F)) ≈ inv(MW)
# test recursive stacking of woodbury objects
b = randn(n, 1)
W2 = Woodbury(W, b, ones(1, 1), b')
F2 = factorize(W2)
M2 = Matrix(W2)
@test logdet(W2) ≈ logdet(M2)
@test logdet(F2) ≈ logdet(M2)
# test factorize_D behavior on non-hermitian 1x1 matrix
using WoodburyFactorizations: factorize_D
FD = factorize_D(W2, fill(-rand(), (1, 1)))
@test FD isa Matrix
@test size(FD) == (1, 1)
# test rank 1 constructor
x = randn(n)
A = Diagonal(2 .+ exp.(randn(n)))
u = randn(n)
W = Woodbury(A, u)
@test Matrix(W) ≈ A + u*u'
b = W*x
@test W \ b ≈ x
v = randn(n)
W = Woodbury(A, u, v')
@test Matrix(W) ≈ A + u*v'
b = W*x
@test W \ b ≈ x
# LowRank constructor
U = randn(n, 1)
W = Woodbury(I(n), U, U')
# CholeskyPivoted constructor
A = randn(1, n)
A = A'A
C = cholesky(A, RowMaximum(), check = false)
W = Woodbury(A, C)
@test W isa Woodbury
@test Matrix(W) ≈ 2A
# tests with α = -
W = Woodbury(I(n), C, -1)
# display(W)
@test Matrix(W) ≈ I(n) - A
@test inv(W) ≈ inv(I(n) - A)
FW = factorize(W)
@test FW isa Inverse
@test Matrix(FW) ≈ I(n) - A
@test Matrix(inverse(FW)) ≈ inv(I(n) - A)
MW = I(n) - A
# indexing
for i in 1:n, j in 1:n
@test W[i, j] ≈ MW[i, j]
end
@test tr(W) ≈ tr(MW)
@test diag(W) ≈ diag(MW)
# Woodbury structure with 1d outer dimension
a, b, c, d = randn(4)
W = Woodbury(a, b, c, d)
MW = Matrix(W)
@test size(MW) == (1, 1)
@test MW[1, 1] ≈ a + *(b, c, d)
a = randn()
B = randn(1, n)
C = randn(n, n)
D = randn(n, 1)
W = Woodbury(a, B, C, D)
MW = Matrix(W)
@test size(MW) == (1, 1)
@test MW[1, 1] ≈ a + dot(B, C, D)
@test inv(W) isa Real
@test factorize(W) isa Real
end
end # TestWoodburyFactorizations
| WoodburyFactorizations | https://github.com/SebastianAment/WoodburyFactorizations.jl.git |
|
[
"MIT"
] | 1.1.0 | a54a7925b96f109de91094ef83e2ebd3f72a593a | code | 39 | include("./WoodburyFactorizations.jl")
| WoodburyFactorizations | https://github.com/SebastianAment/WoodburyFactorizations.jl.git |
|
[
"MIT"
] | 1.1.0 | a54a7925b96f109de91094ef83e2ebd3f72a593a | docs | 405 | # WoodburyFactorizations.jl
[](https://github.com/SebastianAment/WoodburyFactorizations.jl/actions/workflows/CI.yml)
[](https://codecov.io/gh/SebastianAment/WoodburyFactorizations.jl)
| WoodburyFactorizations | https://github.com/SebastianAment/WoodburyFactorizations.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 855 | using Documenter, WiNDC, GamsStructure, PATHSolver
const _PAGES = [
"Introduction" => ["index.md"],
"Data" => ["data/core.md"],
"Core Module" => ["core/overview.md","core/national_model.md","core/national_set_list.md","core/state_model.md","core/set_listing.md"]
]
makedocs(
sitename="WiNDC.jl",
authors="WiNDC",
#format = Documenter.HTML(
# # See https://github.com/JuliaDocs/Documenter.jl/issues/868
# prettyurls = get(ENV, "CI", nothing) == "true",
# analytics = "UA-44252521-1",
# collapselevel = 1,
# assets = ["assets/extra_styles.css"],
# sidebar_sitename = false,
#),
#strict = true,
pages = _PAGES
)
deploydocs(
repo = "https://github.com/uw-windc/WiNDC.jl",
target = "build",
branch = "gh-pages",
versions = ["stable" => "v^", "v#.#" ],
) | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 923 | module WiNDC
using JuMP
using PATHSolver
using Ipopt
using GamsStructure
using CSV
using XLSX
using DataFrames
using HTTP
using JSON
export generate_report
export national_model_mcp, national_model_mcp_year,
state_disaggregation_model_mcp,state_disaggregation_model_mcp_year
export load_national_data,load_state_data
include("helper_functions.jl")
include("data/notations.jl")
include("data/core/bea_api/bea_api.jl")
#Models
include("core/nationalmodel.jl")
include("core/state_disaggregation_model.jl")
#Data
include("data/core/core_data_defines.jl")
include("data/core/bea_io/PartitionBEA.jl")
include("data/core/bea_gsp/bea_gsp.jl")
include("data/core/bea_pce/bea_pce.jl")
include("data/core/census_sgf/census_sgf.jl")
include("data/core/faf/faf.jl")
include("data/core/usa_trade/usa_trade.jl")
include("data/core/state_disaggregation.jl")
include("data/core/core_data.jl")
end # module WiNDC
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 646 | extract_variable_ref(v::NonlinearExpr) = v.args[1]
extract_variable_ref(v::AffExpr) = collect(keys(v.terms))[1]
extract_variable_ref(v::QuadExpr) = extract_variable_ref(v.aff)
function generate_report(m::JuMP.Model)
out = []
#mapping = Dict()
for ci in all_constraints(m; include_variable_in_set_constraints = false)
c = constraint_object(ci)
var = extract_variable_ref(c.func[2])
val = value(var)
margin = value(c.func[1])
push!(out,(var,val,margin))
#mapping[extract_variable_ref(c.func[2])] = c.func[1]
end
df = DataFrame(out,[:var,:value,:margin])
return df
end
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 8968 |
m = Model(PATHSolver.Optimizer)
@variables(m,begin
# $sectors:
Y[G,R,S]>=0 # Production (includes I and G)
C[R,S,H]>=0 # Consumption
X[I,R,S]>=0 # Disposition
Z[I,R,S]>=0 # Armington demand
FT[F,R,S]>=0 # Specific factor transformation
M[I,R]>=0 # Import
YT[J]>=0 # Transport
# $commodities:
PY[G,R,S]>=0 # Output price
PZ[I,R,S]>=0 # Armington composite price
PD[I,R,S]>=0 # Local goods price
P[I,R]>=0 # National goods price
PC[R,S,H]>=0 # Consumption price
PF[F,R,S]>=0 # Primary factors rent
PS[F,G,R,S]>=0 # Sector-specific primary factors
PM[I,R]>=0 # Import price
PT[J]>=0 # Transportation services
# $consumer:
RH[R,S,H]>=0 # Representative household
GOVT[R]>=0 # Public expenditure
INV[R]>=0 # Investment
end)
theta_pl_y_va = GamsParameter(GU, (:r,:s), "Labor value share")
theta_PFX_X = GamsParameter(GU, (:r,:g), "Export value share")
theta_PN_X = GamsParameter(GU, (:r,:g), "National value share")
theta_PD_X = GamsParameter(GU, (:r,:g), "Domestic value share")
theta_PN_A_d = GamsParameter(GU, (:r,:g), "National value share in nest d")
theta_PFX_A_dm = GamsParameter(GU, (:r,:g), "Imported value share in nest dm")
thetac = GamsParameter(GU, (:r,:g,:h), "Consumption value share")
betaks = GamsParameter(GU, (:r,:s), "Capital supply value share")
theta_PC_RA = GamsParameter(GU, (:r,:h), "Value share of PC in RA")
#=
theta_pl_y_va[:r,:s]$ld0[:r,:s] = ld0[:r,:s]/(ld0[:r,:s]+kd0[:r,:s]*(1+tk0[:r]))
theta_PFX_X[:r,:g]$x_[:r,:g] = (x0[:r,:g]-rx0[:r,:g])/(x0[:r,:g]-rx0[:r,:g] + xn0[:r,:g] + xd0[:r,:g])
theta_PN_X[:r,:g]$x_[:r,:g] = xn0[:r,:g]/(x0[:r,:g]-rx0[:r,:g] + xn0[:r,:g] + xd0[:r,:g])
theta_PD_X[:r,:g]$x_[:r,:g] = xd0[:r,:g]/(x0[:r,:g]-rx0[:r,:g] + xn0[:r,:g] + xd0[:r,:g])
theta_PN_A_d[:r,:g]$a_[:r,:g] = nd0[:r,:g]/(nd0[:r,:g]+dd0[:r,:g])
theta_PFX_A_dm[:r,:g]$a_[:r,:g] = m0[:r,:g]*(1+tm0[:r,:g])/(m0[:r,:g]*(1+tm0[:r,:g])+nd0[:r,:g]+dd0[:r,:g])
thetac[:r,:g,:h] = cd0_h[:r,:g,:h]/sum(cd0_h[:r,[g],:h] for g in G)
betaks[:r,:s] = kd0[:r,:s] / sum(kd0[[r],[s]] for r in R,s in S)
theta_PC_RA[:r,:h] = c0_h[:r,:h]/(c0_h[:r,:h]+lsr0[:r,:h])
=#
@expressions(m,begin
PI_Y_VA[r=R,s=S],
(PL[r]^theta_pl_y_va[[r],[s]] * (RK[r,s]*(1+tk[[r],[s]])/(1+tk0[[r]]))^(1-theta_pl_y_va[[r],[s]]))
O_Y_PY[r=R,g=G,s=S],
ys0[[r],[s],[g]]
I_PA_Y[r=R,g=G,s=S],
id0[[r],[g],[s]]
I_PL_Y[r=R,s=S],
(ld0[[r],[s]] * PI_Y_VA[r,s] / PL[r])
I_RK_Y[r=R,s=S],
(kd0[[r],[s]] * PI_Y_VA[r,s]*(1+tk0[[r]])/(RK[r,s]*(1+tk[[r],[s]])))
PI_X[r=R,g=G],
((theta_PFX_X[r,g]*PFX^(1+4) + theta_PN_X[r,g]*PN[g]^(1+4) + theta_PD_X[r,g]*PD[r,g]^(1+4))^(1/(1+4)))
O_X_PFX[r=R,g=G],
((x0[[r],[g]]-rx0[[r],[g]])*(PFX/PI_X[r,g])^4)
O_X_PN[g=G,r=R],
(xn0[[r],[g]]*(PN[g]/PI_X[r,g])^4)
O_X_PD[r=R,g=G],
(xd0[[r],[g]]*(PD[r,g]/PI_X[r,g])^4)
I_PY_X[r=R,g=G],
s0[[r],[g]]
PI_A_D[r=R,g=G],
((theta_PN_A_d[[r],[g]]*PN[g]^(1-2)+(1-theta_PN_A_d[[r],[g]])*PD[r,g]^(1-2))^(1/(1-2)))
PI_A_DM[r=R,g=G],
((theta_PFX_A_dm[[r],[g]]*(PFX*(1+tm[[r],[g]])/(1+tm0[[r],[g]]))^(1-4)+(1-theta_PFX_A_dm[[r],[g]])*PI_A_D[r,g]^(1-4))^(1/(1-4)))
O_A_PA[r=R,g=G],
a0[[r],[g]]
O_A_PFX[r=R,g=G],
rx0[[r],[g]]
I_PN_A[g=G,r=R],
(nd0[[r],[g]]*(PI_A_DM[r,g]/PI_A_D[r,g])^4 * (PI_A_D[r,g]/PN[g])^2)
I_PD_A[r=R,g=G],
(dd0[[r],[g]]*(PI_A_DM[r,g]/PI_A_D[r,g])^4 * (PI_A_D[r,g]/PD[r,g])^2)
I_PFX_A[r=R,g=G],
(m0[[r],[g]]*(PI_A_DM[r,g]*(1+tm0[[r],[g]])/(PFX*(1+tm[[r],[g]])))^4)
I_PM_A[r=R,m=M,g=G],
md0[[r],[m],[g]]
O_MS_PM[r=R,m=M],
(sum(md0[[r],[m],[gm]] for gm = GM))
I_PN_MS[gm=GM,r=R,m=M],
(nm0[[r],[gm],[m]])
I_PD_MS[r=R,gm=GM,m=M],
(dm0[[r],[gm],[m]])
PI_C[r=R,h=H],
(prod(PA[r,g]^thetac[[r],[g],[h]] for g = G))
O_C_PC[r=R,h=H],
(c0_h[[r],[h]])
I_PA_C[r=R,g=G,h=H],
(cd0_h[[r],[g],[h]]*PI_C[r,h]/PA[r,g]) #! N.B. Set g enters PI_C but is local to that macro
O_LS_PL[q=Q,r=R,h=H],
(le0[[r],[q],[h]])
I_PLS_LS[r=R,h=H],
(ls0[[r],[h]])
PI_KS,
(sum((r,s),betaks[[r],[s]]*RK[r,s]^(1+etak))^(1/(1+etak)))
O_KS_RK[r=R,s=S],
(kd0[[r],[s]]*(RK[r,s]/PI_KS)^etak)
I_RKS_KS,
(sum((r,s),kd0[[r],[s]]))
PI_RA[r=R,h=H],
((theta_PC_RA[r,h]*PC[r,h]^(1-esubL[[r],[h]]) + (1-theta_PC_RA[r,h])*PLS[r,h]^(1-esubL[[r],[h]]))^(1/(1-esubL[[r],[h]])))
W_RA[r=R,h=H],
(RA[r,h]/((c0_h[[r],[h]]+lsr0[[r],[h]])*PI_RA[r,h]))
D_PC_RA[r=R,h=H],
(c0_h[[r],[h]] * W_RA[r,h] * (PI_RA[r,h]/PC[r,h])^esubL[[r],[h]])
D_PLS_RA[r=R,h=H],
(lsr0[[r],[h]] * W_RA[r,h] * (PI_RA[r,h]/PLS[r,h])^esubL[[r],[h]])
E_RA_PLS[r=R,h=H],
(ls0[[r],[h]]+lsr0[[r],[h]])
E_RA_PK[r=R,h=H],
(ke0[[r],[h]])
E_RA_PFX[r=R,h=H],
(TRANS*sum(hhtrn0[[r],[h],[trn]] for trn = TRN)-SAVRATE*sav0[[r],[h]])
D_PK_NYSE,
(NYSE/PK)
E_NYSE_PY[r=R,g=G],
(yh0[[r],[g]])
E_NYSE_RKS,
(SSK*sum([r,s],kd0[[r],[s]]))
D_PA_INVEST[r=R,g=G],
(i0[[r],[g]] * INVEST/sum((r,g),PA[r,g]*i0[[r],[g]]))
E_INVEST_PFX,
(fsav0+SAVRATE*totsav0)
D_PA_GOVT[r=R,g=G],
(g0[[r],[g]]*GOVT/sum((r,g),PA[r,g]*g0[[r],[g]]))
E_GOVT_PFX,
(govdef0-TRANS*sum([r,h],trn0[[r],[h]]))
end)
@constraints(m, begin
prf_Y[r=R,s=S;y_[[r],[s]]!=0],
sum(PA[r,g]*I_PA_Y[r,g,s] for g in G) + I_PL_Y[r,s]*PL[r] + I_RK_Y[r,s]*RK[r,s]*(1+tk[[r],[s]]) -
( sum(PY[r,g]*O_Y_PY[r,g,s]*(1-ty[[r],[s]]) for g in G) )
prf_X[r=R,g=G;x_[[r],[g]]!=0],
PY[r,g]*I_PY_X[r,g] - ( PFX*O_X_PFX[r,g] + PN[g]*O_X_PN[g,r] + PD[r,g]*O_X_PD[r,g] )
prf_a[r=R,g=G;a_[[r],[g]]!=0],
sum(PM[r,m]*I_PM_A[r,m,g] for m in M) + PFX*(1+tm[[r],[g]])*I_PFX_A[r,g] + PD[r,g]*I_PD_A[r,g] +
PN[g]*I_PN_A[g,r] - ( PFX*O_A_PFX[r,g] + PA[r,g]*O_A_PA[r,g]*(1-ta[[r],[g]]) )
prf_MS[r=R,m=M],
sum(gm, PD[r,gm]*I_PD_MS[r,gm,m] + PN[gm]*I_PN_MS[gm,r,m]) - ( PM[r,m]*O_MS_PM[r,m] )
prf_c[r=R,h=H],
sum( PA[r,g]*I_PA_C[r,g,h] for g in G) - ( PC[r,h]*O_C_PC[r,h] )
prf_LS[r=R,h=H],
PLS[r,h]*I_PLS_LS[r,h] - ( sum( PL[q]*O_LS_PL[q,r,h]*(1-tl[[r],[h]]) for q in Q) )
prf_ks,
RKS*I_RKS_KS - ( sum( RK[r,s]*O_KS_RK[r,s] for r in R, s in S) )
bal_ra[r=R,h=H],
RA[r,h] - ( PLS[r,h] * E_RA_PLS[r,h] + PFX * E_RA_PFX[r,h] + PK * E_RA_PK[r,h] )
bal_NYSE,
NYSE - ( sum(PY[r,g]*E_NYSE_PY[r,g] for r in R, g in G) + RKS*E_NYSE_RKS )
bal_INVEST,
INVEST - ( PFX*fsav0 + SAVRATE*PFX*totsav0 )
bal_GOVT,
GOVT - ( PFX*(govdef0 - TRANS*sum(trn0[[r],[h]]) for r in R, h in H) +
sum( Y[r,s] * (sum(PY[r,g]*ys0[[r],[s],[g]]*ty[[r],[s]] for g in G for r in R, s in S if y_[[r],[s]]!=0) +
I_RK_Y[r,s]*RK[r,s]*tk[[r],[s]])) + sum(a_[r,g], A[r,g] * (PA[r,g]*ta[[r],[g]]*a0[[r],[g]] + PFX*I_PFX_A[r,g]*tm[[r],[g]])) +
sum([r,h,q], LS[r,h] * PL[q] * O_LS_PL[q,r,h] * tl[[r],[h]]) )
aux_ssk,
sum(i0[[r],[g]]*PA[r,g] for r in R, g in G) - ( sum(i0[[r],[g]] for r in R, g in G)*RKS )
aux_savrate,
INVEST - ( sum( PA[r,g]*i0[[r],[g]] for r in R, g in G)*SSK )
aux_trans,
GOVT - ( sum(PA[r,g]*g0[[r],[g]] for r in R, g in G) )
mkt_PA[r=R,g=G;a0[[r],[g]]!=0],
sum( A[r,g]*O_A_PA[r,g] for r in R, g in G if a_[[r],[g]]!=0) -
( sum( Y[r,s]*I_PA_Y[r,g,s] for r in R, s in S if y_[[r],[s]]!=0) +
sum( C[r,h]*I_PA_C[r,g,h] for h in H) + D_PA_INVEST[r,g] + D_PA_GOVT[r,g] )
mkt_PY[r=R,g=G;s0[[r],[g]]!=0],
sum( Y[r,s]*O_Y_PY[r,g,s] for r in R, s in S if y_[[r],[s]]!=0) + E_NYSE_PY[r,g] - (
sum( X[r,g]*I_PY_X[r,g] for r in R, g in G if x_[[r],[g]]!=0) )
mkt_PD[r=R,g=G],
sum( X[r,g]*O_X_PD[r,g] for r in R, g in G if x_[[r],[g]]!=0) - (
sum( A[r,g]*I_PD_A[r,g] for r in R, g in G if a_[[r],[g]]!=0) +
sum( MS[r,m]*I_PD_MS[r,gm,m] for m in M, gm in GM) )
mkt_RK[r=R,s=S;kd0[[r],[s]]!=0],
KS*O_KS_RK[r,s] - ( Y[r,s]*I_RK_Y[r,s] )
mkt_RKS,
E_NYSE_RKS - ( KS*I_RKS_KS )
mkt_PM[r=R,m=M],
MS[r,m]*O_MS_PM[r,m] - ( sum(A[r,g]*I_PM_A[r,m,g] for r in R, g in G if a_[[r],[g]]!=0) )
mkt_PC[r=R,h=H],
C[r,h]*O_C_PC[r,h] - ( D_PC_RA[r,h] )
mkt_PN[g=G],
sum( X[r,g]*O_X_PN[g,r] for r in R, g in G if x_[[r],[g]]!=0) - (
sum( A[r,g]*I_PN_A[g,r] for r in R, g in G if a_[[r],[g]]!=0) +
sum([r,m,gm], MS[r,m]*I_PN_MS[gm,r,m]) )
mkt_PLS[r=R,h=H],
E_RA_pls[[r],[h]] - ( D_PLS_RA[r,h] + LS[r,h] * I_PLS_LS[r,h] )
mkt_PL[r=R],
sum( LS[r,h]*O_LS_PL[q,r,h] for q in Q, r in R, h in H) - (
sum( Y[r,s]*I_PL_Y[r,s] for r in R, s in S if y_[[r],[s]]!=0) )
mkt_PK,
sum( E_RA_PK[r,h] for r in R, h in H) - ( D_PK_NYSE )
mkt_PFX,
sum( X[r,g]*O_X_PFX[r,g] for r in R, g in G if x_[[r],[g]]!=0) +
sum( A[r,g]*O_A_PFX[r,g] for r in R, g in G if a_[[r],[g]]!=0) +
sum(E_RA_PFX[r,h] for r in R, h in H) + E_INVEST_PFX + E_GOVT_PFX - (
sum( A[r,g]*I_PFX_A[r,g] for r in R, g in G if a_[[r],[g]]!=0) )
end) | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 6350 | """
national_model_mcp(GU::GamsUniverse;solver = PATHSolver.Optimizer)
Run all years of the the national model. Returns a dictionary containing
each year.
"""
function national_model_mcp(GU::GamsUniverse;solver = PATHSolver.Optimizer)
models = Dict()
for year∈GU[:yr]
m = national_model_mcp_year(GU,year; solver = solver)
set_silent(m)
optimize!(m)
models[parse(Int,string(year))] = m
end
return models
end
"""
national_model_mcp_year(GU::GamsUniverse,year::Symbol;solver = PATHSolver.Optimizer)
Run the national model for a single year.
"""
function national_model_mcp_year(GU::GamsUniverse,year::Symbol;solver = PATHSolver.Optimizer)
"""
Self notes:
1. The four theta's get defined as new parameters
"""
#################
### GU ##########
#################
VA = GU[:va]
J = GU[:j]
I = GU[:i]
M = GU[:m]
Y_ = [j for j in GU[:j] if sum(GU[:ys0][[year],[j],[i]] for i∈I)!=0]
A_ = [i for i in GU[:i] if GU[:a0][[year],[i]]!=0]
PY_ = [i for i in GU[:i] if sum(GU[:ys0][[year],[j],[i]] for j∈J)!=0]
XFD = [fd for fd in GU[:fd] if fd!=:pce]
####################
## GamsStructure.Parameters ######
####################
va0 = GU[:va0]
m0 = GU[:m0]
tm0 = GU[:tm0]
y0 = GU[:y0]
a0 = GU[:a0]
ta0 = GU[:ta0]
x0 = GU[:x0]
fd0 = GU[:fd0]
ms0 = GU[:ms0]
bopdef = GU[:bopdef0][[year]]
fs0 = GU[:fs0]
ys0 = GU[:ys0]
id0 = GU[:id0]
md0 = GU[:md0]
ty = GamsStructure.Parameter(GU,(:yr,:i))
tm = GamsStructure.Parameter(GU,(:yr,:i))
ta = GamsStructure.Parameter(GU,(:yr,:i))
ty[:yr,:i] = GU[:ty0][:yr,:i]
tm[:yr,:i] = GU[:tm0][:yr,:i].*0 #for the counterfactual
ta[:yr,:i] = GU[:ta0][:yr,:i].*0 #for the counterfactual
thetava = GamsStructure.Parameter(GU,(:va,:j)) #GU[:thetava]
thetam = GamsStructure.Parameter(GU,(:i,)) #GU[:thetam]
thetax = GamsStructure.Parameter(GU,(:i,)) #GU[:thetax]
thetac = GamsStructure.Parameter(GU,(:i,)) #GU[:thetac]
for va∈VA, j∈J
if va0[[year],[va],[j]]≠0
thetava[[va],[j]] = va0[[year],[va],[j]]/sum(va0[[year],[v],[j]] for v∈VA)
end
end
for i∈I
if m0[[year],[i]] != 0
thetam[[i]] = m0[[year],[i]].*(1 .+tm0[[year],[i]])./(m0[[year],[i]].*(1 .+tm0[[year],[i]] ).+ y0[[year],[i]])
end
end
for i∈I
if x0[[year],[i]] != 0
thetax[[i]] = x0[[year],[i]]./(x0[[year],[i]].+a0[[year],[i]].*(1 .-ta0[[year],[i]]))
end
end
thetac[:i] = fd0[[year],:i,[:pce]]./sum(fd0[[year],:i,[:pce]])
#######################
## Model starts here ##
#######################
m = JuMP.Model(solver)
@variables(m,begin
Y[J]>=0, (start = 1,)
A[I]>=0, (start = 1,)
MS[M]>=0, (start = 1,)
PA[I]>=0, (start = 1,)
PY[I]>=0, (start = 1,)
PVA[VA]>=0, (start = 1,)
PM[M]>=0, (start = 1,)
PFX>=0, (start = 1,)
RA>=0, (start = sum(fd0[[year],:i,[:pce]]),)
end)
####################
## Macros in Gams ##
####################
@expressions(m, begin
CVA[j=J],
prod(PVA[va]^thetava[[va],[j]] for va∈VA)
PMD[i=I],
(thetam[[i]]*(PFX*(1+tm[[year],[i]])/(1+tm0[[year],[i]]))^(1-2) + (1-thetam[[i]])*PY[i]^(1-2))^(1/(1-2))
PXD[i=I],
(thetax[[i]]*PFX^(1+2) + (1-thetax[[i]])*(PA[i]*(1-ta[[year],[i]])/(1-ta0[[year],[i]]))^(1+2))^(1/(1+2))
MD[i=I],
A[i]*m0[[year],[i]]*( (PMD[i]*(1+tm0[[year],[i]])) / (PFX*(1+tm[[year],[i]])))^2
YD[i=I],
A[i]*y0[[year],[i]]*(PMD[i]/PY[i])^2
XS[i=I],
A[i]*x0[[year],[i]]*(PFX/PXD[i])^2
DS[i = I],
A[i]*a0[[year],[i]]*(PA[i]*(1-ta[[year],[i]])/(PXD[i]*(1-ta0[[year],[i]])))^2
end)
########################
## End of GAMS Macros ##
########################
@constraints(m,begin
prf_Y[j=Y_], #defined on y_(j)
CVA[j]*sum(va0[[year],[va],[j]] for va∈VA) +
sum(PA[i]*id0[[year],[i],[j]] for i∈I) -
sum(PY[i]*ys0[[year],[j],[i]] for i∈I)*(1-ty[[year],[j]]) ⟂ Y[j]
prf_A[i = A_], #defined on a_(i)
sum(PM[m_]*md0[[year],[m_],[i]] for m_∈M) +
PMD[i] *
(y0[[year],[i]] +(1+tm0[[year],[i]])*m0[[year],[i]]) -
PXD[i] *
(x0[[year],[i]] + a0[[year],[i]]*(1-ta0[[year],[i]])) ⟂ A[i]
prf_MS[m_ = M],
sum(PY[i]*ms0[[year],[i],[m_]] for i∈I) -
PM[m_]*sum(ms0[[year],[i],[m_]] for i∈I) ⟂ MS[m_]
bal_RA,
-RA + sum(PY[i]*fs0[[year],[i]] for i∈I) + PFX*bopdef -
sum(PA[i]*fd0[[year],[i],[xfd]] for i∈I,xfd∈XFD) + sum(PVA[va]*va0[[year],[va],[j]] for va∈VA,j∈J) +
sum(A[i]*(a0[[year],[i]]*PA[i]*ta[[year],[i]] + PFX*MD[i]*tm[[year],[i]]) for i∈I) +
sum(Y[j]*sum(ys0[[year],[j],[i]]*PY[i] for i∈I)*ty[[year],[j]] for j∈J) ⟂ RA
#thetac[:i] = fd0[[year],:i,[:pce]]./sum(fd0[[year],:i,[:pce]])
mkt_PA[i = A_],
-DS[i] + thetac[[i]] * RA/PA[i] + sum(fd0[[year],[i],[xfd]] for xfd∈XFD) +
sum(Y[j]*id0[[year],[i],[j]] for j∈Y_) ⟂ PA[i]
mkt_PY[i=I],
-sum(Y[j]*ys0[[year],[j],[i]] for j∈Y_) +
sum(MS[m_]*ms0[[year],[i],[m_]] for m_∈M) + YD[i] ⟂ PY[i]
mkt_PVA[va = VA],
-sum(va0[[year],[va],[j]] for j∈J) +
sum(Y[j]*va0[[year],[va],[j]]*CVA[j]/PVA[va] for j∈Y_) ⟂ PVA[va]
mkt_PM[m_ = M],
MS[m_]*sum(ms0[[year],[i],[m_]] for i∈I) -
sum(A[i]*md0[[year],[m_],[i]] for i∈I if a0[[year],[i]]≠0) ⟂ PM[m_]
mkt_PFX,
sum(XS[i] for i∈A_) + bopdef -
sum(MD[i] for i∈A_) ⟂ PFX
end)
#############################
## Fix unmatched variables ##
#############################
for i∈I
if a0[[year],[i]] == 0
fix(A[i],0,force=true)
fix(PA[i],0,force=true)
end
end
return m
end
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 13392 | """
state_disaggregation_model_mcp(GU::GamsUniverse)
Run all years of the the state-level model. Returns a dictionary containing
each year.
"""
function state_disaggregation_model_mcp(GU::GamsUniverse)
models = Dict()
for year∈GU[:yr]
m = state_disaggregation_model_mcp_year(GU,year)
set_silent(m)
optimize!(m)
models[parse(Int,string(year))] = m
end
return models
end
"""
state_disaggregation_model_mcp_year(GU::GamsUniverse,year::Symbol)
Return the model for the state-level disaggreation for a single year.
"""
function state_disaggregation_model_mcp_year(GU::GamsUniverse,year::Symbol)
model = JuMP.Model(PATHSolver.Optimizer)
R = [r for r∈GU[:r]]
S = [s for s∈GU[:s]]
G = [g for g∈GU[:g]]
M = [m for m∈GU[:m]]
GM = [gm for gm∈GU[:gm]]
ys0 = GamsStructure.Parameter(GU,(:r,:s,:g))
ys0[:r,:s,:g] = GU[:ys0_][[year],:r,:s,:g]
id0 = GamsStructure.Parameter(GU,(:r,:g,:s))
id0[:r,:g,:s] = GU[:id0_][[year],:r,:g,:s]
ld0 = GamsStructure.Parameter(GU,(:r,:s))
ld0[:r,:s] = GU[:ld0_][[year],:r,:s]
kd0 = GamsStructure.Parameter(GU,(:r,:s))
kd0[:r,:s] = GU[:kd0_][[year],:r,:s]
ty0 = GamsStructure.Parameter(GU,(:r,:s))
ty0[:r,:s] = GU[:ty0_][[year],:r,:s]
ty = ty0
m0 = GamsStructure.Parameter(GU,(:r,:g))
m0[:r,:g] = GU[:m0_][[year],:r,:g]
x0 = GamsStructure.Parameter(GU,(:r,:g))
x0[:r,:g] = GU[:x0_][[year],:r,:g]
rx0 = GamsStructure.Parameter(GU,(:r,:g))
rx0[:r,:g] = GU[:rx0_][[year],:r,:g]
md0 = GamsStructure.Parameter(GU,(:r,:m,:g))
md0[:r,:m,:g] = GU[:md0_][[year],:r,:m,:g]
nm0 = GamsStructure.Parameter(GU,(:r,:g,:m))
nm0[:r,:g,:m] = GU[:nm0_][[year],:r,:g,:m]
dm0 = GamsStructure.Parameter(GU,(:r,:g,:m))
dm0[:r,:g,:m] = GU[:dm0_][[year],:r,:g,:m]
s0 = GamsStructure.Parameter(GU,(:r,:g))
s0[:r,:g] = GU[:s0_][[year],:r,:g]
a0 = GamsStructure.Parameter(GU,(:r,:g))
a0[:r,:g] = GU[:a0_][[year],:r,:g]
ta0 = GamsStructure.Parameter(GU,(:r,:g))
ta0[:r,:g] = GU[:ta0_][[year],:r,:g]
ta = deepcopy(ta0)
tm0 = GamsStructure.Parameter(GU,(:r,:g))
tm0[:r,:g] = GU[:tm0_][[year],:r,:g]
tm = deepcopy(tm0)
tm[:r,:g] = tm[:r,:g]*0 #Shock, set tariffs to zero
cd0 = GamsStructure.Parameter(GU,(:r,:g))
cd0[:r,:g] = GU[:cd0_][[year],:r,:g]
c0 = GamsStructure.Parameter(GU,(:r,))
c0[:r] = GU[:c0_][[year],:r]
yh0 = GamsStructure.Parameter(GU,(:r,:g))
yh0[:r,:g] = GU[:yh0_][[year],:r,:g]
bopdef0 = GamsStructure.Parameter(GU,(:r,))
bopdef0[:r] = GU[:bopdef0_][[year],:r]
g0 = GamsStructure.Parameter(GU,(:r,:g))
g0[:r,:g] = GU[:g0_][[year],:r,:g]
i0 = GamsStructure.Parameter(GU,(:r,:g))
i0[:r,:g] = GU[:i0_][[year],:r,:g]
xn0 = GamsStructure.Parameter(GU,(:r,:g))
xn0[:r,:g] = GU[:xn0_][[year],:r,:g]
xd0 = GamsStructure.Parameter(GU,(:r,:g))
xd0[:r,:g] = GU[:xd0_][[year],:r,:g]
dd0 = GamsStructure.Parameter(GU,(:r,:g))
dd0[:r,:g] = GU[:dd0_][[year],:r,:g]
nd0 = GamsStructure.Parameter(GU,(:r,:g))
nd0[:r,:g] = GU[:nd0_][[year],:r,:g]
hhadj = GamsStructure.Parameter(GU,(:r,))
hhadj[:r] = GU[:hhadj0_][[year],:r]
@variables(model,begin
Y[R,S]>=0, (start = 1,)
X[R,G]>=0, (start =1,)
A[R,G]>=0, (start =1,)
C[R]>=0, (start =1,)
MS[R,M]>=0, (start =1,)
PA[R,G]>=0, (start =1,)
PY[R,G]>=0, (start =1,)
PD[R,G]>=0, (start =1,)
PN[G]>=0, (start =1,)
PL[R]>=0, (start =1,)
PK[R,S]>=0, (start =1,)
PM[R,M]>=0, (start =1,)
PC[R]>=0, (start =1,)
PFX>=0, (start =1,)
RA[r=R]>=0, (start = c0[[r]],)
end)
for r∈R,s∈S
if kd0[[r],[s]] ≠ 0
set_lower_bound(PK[r,s],1e-5)
end
end
for r∈R,g∈G
if a0[[r],[g]] == 0
fix(PA[r,g],0,force=true)
end
if s0[[r],[g]] == 0
fix(PY[r,g],0,force=true)
fix(X[r,g],0,force=true)
end
if xd0[[r],[g]] == 0
fix(PD[r,g],0,force=true)
end
#s and g are aliases
if kd0[[r],[g]] == 0
fix(PK[r,g],0,force=true)
end
if sum(ys0[[r],[g],:g]) == 0
fix(Y[r,g],0,force=true)
end
if a0[[r],[g]] + rx0[[r],[g]] == 0
fix(A[r,g],0,force=true)
end
end
lvs = GamsStructure.Parameter(GU,(:r,:s))
lvs[:r,:s] = ld0[:r,:s]./(ld0[:r,:s] + kd0[:r,:s])
@expressions(model,begin
PI_Y[r=R,s=S], PL[r]^lvs[[r],[s]]*PK[r,s]^(1-lvs[[r],[s]])
O_Y_PY[r=R,g=G,s=S], ys0[[r],[s],[g]]
I_PA_Y[r=R,g=G,s=S], id0[[r],[g],[s]]
I_PL_Y[r=R,s=S], ld0[[r],[s]]*ifelse(ld0[[r],[s]]!=0, (PI_Y[r,s]/PL[r]),0) #if ld0[[r],[s]]!=0
I_PK_Y[r=R,s=S], kd0[[r],[s]]*ifelse(kd0[[r],[s]]!=0, (PI_Y[r,s]/PK[r,s]),0) #if kd0[[r],[s]]!=0
R_Y_RA[r=R,s=S], sum(PY[r,g]*ty[[r],[s]]*O_Y_PY[r,g,s] for g∈G)
end)
theta_X_PD = GamsStructure.Parameter(GU,(:r,:g))
theta_X_PD[:r,:g] = xd0[:r,:g]./s0[:r,:g]
theta_X_PN = GamsStructure.Parameter(GU,(:r,:g))
theta_X_PN[:r,:g] = xn0[:r,:g]./s0[:r,:g]
theta_X_PFX = GamsStructure.Parameter(GU,(:r,:g))
theta_X_PFX[:r,:g] = (x0[:r,:g] - rx0[:r,:g])./s0[:r,:g]
@expressions(model,begin
PI_X[r=R,g=G], (theta_X_PD[[r],[g]] * PD[r,g]^(1+4) + theta_X_PN[[r],[g]] * PN[g]^(1+4) + theta_X_PFX[[r],[g]] * PFX^(1+4) )^(1/(1+4))
O_X_PFX[r=R,g=G], (x0[[r],[g]]-rx0[[r],[g]])*ifelse(x0[[r],[g]] - rx0[[r],[g]] !=0, ((PFX/PI_X[r,g])^4),0) #$(x0(r,g)-rx0(r,g)))
O_X_PN[g=G,r=R], xn0[[r],[g]]*ifelse(xn0[[r],[g]]!=0,((PN[g]/PI_X[r,g])^4),0) #$xn0(r,g))
end)
@expression(model,
O_X_PD[r=R,g=G], xd0[[r],[g]]*ifelse(xd0[[r],[g]]!=0,
ifelse(!isapprox(theta_X_PD[[r],[g]],1,atol=1e-6), (PD[r,g]/PI_X[r,g])^4, 1)
,0)
)
@expression(model,
I_PY_X[r=R,g=G], s0[[r],[g]]
)
theta_PN_A = GamsStructure.Parameter(GU,(:r,:g))
theta_PD_A = GamsStructure.Parameter(GU,(:r,:g))
theta_PFX_A = GamsStructure.Parameter(GU,(:r,:g))
theta_PFX_A[:r,:g] = ifelse.(m0[:r,:g].!=0, m0[:r,:g].*(1 .+ tm0[:r,:g])./(m0[:r,:g].*(1 .+ tm0[:r,:g])+nd0[:r,:g]+dd0[:r,:g]),0)
theta_PN_A[:r,:g] = ifelse.(nd0[:r,:g] .!=0, nd0[:r,:g] ./(nd0[:r,:g]+dd0[:r,:g]), 0)
theta_PD_A[:r,:g] = ifelse.(dd0[:r,:g] .!=0, dd0[:r,:g] ./(nd0[:r,:g]+dd0[:r,:g]), 0)
@expressions(model,begin
PI_PFX_A[r=R,g=G], PFX*(1+tm[[r],[g]])/(1+tm0[[r],[g]])
# Need to do an ifelse on this
PI_A_D[r=R,g=G], (
ifelse(!isapprox(theta_PN_A[[r],[g]],0,atol=1e-10),theta_PN_A[[r],[g]]*(PN[g]^(1-4)),0) +
ifelse(!isapprox(theta_PD_A[[r],[g]],0,atol=1e-10),theta_PD_A[[r],[g]]*(PD[r,g]^(1-4)),0)
)^(1/(1-4))
PI_A_DM[r=R,g=G], (
ifelse(!isapprox(theta_PFX_A[[r],[g]],0,atol=1e-10),theta_PFX_A[[r],[g]]*(PI_PFX_A[r,g]^(1.0-2)),0) +
ifelse(!isapprox(1-theta_PFX_A[[r],[g]],0,atol=1e-10), (1-theta_PFX_A[[r],[g]])*(PI_A_D[r,g]^(1.0-2)),0)
)^(1.0/(1-2))
O_A_PA[r=R,g=G], a0[[r],[g]]
O_A_PFX[r=R,g=G], rx0[[r],[g]]
I_PN_A[g=G,r=R], nd0[[r],[g]]*ifelse(nd0[[r],[g]]!=0,
(PI_A_DM[r,g]/PI_A_D[r,g])^2*(PI_A_D[r,g]/PN[g])^4.0
,0
)
I_PD_A[r=R,g=G], dd0[[r],[g]]*ifelse(!isapprox(dd0[[r],[g]],0,atol=1e-8),
(PI_A_DM[r,g]/PI_A_D[r,g])^2*(PI_A_D[r,g]/PD[r,g])^4.0
,0
)
I_PFX_A[r=R,g=G], m0[[r],[g]]*ifelse(m0[[r],[g]]!=0,
(PI_A_DM[r,g]/PI_PFX_A[r,g])^2
,0
)
I_PM_A[r=R,m=M,g=G],md0[[r],[m],[g]]
R_A_RA[r=R,g=G], ta[[r],[g]]*PA[r,g]*O_A_PA[r,g] + tm[[r],[g]]*PFX*I_PFX_A[r,g]
O_MS_PM[r=R,m=M], sum(md0[[r],[m],[gm]] for gm∈GM )
#I_PN_MS[gm=GM,r=R,m=M], nm0[[r],[gm],[m]]
I_PN_MS[gm=G,r=R,m=M], ifelse(gm∈GM, nm0[[r],[gm],[m]],0)
#I_PD_MS[r=R,gm=GM,m=M], dm0[[r],[gm],[m]]
I_PD_MS[r=R,gm=G,m=M], ifelse(gm∈GM, dm0[[r],[gm],[m]],0)
end)
theta_PA_C = GamsStructure.Parameter(GU,(:r,:g))
theta_PA_C[:r,:g] = cd0[:r,:g]./sum(cd0[:r,:g],dims=2)
@expressions(model,begin
PI_C[r=R], prod(PA[r,g]^theta_PA_C[[r],[g]] for g∈G if theta_PA_C[[r],[g]] != 0)
O_C_PC[r=R], c0[[r]]
I_PA_C[r=R,g=G], cd0[[r],[g]]*ifelse(cd0[[r],[g]]!=0,
(PI_C[r]/PA[r,g])
,0
)
E_RA_PY[r=R,g=G], yh0[[r],[g]]
E_RA_PFX[r=R], bopdef0[[r]]+hhadj[[r]]
E_RA_PA[r=R,g=G], -g0[[r],[g]]-i0[[r],[g]]
E_RA_PL[r=R], sum(ld0[[r],[s]] for s∈S)
E_RA_PK[r=R,s=S], kd0[[r],[s]]
D_PC_RA[r=R], RA[r]/PC[r]
end)
########################
## Start of Equations ##
########################
@constraints(model,begin
# Zero profit condition: value of inputs from national market (PN[g]), domestic market (PD[r,g])
# and imports (PFX) plus tax liability equals the value of supply to the PA[r,g] market and
# re-exports to the PFX market:
prf_Y[r=R,s=S],
sum(PA[r,g]*I_PA_Y[r,g,s] for g∈G) +
PL[r]*I_PL_Y[r,s] + PK[r,s]*I_PK_Y[r,s] + R_Y_RA[r,s] -
sum(PY[r,g]*O_Y_PY[r,g,s] for g∈G) ⟂ Y[r,s]
prf_X[r=R,g=G],
PY[r,g]*I_PY_X[r,g] - (PFX*O_X_PFX[r,g] + PN[g]*O_X_PN[g,r] + PD[r,g]*O_X_PD[r,g]) ⟂ X[r,g]
prf_A[r=R,g=G],
PN[g]*I_PN_A[g,r] + PD[r,g]*I_PD_A[r,g] + PFX*I_PFX_A[r,g] + sum(PM[r,m]*I_PM_A[r,m,g] for m∈M) + R_A_RA[r,g] -
(PA[r,g]*O_A_PA[r,g] + PFX * O_A_PFX[r,g]) ⟂ A[r,g]
prf_MS[r=R,m=M], sum(PN[gm]*I_PN_MS[gm,r,m] + PD[r,gm]*I_PD_MS[r,gm,m] for gm∈GM) - PM[r,m]*O_MS_PM[r,m] ⟂ MS[r,m]
prf_C[r=R], sum(PA[r,g]*I_PA_C[r,g] for g∈G) - PC[r]*O_C_PC[r] ⟂ C[r]
# Market clearance conditions: production outputs plus consumer endowments equal production inputs
# plus consumer demand.
# Aggregate absorption associated with intermediate and consumer demand:
mkt_PA[r=R,g=G], A[r,g]*O_A_PA[r,g] + E_RA_PA[r,g] -(
sum(Y[r,s]*I_PA_Y[r,g,s] for s∈S) + I_PA_C[r,g]*C[r]) ⟂ PA[r,g]
# Producer output supply and demand:
mkt_PY[r=R,g=G], sum(Y[r,s]*O_Y_PY[r,g,s] for s∈S) + E_RA_PY[r,g] - X[r,g] * I_PY_X[r,g] ⟂ PY[r,g]
# Regional market for goods:
mkt_PD[r=R,g=G], X[r,g]*O_X_PD[r,g] - (A[r,g]*I_PD_A[r,g] + ifelse(g∈GM, sum(MS[r,m]*I_PD_MS[r,g,m] for m∈M),0)) ⟂ PD[r,g] #$gm[g])
# National market for goods:
mkt_PN[g=G], sum(X[r,g] * O_X_PN[g,r] for r∈R) - (
sum(A[r,g] * I_PN_A[g,r] for r∈R) + ifelse(g∈GM, sum(MS[r,m]*I_PN_MS[g,r,m] for r∈R,m∈M),0)) ⟂ PN[g] #$gm[g]
# Foreign exchange:
mkt_PFX, sum(X[r,g]*O_X_PFX[r,g] for r∈R,g∈G if s0[[r],[g]]!=0) + sum(A[r,g]*O_A_PFX[r,g] for r∈R,g∈G) + sum(E_RA_PFX[r] for r∈R) -
sum(A[r,g] * I_PFX_A[r,g] for r∈R,g∈G) ⟂ PFX
# Labor market:
mkt_PL[r=R], E_RA_PL[r] - sum(Y[r,s]*I_PL_Y[r,s] for s∈S) ⟂ PL[r]
# Capital stocks:
mkt_PK[r=R,s=S], E_RA_PK[r,s] - Y[r,s]*I_PK_Y[r,s] ⟂ PK[r,s]
# Margin supply and demand:
mkt_PM[r=R,m=M], MS[r,m]*O_MS_PM[r,m] - sum(A[r,g] * I_PM_A[r,m,g] for g∈G) ⟂ PM[r,m]
# Consumer demand:
mkt_PC[r=R], C[r]*O_C_PC[r] - D_PC_RA[r] ⟂ PC[r]
# Income balance:
bal_RA[r=R], RA[r] - (
# Endowment income from yh0[r,g]:
sum(PY[r,g]*E_RA_PY[r,g] for g∈G) +
# Wage income from ld0:
PL[r]*E_RA_PL[r] +
# Income associated with bopdef[r] and hhadj[r]:
PFX*E_RA_PFX[r] +
# Government and investment demand (g0[r,g] + i0[r,g]):
sum(PA[r,g]*E_RA_PA[r,g] for g∈G) +
# Capital earnings (kd0[r,s]):
sum(PK[r,s]*E_RA_PK[r,s] for s∈S) +
# Tax revenues are expressed as values per unit activity, so we
# need multiply these by the activity level to compute total income:
sum(R_Y_RA[r,s]*Y[r,s] for s∈S if sum(ys0[[r],[s],:g]) > 0) +
sum(R_A_RA[r,g]*A[r,g] for g∈G if (a0[[r],[g]] + rx0[[r],[g]]) != 0)
)⟂ RA[r]
end)
return model
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 2224 |
"""
fill_parameter!(GU::GamsUniverse,df_full::DataFrame,parm::Symbol,col_set_link,additional_filters)
col_set_link is a dictionary with entries :set_name => :column_name
additional_filters is a dictionary with entries :parameter_name => (:column_name, :values_to_keep)
"""
function fill_parameter!(GU::GamsUniverse,df_full::DataFrame,parm::Symbol,col_set_link,additional_filters)
df = deepcopy(df_full)
for s in domain(GU[parm])
col = col_set_link[s]
filter!(col => x-> x in GU[s], df)
end
if parm in keys(additional_filters)
col, good = additional_filters[parm]
filter!(col => x-> x == good, df)
end
columns = [col_set_link[e] for e in domain(GU[parm])]
for row in eachrow(df)
d = [[row[e]] for e∈columns]
GU[parm][d...] = row[:value]
end
end
"""
notation_link
Input data is dirty. This struct matches the dirty input data to a replacement
dataframe in a consistent manner.
dirty_to_replace -> The dirty column in the input data
data -> The replacement dataframe
dirty_to_match -> The column in the replacement dataframe that matches the dirty_to_replace
column in the input data.
clean_column -> The column in the replacement dataframe with the correct output
clean_name -> The final name that should appear in the output dataframe.
"""
struct notation_link
dirty_to_replace::Symbol
data::DataFrame
dirty_to_match::Symbol
clean_column::Symbol
clean_name::Symbol
end
function apply_notation(df, notation)
data = notation.data
dirty = notation.dirty_to_replace
dirty_match = notation.dirty_to_match
clean = notation.clean_column
clean_name = notation.clean_name
if dirty_match != clean
cols = [clean,dirty_match]
else
cols = [dirty_match]
end
df = innerjoin(data[!,cols],df,on = dirty_match => dirty, matchmissing=:notequal)
if dirty_match != clean
select!(df,Not(dirty_match))
end
if clean_name != clean
rename!(df, clean => clean_name)
end
return df
end
function apply_notations(df, notations)
for notation in notations
df = apply_notation(df,notation)
end
return df
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 1321 | include("./sets/sets.jl")
"""
load_national_data(data_dir)
Load and balance the national BEA Input/Output summary tables.
To Do:
1. Verify calibration
2. Add option to run MCP model to ensure calibration
"""
function load_national_data(data_dir)
J = JSON.parsefile("$data_dir\\data_information.json")
core_dir = joinpath(data_dir,"core")
core_info = J["core"]
GU = WiNDC.initialize_sets();
WiNDC.load_bea_io!(GU,core_dir,core_info["bea_io"]);
return GU
end
"""
load_state_data(data_dir)
Disaggregate the national dataset to the state level. This will
check that the resulting dataset is balanced.
To Do:
1. Add option to run MCP model to ensure calibration
"""
function load_state_data(data_dir)
J = JSON.parsefile("$data_dir\\data_information.json")
core_dir = joinpath(data_dir,"core")
core_info = J["core"]
GU = WiNDC.initialize_sets();
WiNDC.load_bea_io!(GU,core_dir,core_info["bea_io"]);
WiNDC.load_bea_gsp!(GU,core_dir,core_info["bea_gsp"]);
WiNDC.load_bea_pce!(GU,core_dir,core_info["bea_pce"]);
WiNDC.load_sgf_data!(GU,core_dir,core_info["census_sgf"]);
WiNDC.load_faf_data!(GU,core_dir,core_info["faf"])
WiNDC.load_usa_trade!(GU,core_dir,core_info["usatrd"])
GU = state_dissagregation(GU)
return GU
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 113369 | function bea_io_notations()
bea_code = DataFrame([
("111CA", "agr"),
("113FF", "fof"),
("211", "oil"),
("212", "min"),
("213", "smn"),
("22", "uti"),
("23", "con"),
("321", "wpd"),
("327", "nmp"),
("331", "pmt"),
("332", "fmt"),
("333", "mch"),
("334", "cep"),
("335", "eec"),
("3361MV", "mot"),
("3364OT", "ote"),
("337", "fpd"),
("339", "mmf"),
("311FT", "fbp"),
("313TT", "tex"),
("315AL", "alt"),
("322", "ppd"),
("323", "pri"),
("324", "pet"),
("325", "che"),
("326", "pla"),
("42", "wht"),
("441", "mvt"),
("445", "fbt"),
("452", "gmt"),
("4A0", "ott"),
("481", "air"),
("482", "trn"),
("483", "wtt"),
("484", "trk"),
("485", "grd"),
("486", "pip"),
("487OS", "otr"),
("493", "wrh"),
("511", "pub"),
("512", "mov"),
("513", "brd"),
("514", "dat"),
("521CI", "bnk"),
("523", "sec"),
("524", "ins"),
("525", "fin"),
("HS", "hou"),
("ORE", "ore"),
("532RL", "rnt"),
("5411", "leg"),
("5415", "com"),
("5412OP", "tsv"),
("55", "man"),
("561", "adm"),
("562", "wst"),
("61", "edu"),
("621", "amb"),
("622", "hos"),
("623", "nrs"),
("624", "soc"),
("711AS", "art"),
("713", "rec"),
("721", "amd"),
("722", "res"),
("81", "osv"),
("GFGD", "fdd"),
("GFGN", "fnd"),
("GFE", "fen"),
("GSLG", "slg"),
("GSLE", "sle"),
("Other", "oth"),
("Used", "use"),
("T005", "interm"),
("V001", "compen"),
("V003", "surplus"),
("T00OTOP", "othtax"),
("VABAS", "basicvalueadded"),
("T018", "industryoutput"),
("T00TOP", "taxes"),
("T00SUB", "subsidies"),
("VAPRO", "valueadded"),
("T001", "totint"),
("F010", "pce"),
("F02E", "equipment"),
("F02N", "intelprop"),
("F02R", "residential"),
("F02S", "structures"),
("F030", "changinv"),
("F040", "exports"),
("F06C", "defense"),
("F06E", "def_equipment"),
("F06N", "def_intelprop"),
("F06S", "def_structures"),
("F07C", "nondefense"),
("F07E", "fed_equipment"),
("F07N", "fed_intelprop"),
("F07S", "fed_structures"),
("F10C", "state_consume"),
("F10E", "state_equipment"),
("F10N", "state_intelprop"),
("F10S", "state_invest"),
("T019", "totaluse"),
("T017", "TotalBasic"),
("T007", "Output"),
("MCIF", "imports"),
("MADJ", "ciffob"),
("T013", "BasicSupply"),
("Trade", "Margins"),
("Trans", "TrnCost"),
("T014", "TrdTrn"),
("MDTY", "Duties"),
("TOP", "Tax"),
("SUB", "Subsidies"),
("T015", "TaxLesSubsidies"),
("T016", "Supply")
], [:naics_code,:i])
notations = []
push!(notations,notation_link(:RowCode,bea_code,:naics_code,:i,:commodity))#,:RowCode,:bea_code))
push!(notations,notation_link(:ColCode,bea_code,:naics_code,:i,:industry))
return notations
end
function regions()
regions = DataFrame([
("Alabama","01000000000000","AL","1"),
("Alaska","02000000000000","AK","2"),
("Arizona","03000000000000","AZ","4"),
("Arkansas","04000000000000","AR","5"),
("California","05000000000000","CA","6"),
("Colorado","06000000000000","CO","8"),
("Connecticut","07000000000000","CT","9"),
("Delaware","08000000000000","DE","10"),
("Florida","10000000000000","FL","12"),
("Georgia","11000000000000","GA","13"),
("Hawaii","12000000000000","HI","15"),
("Idaho","13000000000000","ID","16"),
("Illinois","14000000000000","IL","17"),
("Indiana","15000000000000","IN","18"),
("Iowa","16000000000000","IA","19"),
("Kansas","17000000000000","KS","20"),
("Kentucky","18000000000000","KY","21"),
("Louisiana","19000000000000","LA","22"),
("Maine","20000000000000","ME","23"),
("Maryland","21000000000000","MD","24"),
("Massachusetts","22000000000000","MA","25"),
("Michigan","23000000000000","MI","26"),
("Minnesota","24000000000000","MN","27"),
("Mississippi","25000000000000","MS","28"),
("Missouri","26000000000000","MO","29"),
("Montana","27000000000000","MT","30"),
("Nebraska","28000000000000","NE","31"),
("Nevada","29000000000000","NV","32"),
("New Hampshire","30000000000000","NH","33"),
("New Jersey","31000000000000","NJ","34"),
("New Mexico","32000000000000","NM","35"),
("New York","33000000000000","NY","36"),
("North Carolina","34000000000000","NC","37"),
("North Dakota","35000000000000","ND","38"),
("Ohio","36000000000000","OH","39"),
("Oklahoma","37000000000000","OK","40"),
("Oregon","38000000000000","OR","41"),
("Pennsylvania","39000000000000","PA","42"),
("Rhode Island","40000000000000","RI","44"),
("South Carolina","41000000000000","SC","45"),
("South Dakota","42000000000000","SD","46"),
("Tennessee","43000000000000","TN","47"),
("Texas","44000000000000","TX","48"),
("Utah","45000000000000","UT","49"),
("Vermont","46000000000000","VT","50"),
("Virginia","47000000000000","VA","51"),
("Washington","48000000000000","WA","53"),
("West Virginia","49000000000000","WV","54"),
("Wisconsin","50000000000000","WI","55"),
("Wyoming","51000000000000","WY","56"),
("District of Columbia","09000000000000","DC","11"),
("Dist of Columbia",missing,"DC",missing),
],[:region_fullname,:sgf_code,:region_abbv,:fips_state]);
return regions
end
function bea_gsp_notations()
notations = []
region = regions()
push!(notations,notation_link(:state,region,:region_fullname,:region_abbv,:region_abbv))
bea_gsp_map = DataFrame([
("Gross domestic product (GDP) by state","gdp"),
("Taxes on production and imports less subsidies","taxsbd"),
("Compensation of employees","cmp"),
("Subsidies","sbd"),
("Taxes on production and imports","tax"),
("Gross operating surplus","gos"),
("Quantity indexes for real GDP by state (2012=100.0)","qty"),
("Real GDP by state","rgdp")],
[:bea_code,:gdpcat])
#bea_gsp_map = WiNDC_notation(bea_gsp_map,:gdpcat)
push!(notations, notation_link(:ComponentName,bea_gsp_map,:bea_code,:gdpcat,:gdpcat))
bea_gsp_mapsec = DataFrame([
(4, "agr"),
(5, "fof"),
(7, "oil"),
(8, "min"),
(9, "smn"),
(10, "uti"),
(11, "con"),
(14, "wpd"),
(15, "nmp"),
(16, "pmt"),
(17, "fmt"),
(18, "mch"),
(19, "cep"),
(20, "eec"),
(21, "mot"),
(22, "ote"),
(23, "fpd"),
(24, "mmf"),
(26, "fbp"),
(27, "tex"),
(28, "alt"),
(29, "ppd"),
(30, "pri"),
(31, "pet"),
(32, "che"),
(33, "pla"),
(34, "wht"),
(35, "mvt"),
(35, "fbt"),
(35, "gmt"),
(35, "ott"),
(37, "air"),
(38, "trn"),
(39, "wtt"),
(40, "trk"),
(41, "grd"),
(42, "pip"),
(43, "otr"),
(44, "wrh"),
(46, "pub"),
(47, "mov"),
(48, "brd"),
(49, "dat"),
(52, "bnk"),
(53, "sec"),
(54, "ins"),
(55, "fin"),
(57, "hou"),
(57, "ore"),
(58, "rnt"),
(61, "leg"),
(62, "com"),
(63, "tsv"),
(64, "man"),
(66, "adm"),
(67, "wst"),
(69, "edu"),
(71, "amb"),
(72, "hos"),
(72, "nrs"),
(73, "soc"),
(76, "art"),
(77, "rec"),
(79, "amd"),
(80, "res"),
(81, "osv"),
(83, "fnd"),
(83, "fen"),
(84, "fdd"),
(85, "slg"),
(85, "sle")
],
[:gsp_industry_id,:i]
)
#bea_gsp_mapsec = WiNDC_notation(bea_gsp_mapsec,:i)
push!(notations, notation_link(:IndustryID,bea_gsp_mapsec,:gsp_industry_id,:i,:i))
return notations
end
function bea_pce_notations()
notations = []
region = regions()
push!(notations, notation_link(:GeoName,region,:region_fullname,:region_abbv,:r))
pce_map = DataFrame([
("Food and beverages purchased for off-premises consumption","foo","agr"),
("Recreational goods and vehicles","rec","fof"),
("Gasoline and other energy goods","enr","oil"),
("Gasoline and other energy goods","enr","min"),
("Other nondurable goods","ong","smn"),
("Housing and utilities","utl","uti"),
("Other durable goods","odg","con"),
("Food and beverages purchased for off-premises consumption","foo","fbp"),
("Clothing and footwear","clo","tex"),
("Clothing and footwear","clo","alt"),
("Furnishings and durable household equipment","hdr","wpd"),
("Other durable goods","odg","ppd"),
("Other durable goods","odg","pri"),
("Other durable goods","odg","pet"),
("Other durable goods","odg","che"),
("Other durable goods","odg","pla"),
("Other durable goods","odg","nmp"),
("Other durable goods","odg","pmt"),
("Other durable goods","odg","fmt"),
("Other durable goods","odg","mch"),
("Recreational goods and vehicles","rec","cep"),
("Recreational goods and vehicles","rec","eec"),
("Motor vehicles and parts","mvp","mot"),
("Motor vehicles and parts","mvp","ote"),
("Furnishings and durable household equipment","hdr","fpd"),
("Other durable goods","odg","mmf"),
("Other durable goods","odg","wht"),
("Motor vehicles and parts","mvp","mvt"),
("Food and beverages purchased for off-premises consumption","foo","fbt"),
("Other nondurable goods","ong","gmt"),
("Other nondurable goods","ong","ott"),
("Transportation services","trn","air"),
("Transportation services","trn","trn"),
("Transportation services","trn","wtt"),
("Transportation services","trn","trk"),
("Transportation services","trn","grd"),
("Transportation services","trn","pip"),
("Transportation services","trn","otr"),
("Other services","osr","wrh"),
("Other services","osr","pub"),
("Other services","osr","mov"),
("Other services","osr","brd"),
("Other services","osr","dat"),
("Financial services and insurance","fsr","bnk"),
("Financial services and insurance","fsr","sec"),
("Financial services and insurance","fsr","ins"),
("Financial services and insurance","fsr","fin"),
("Housing and utilities","utl","hou"),
("Housing and utilities","utl","ore"),
("Recreation services","rsr","rnt"),
("Other services","osr","leg"),
("Other services","osr","com"),
("Other services","osr","tsv"),
("Other services","osr","man"),
("Other services","osr","adm"),
("Housing and utilities","utl","wst"),
("Household consumption expenditures (for services)","hce","edu"),
("Health care","hea","amb"),
("Health care","hea","hos"),
("Health care","hea","nrs"),
("Health care","hea","soc"),
("Recreation services","rsr","art"),
("Recreation services","rsr","rec"),
("Recreation services","rsr","amd"),
("Food services and accommodations","htl","res"),
("Other services","osr","osv"),
("Gross output of nonprofit institutions","npi","fdd"),
("Gross output of nonprofit institutions","npi","fnd"),
("Gross output of nonprofit institutions","npi","fen"),
("Gross output of nonprofit institutions","npi","slg"),
("Gross output of nonprofit institutions","npi","sle"),
("Gross output of nonprofit institutions","npi","use"),
("Gross output of nonprofit institutions","npi","oth"),
#("Personal consumption expenditures","pce",missing),
#("Goods","gds",missing),
#("Durable goods","dur",missing),
#("Nondurable goods","ndr",missing),
#("Services","ser",missing),
#("Final consumption expenditures of nonprofit institutions serving households (NPISHs)","npish",missing),
#("Less: Receipts from sales of goods and services by nonprofit institutions","nps",missing),
],[:pce_description,:pce,:i])
push!(notations,notation_link(:Description,pce_map,:pce_description,:i,:i))
return notations
end
function faf_notations()
notations = []
region = regions()
push!(notations, notation_link(:dms_origst,region,:fips_state,:region_abbv,:dms_orig))
push!(notations, notation_link(:dms_destst,region,:fips_state,:region_abbv,:dms_dest))
sctg2 = DataFrame([
(1, "agr"),
(2, "agr"),
(3, "agr"),
(4, "agr"),
(5, "agr"),
(1, "fof"),
(25, "fof"),
(16, "oil"),
(19, "oil"),
(10, "min"),
(11, "min"),
(12, "min"),
(13, "min"),
(14, "min"),
(15, "min"),
(10, "smn"),
(11, "smn"),
(12, "smn"),
(13, "smn"),
(14, "smn"),
(15, "smn"),
(26, "wpd"),
(31, "nmp"),
(32, "pmt"),
(33, "pmt"),
(32, "fmt"),
(33, "fmt"),
(34, "mch"),
(35, "cep"),
(35, "eec"),
(36, "mot"),
(37, "ote"),
(39, "fpd"),
(40, "mmf"),
(6, "fbp"),
(7, "fbp"),
(8, "fbp"),
(9, "fbp"),
(30, "tex"),
(30, "alt"),
(27, "ppd"),
(28, "ppd"),
(29, "pri"),
(17, "pet"),
(18, "pet"),
(19, "pet"),
(20, "che"),
(21, "che"),
(22, "che"),
(23, "che"),
(24, "pla"),
(41, "oth"),
(43, "oth"),
(41, "use"),
(43, "use")
], [:sctg2,:i])
push!(notations, notation_link(:sctg2,sctg2,:sctg2,:i,:i))
years = DataFrame([
("1997", "1997"),
("1997", "1998"),
("1997", "1999"),
("2002", "2000"),
("2002", "2001"),
("2002", "2002"),
("2002", "2003"),
("2002", "2004"),
("2007", "2005"),
("2007", "2006"),
("2007", "2007"),
("2007", "2008"),
("2007", "2009"),
("2012", "2010"),
("2012", "2011"),
("2012", "2012"),
("2012", "2013"),
("2012", "2014"),
("2017", "2015"),
("2017", "2016"),
("2017", "2017"),
("2018", "2018"),
("2019", "2019"),
("2020", "2020"),
("2021", "2021"),
],[:faf_year,:year])
push!(notations, notation_link(:year,years,:faf_year,:year,:year))
return notations
end
function usatrd_notations()
notations = []
region = regions()
push!(notations,notation_link(:State,region,:region_fullname,:region_abbv,:region_abbv))
naics_map = DataFrame([
("1111", :agr),
("1112", :agr),
("1113", :agr),
("1114", :agr),
("1119", :agr),
("1121", :agr),
("1122", :agr),
("1123", :agr),
("1124", :agr),
("1125", :agr),
("1129", :agr),
("1132", :fof),
("1133", :fof),
("1141", :fof),
("2111", :oil),
("2121", :min),
("2122", :min),
("2123", :min),
("3111", :fbp),
("3112", :fbp),
("3113", :fbp),
("3114", :fbp),
("3115", :fbp),
("3116", :fbp),
("3117", :fbp),
("3118", :fbp),
("3119", :fbp),
("3121", :fbp),
("3122", :fbp),
("3131", :tex),
("3132", :tex),
("3133", :tex),
("3141", :tex),
("3149", :tex),
("3151", :alt),
("3152", :alt),
("3159", :alt),
("3161", :alt),
("3162", :alt),
("3169", :alt),
("3211", :wpd),
("3212", :wpd),
("3219", :wpd),
("3221", :ppd),
("3222", :ppd),
("3231", :pri),
("3241", :pet),
("3251", :che),
("3252", :che),
("3253", :che),
("3254", :che),
("3255", :che),
("3256", :che),
("3259", :che),
("3261", :pla),
("3262", :pla),
("3271", :nmp),
("3272", :nmp),
("3273", :nmp),
("3274", :nmp),
("3279", :nmp),
("3311", :pmt),
("3312", :pmt),
("3313", :pmt),
("3314", :pmt),
("3315", :fmt),
("3321", :fmt),
("3322", :fmt),
("3323", :fmt),
("3324", :fmt),
("3325", :fmt),
("3326", :fmt),
("3327", :fmt),
("3329", :fmt),
("3331", :fmt),
("3332", :mch),
("3333", :mch),
("3334", :mch),
("3335", :mch),
("3336", :mch),
("3339", :mch),
("3341", :cep),
("3342", :cep),
("3343", :cep),
("3344", :cep),
("3345", :cep),
("3346", :cep),
("3351", :eec),
("3352", :eec),
("3353", :eec),
("3359", :eec),
("3361", :mot),
("3362", :mot),
("3363", :mot),
("3364", :ote),
("3365", :ote),
("3366", :ote),
("3369", :ote),
("3371", :fpd),
("3372", :fpd),
("3379", :fpd),
("3391", :mmf),
("3399", :mmf),
("5112", :pub),
("9100", :use),
("9200", :use),
("9300", :use),
("9800", :oth),
("9900", :oth),
], [:naics,:i])
push!(notations,notation_link(:naics,naics_map,:naics,:i,:i))
return notations
end
function usatrd_shares_notations()
notations = []
region = regions()
push!(notations,notation_link(:State,region,:region_fullname,:region_abbv,:region_abbv))
return notations
end
function sgf_notations()
notations = []
region = regions()
push!(notations,notation_link(:government_code,region,:sgf_code,:region_abbv,:region_abbv))
sgf_codes = DataFrame([
("Education","educat","E12","edu"),
("Education","educat","E16","edu"),
("Education","educat","E18","edu"),
("Education","educat","E21","edu"),
("Education","educat","F12","edu"),
("Education","educat","F16","edu"),
("Education","educat","F18","edu"),
("Education","educat","F21","edu"),
("Education","educat","G12","edu"),
("Education","educat","G16","edu"),
("Education","educat","G18","edu"),
("Education","educat","G21","edu"),
("Education","educat","J19","edu"),
("Education","educat","M12","edu"),
("Education","educat","M18","edu"),
("Education","educat","M21","edu"),
("Education","educat","Q12","edu"),
("Education","educat","Q18","edu"),
("Public welfare","pubwel","E74","tex"),
("Public welfare","pubwel","E74","alt"),
("Public welfare","pubwel","E74","wpd"),
("Public welfare","pubwel","E74","ppd"),
("Public welfare","pubwel","E74","pri"),
("Public welfare","pubwel","E74","wst"),
("Public welfare","pubwel","E74","soc"),
("Public welfare","pubwel","E75","tex"),
("Public welfare","pubwel","E75","alt"),
("Public welfare","pubwel","E75","wpd"),
("Public welfare","pubwel","E75","ppd"),
("Public welfare","pubwel","E75","pri"),
("Public welfare","pubwel","E75","wst"),
("Public welfare","pubwel","E75","soc"),
("Public welfare","pubwel","E77","tex"),
("Public welfare","pubwel","E77","alt"),
("Public welfare","pubwel","E77","wpd"),
("Public welfare","pubwel","E77","ppd"),
("Public welfare","pubwel","E77","pri"),
("Public welfare","pubwel","E77","wst"),
("Public welfare","pubwel","E77","soc"),
("Public welfare","pubwel","E79","tex"),
("Public welfare","pubwel","E79","alt"),
("Public welfare","pubwel","E79","wpd"),
("Public welfare","pubwel","E79","ppd"),
("Public welfare","pubwel","E79","pri"),
("Public welfare","pubwel","E79","wst"),
("Public welfare","pubwel","E79","soc"),
("Public welfare","pubwel","F77","tex"),
("Public welfare","pubwel","F77","alt"),
("Public welfare","pubwel","F77","wpd"),
("Public welfare","pubwel","F77","ppd"),
("Public welfare","pubwel","F77","pri"),
("Public welfare","pubwel","F77","wst"),
("Public welfare","pubwel","F77","soc"),
("Public welfare","pubwel","F79","tex"),
("Public welfare","pubwel","F79","alt"),
("Public welfare","pubwel","F79","wpd"),
("Public welfare","pubwel","F79","ppd"),
("Public welfare","pubwel","F79","pri"),
("Public welfare","pubwel","F79","wst"),
("Public welfare","pubwel","F79","soc"),
("Public welfare","pubwel","G77","tex"),
("Public welfare","pubwel","G77","alt"),
("Public welfare","pubwel","G77","wpd"),
("Public welfare","pubwel","G77","ppd"),
("Public welfare","pubwel","G77","pri"),
("Public welfare","pubwel","G77","wst"),
("Public welfare","pubwel","G77","soc"),
("Public welfare","pubwel","G79","tex"),
("Public welfare","pubwel","G79","alt"),
("Public welfare","pubwel","G79","wpd"),
("Public welfare","pubwel","G79","ppd"),
("Public welfare","pubwel","G79","pri"),
("Public welfare","pubwel","G79","wst"),
("Public welfare","pubwel","G79","soc"),
("Public welfare","pubwel","J67","tex"),
("Public welfare","pubwel","J67","alt"),
("Public welfare","pubwel","J67","wpd"),
("Public welfare","pubwel","J67","ppd"),
("Public welfare","pubwel","J67","pri"),
("Public welfare","pubwel","J67","wst"),
("Public welfare","pubwel","J67","soc"),
("Public welfare","pubwel","J68","tex"),
("Public welfare","pubwel","J68","alt"),
("Public welfare","pubwel","J68","wpd"),
("Public welfare","pubwel","J68","ppd"),
("Public welfare","pubwel","J68","pri"),
("Public welfare","pubwel","J68","wst"),
("Public welfare","pubwel","J68","soc"),
("Public welfare","pubwel","M67","tex"),
("Public welfare","pubwel","M67","alt"),
("Public welfare","pubwel","M67","wpd"),
("Public welfare","pubwel","M67","ppd"),
("Public welfare","pubwel","M67","pri"),
("Public welfare","pubwel","M67","wst"),
("Public welfare","pubwel","M67","soc"),
("Public welfare","pubwel","M68","tex"),
("Public welfare","pubwel","M68","alt"),
("Public welfare","pubwel","M68","wpd"),
("Public welfare","pubwel","M68","ppd"),
("Public welfare","pubwel","M68","pri"),
("Public welfare","pubwel","M68","wst"),
("Public welfare","pubwel","M68","soc"),
("Public welfare","pubwel","M79","tex"),
("Public welfare","pubwel","M79","alt"),
("Public welfare","pubwel","M79","wpd"),
("Public welfare","pubwel","M79","ppd"),
("Public welfare","pubwel","M79","pri"),
("Public welfare","pubwel","M79","wst"),
("Public welfare","pubwel","M79","soc"),
("Public welfare","pubwel","S67","tex"),
("Public welfare","pubwel","S67","alt"),
("Public welfare","pubwel","S67","wpd"),
("Public welfare","pubwel","S67","ppd"),
("Public welfare","pubwel","S67","pri"),
("Public welfare","pubwel","S67","wst"),
("Public welfare","pubwel","S67","soc"),
("Hospitals","hosptl","E36","hos"),
("Hospitals","hosptl","F36","hos"),
("Hospitals","hosptl","G36","hos"),
("Hospitals","hosptl","M36","hos"),
("Health","health","E32","amb"),
("Health","health","E32","nrs"),
("Health","health","F32","amb"),
("Health","health","F32","nrs"),
("Health","health","G32","amb"),
("Health","health","G32","nrs"),
("Health","health","M32","amb"),
("Health","health","M32","nrs"),
("Highways","hghway","E44","con"),
("Highways","hghway","E44","air"),
("Highways","hghway","E44","trn"),
("Highways","hghway","E44","wtt"),
("Highways","hghway","E44","trk"),
("Highways","hghway","E44","grd"),
("Highways","hghway","E44","pip"),
("Highways","hghway","E44","otr"),
("Highways","hghway","M44","con"),
("Highways","hghway","M44","air"),
("Highways","hghway","M44","trn"),
("Highways","hghway","M44","wtt"),
("Highways","hghway","M44","trk"),
("Highways","hghway","M44","grd"),
("Highways","hghway","M44","pip"),
("Highways","hghway","M44","otr"),
("Highways","hghway","F44","con"),
("Highways","hghway","F44","air"),
("Highways","hghway","F44","trn"),
("Highways","hghway","F44","wtt"),
("Highways","hghway","F44","trk"),
("Highways","hghway","F44","grd"),
("Highways","hghway","F44","pip"),
("Highways","hghway","F44","otr"),
("Highways","hghway","G44","con"),
("Highways","hghway","G44","air"),
("Highways","hghway","G44","trn"),
("Highways","hghway","G44","wtt"),
("Highways","hghway","G44","trk"),
("Highways","hghway","G44","grd"),
("Highways","hghway","G44","pip"),
("Highways","hghway","G44","otr"),
("Highways","hghway","E45","con"),
("Highways","hghway","E45","air"),
("Highways","hghway","E45","trn"),
("Highways","hghway","E45","wtt"),
("Highways","hghway","E45","trk"),
("Highways","hghway","E45","grd"),
("Highways","hghway","E45","pip"),
("Highways","hghway","E45","otr"),
("Highways","hghway","F45","con"),
("Highways","hghway","F45","air"),
("Highways","hghway","F45","trn"),
("Highways","hghway","F45","wtt"),
("Highways","hghway","F45","trk"),
("Highways","hghway","F45","grd"),
("Highways","hghway","F45","pip"),
("Highways","hghway","F45","otr"),
("Highways","hghway","G45","con"),
("Highways","hghway","G45","air"),
("Highways","hghway","G45","trn"),
("Highways","hghway","G45","wtt"),
("Highways","hghway","G45","trk"),
("Highways","hghway","G45","grd"),
("Highways","hghway","G45","pip"),
("Highways","hghway","G45","otr"),
("Police protection","police","E62","fdd"),
("Police protection","police","E62","fnd"),
("Police protection","police","E62","fen"),
("Police protection","police","E62","slg"),
("Police protection","police","E62","sle"),
("Police protection","police","F62","fdd"),
("Police protection","police","F62","fnd"),
("Police protection","police","F62","fen"),
("Police protection","police","F62","slg"),
("Police protection","police","F62","sle"),
("Police protection","police","G62","fdd"),
("Police protection","police","G62","fnd"),
("Police protection","police","G62","fen"),
("Police protection","police","G62","slg"),
("Police protection","police","G62","sle"),
("Police protection","police","M62","fdd"),
("Police protection","police","M62","fnd"),
("Police protection","police","M62","fen"),
("Police protection","police","M62","slg"),
("Police protection","police","M62","sle"),
("Correction","correc","E04","fdd"),
("Correction","correc","E04","fnd"),
("Correction","correc","E04","fen"),
("Correction","correc","E04","slg"),
("Correction","correc","E04","sle"),
("Correction","correc","E05","fdd"),
("Correction","correc","E05","fnd"),
("Correction","correc","E05","fen"),
("Correction","correc","E05","slg"),
("Correction","correc","E05","sle"),
("Correction","correc","F04","fdd"),
("Correction","correc","F04","fnd"),
("Correction","correc","F04","fen"),
("Correction","correc","F04","slg"),
("Correction","correc","F04","sle"),
("Correction","correc","F05","fdd"),
("Correction","correc","F05","fnd"),
("Correction","correc","F05","fen"),
("Correction","correc","F05","slg"),
("Correction","correc","F05","sle"),
("Correction","correc","G04","fdd"),
("Correction","correc","G04","fnd"),
("Correction","correc","G04","fen"),
("Correction","correc","G04","slg"),
("Correction","correc","G04","sle"),
("Correction","correc","G05","fdd"),
("Correction","correc","G05","fnd"),
("Correction","correc","G05","fen"),
("Correction","correc","G05","slg"),
("Correction","correc","G05","sle"),
("Correction","correc","M04","fdd"),
("Correction","correc","M04","fnd"),
("Correction","correc","M04","fen"),
("Correction","correc","M04","slg"),
("Correction","correc","M04","sle"),
("Correction","correc","M05","fdd"),
("Correction","correc","M05","fnd"),
("Correction","correc","M05","fen"),
("Correction","correc","M05","slg"),
("Correction","correc","M05","sle"),
("Natural resources","natres","E54","agr"),
("Natural resources","natres","E54","oil"),
("Natural resources","natres","E54","min"),
("Natural resources","natres","E54","smn"),
("Natural resources","natres","E55","agr"),
("Natural resources","natres","E55","oil"),
("Natural resources","natres","E55","min"),
("Natural resources","natres","E55","smn"),
("Natural resources","natres","E56","agr"),
("Natural resources","natres","E56","oil"),
("Natural resources","natres","E56","min"),
("Natural resources","natres","E56","smn"),
("Natural resources","natres","E59","agr"),
("Natural resources","natres","E59","oil"),
("Natural resources","natres","E59","min"),
("Natural resources","natres","E59","smn"),
("Natural resources","natres","F54","agr"),
("Natural resources","natres","F54","oil"),
("Natural resources","natres","F54","min"),
("Natural resources","natres","F54","smn"),
("Natural resources","natres","F55","agr"),
("Natural resources","natres","F55","oil"),
("Natural resources","natres","F55","min"),
("Natural resources","natres","F55","smn"),
("Natural resources","natres","F56","agr"),
("Natural resources","natres","F56","oil"),
("Natural resources","natres","F56","min"),
("Natural resources","natres","F56","smn"),
("Natural resources","natres","F59","agr"),
("Natural resources","natres","F59","oil"),
("Natural resources","natres","F59","min"),
("Natural resources","natres","F59","smn"),
("Natural resources","natres","G54","agr"),
("Natural resources","natres","G54","oil"),
("Natural resources","natres","G54","min"),
("Natural resources","natres","G54","smn"),
("Natural resources","natres","G55","agr"),
("Natural resources","natres","G55","oil"),
("Natural resources","natres","G55","min"),
("Natural resources","natres","G55","smn"),
("Natural resources","natres","G56","agr"),
("Natural resources","natres","G56","oil"),
("Natural resources","natres","G56","min"),
("Natural resources","natres","G56","smn"),
("Natural resources","natres","G59","agr"),
("Natural resources","natres","G59","oil"),
("Natural resources","natres","G59","min"),
("Natural resources","natres","G59","smn"),
("Natural resources","natres","M54","agr"),
("Natural resources","natres","M54","oil"),
("Natural resources","natres","M54","min"),
("Natural resources","natres","M54","smn"),
("Natural resources","natres","M55","agr"),
("Natural resources","natres","M55","oil"),
("Natural resources","natres","M55","min"),
("Natural resources","natres","M55","smn"),
("Natural resources","natres","M56","agr"),
("Natural resources","natres","M56","oil"),
("Natural resources","natres","M56","min"),
("Natural resources","natres","M56","smn"),
("Natural resources","natres","M59","agr"),
("Natural resources","natres","M59","oil"),
("Natural resources","natres","M59","min"),
("Natural resources","natres","M59","smn"),
("Parks and recreation","parkrc","E61","fof"),
("Parks and recreation","parkrc","E61","art"),
("Parks and recreation","parkrc","E61","rec"),
("Parks and recreation","parkrc","E61","amd"),
("Parks and recreation","parkrc","F61","fof"),
("Parks and recreation","parkrc","F61","art"),
("Parks and recreation","parkrc","F61","rec"),
("Parks and recreation","parkrc","F61","amd"),
("Parks and recreation","parkrc","G61","fof"),
("Parks and recreation","parkrc","G61","art"),
("Parks and recreation","parkrc","G61","rec"),
("Parks and recreation","parkrc","G61","amd"),
("Parks and recreation","parkrc","M61","fof"),
("Parks and recreation","parkrc","M61","art"),
("Parks and recreation","parkrc","M61","rec"),
("Parks and recreation","parkrc","M61","amd"),
("Governmental administration","govadm","E23","wrh"),
("Governmental administration","govadm","E23","pub"),
("Governmental administration","govadm","E23","mov"),
("Governmental administration","govadm","E23","brd"),
("Governmental administration","govadm","E23","dat"),
("Governmental administration","govadm","E23","hou"),
("Governmental administration","govadm","E23","ore"),
("Governmental administration","govadm","E23","rnt"),
("Governmental administration","govadm","E23","leg"),
("Governmental administration","govadm","E23","com"),
("Governmental administration","govadm","E23","tsv"),
("Governmental administration","govadm","E23","man"),
("Governmental administration","govadm","E23","adm"),
("Governmental administration","govadm","E23","fdd"),
("Governmental administration","govadm","E23","fnd"),
("Governmental administration","govadm","E23","fen"),
("Governmental administration","govadm","E23","slg"),
("Governmental administration","govadm","E23","sle"),
("Governmental administration","govadm","E25","wrh"),
("Governmental administration","govadm","E25","pub"),
("Governmental administration","govadm","E25","mov"),
("Governmental administration","govadm","E25","brd"),
("Governmental administration","govadm","E25","dat"),
("Governmental administration","govadm","E25","hou"),
("Governmental administration","govadm","E25","ore"),
("Governmental administration","govadm","E25","rnt"),
("Governmental administration","govadm","E25","leg"),
("Governmental administration","govadm","E25","com"),
("Governmental administration","govadm","E25","tsv"),
("Governmental administration","govadm","E25","man"),
("Governmental administration","govadm","E25","adm"),
("Governmental administration","govadm","E25","fdd"),
("Governmental administration","govadm","E25","fnd"),
("Governmental administration","govadm","E25","fen"),
("Governmental administration","govadm","E25","slg"),
("Governmental administration","govadm","E25","sle"),
("Governmental administration","govadm","E26","wrh"),
("Governmental administration","govadm","E26","pub"),
("Governmental administration","govadm","E26","mov"),
("Governmental administration","govadm","E26","brd"),
("Governmental administration","govadm","E26","dat"),
("Governmental administration","govadm","E26","hou"),
("Governmental administration","govadm","E26","ore"),
("Governmental administration","govadm","E26","rnt"),
("Governmental administration","govadm","E26","leg"),
("Governmental administration","govadm","E26","com"),
("Governmental administration","govadm","E26","tsv"),
("Governmental administration","govadm","E26","man"),
("Governmental administration","govadm","E26","adm"),
("Governmental administration","govadm","E26","fdd"),
("Governmental administration","govadm","E26","fnd"),
("Governmental administration","govadm","E26","fen"),
("Governmental administration","govadm","E26","slg"),
("Governmental administration","govadm","E26","sle"),
("Governmental administration","govadm","E29","wrh"),
("Governmental administration","govadm","E29","pub"),
("Governmental administration","govadm","E29","mov"),
("Governmental administration","govadm","E29","brd"),
("Governmental administration","govadm","E29","dat"),
("Governmental administration","govadm","E29","hou"),
("Governmental administration","govadm","E29","ore"),
("Governmental administration","govadm","E29","rnt"),
("Governmental administration","govadm","E29","leg"),
("Governmental administration","govadm","E29","com"),
("Governmental administration","govadm","E29","tsv"),
("Governmental administration","govadm","E29","man"),
("Governmental administration","govadm","E29","adm"),
("Governmental administration","govadm","E29","fdd"),
("Governmental administration","govadm","E29","fnd"),
("Governmental administration","govadm","E29","fen"),
("Governmental administration","govadm","E29","slg"),
("Governmental administration","govadm","E29","sle"),
("Governmental administration","govadm","E31","wrh"),
("Governmental administration","govadm","E31","pub"),
("Governmental administration","govadm","E31","mov"),
("Governmental administration","govadm","E31","brd"),
("Governmental administration","govadm","E31","dat"),
("Governmental administration","govadm","E31","hou"),
("Governmental administration","govadm","E31","ore"),
("Governmental administration","govadm","E31","rnt"),
("Governmental administration","govadm","E31","leg"),
("Governmental administration","govadm","E31","com"),
("Governmental administration","govadm","E31","tsv"),
("Governmental administration","govadm","E31","man"),
("Governmental administration","govadm","E31","adm"),
("Governmental administration","govadm","E31","fdd"),
("Governmental administration","govadm","E31","fnd"),
("Governmental administration","govadm","E31","fen"),
("Governmental administration","govadm","E31","slg"),
("Governmental administration","govadm","E31","sle"),
("Governmental administration","govadm","F23","wrh"),
("Governmental administration","govadm","F23","pub"),
("Governmental administration","govadm","F23","mov"),
("Governmental administration","govadm","F23","brd"),
("Governmental administration","govadm","F23","dat"),
("Governmental administration","govadm","F23","hou"),
("Governmental administration","govadm","F23","ore"),
("Governmental administration","govadm","F23","rnt"),
("Governmental administration","govadm","F23","leg"),
("Governmental administration","govadm","F23","com"),
("Governmental administration","govadm","F23","tsv"),
("Governmental administration","govadm","F23","man"),
("Governmental administration","govadm","F23","adm"),
("Governmental administration","govadm","F23","fdd"),
("Governmental administration","govadm","F23","fnd"),
("Governmental administration","govadm","F23","fen"),
("Governmental administration","govadm","F23","slg"),
("Governmental administration","govadm","F23","sle"),
("Governmental administration","govadm","F25","wrh"),
("Governmental administration","govadm","F25","pub"),
("Governmental administration","govadm","F25","mov"),
("Governmental administration","govadm","F25","brd"),
("Governmental administration","govadm","F25","dat"),
("Governmental administration","govadm","F25","hou"),
("Governmental administration","govadm","F25","ore"),
("Governmental administration","govadm","F25","rnt"),
("Governmental administration","govadm","F25","leg"),
("Governmental administration","govadm","F25","com"),
("Governmental administration","govadm","F25","tsv"),
("Governmental administration","govadm","F25","man"),
("Governmental administration","govadm","F25","adm"),
("Governmental administration","govadm","F25","fdd"),
("Governmental administration","govadm","F25","fnd"),
("Governmental administration","govadm","F25","fen"),
("Governmental administration","govadm","F25","slg"),
("Governmental administration","govadm","F25","sle"),
("Governmental administration","govadm","F26","wrh"),
("Governmental administration","govadm","F26","pub"),
("Governmental administration","govadm","F26","mov"),
("Governmental administration","govadm","F26","brd"),
("Governmental administration","govadm","F26","dat"),
("Governmental administration","govadm","F26","hou"),
("Governmental administration","govadm","F26","ore"),
("Governmental administration","govadm","F26","rnt"),
("Governmental administration","govadm","F26","leg"),
("Governmental administration","govadm","F26","com"),
("Governmental administration","govadm","F26","tsv"),
("Governmental administration","govadm","F26","man"),
("Governmental administration","govadm","F26","adm"),
("Governmental administration","govadm","F26","fdd"),
("Governmental administration","govadm","F26","fnd"),
("Governmental administration","govadm","F26","fen"),
("Governmental administration","govadm","F26","slg"),
("Governmental administration","govadm","F26","sle"),
("Governmental administration","govadm","F29","wrh"),
("Governmental administration","govadm","F29","pub"),
("Governmental administration","govadm","F29","mov"),
("Governmental administration","govadm","F29","brd"),
("Governmental administration","govadm","F29","dat"),
("Governmental administration","govadm","F29","hou"),
("Governmental administration","govadm","F29","ore"),
("Governmental administration","govadm","F29","rnt"),
("Governmental administration","govadm","F29","leg"),
("Governmental administration","govadm","F29","com"),
("Governmental administration","govadm","F29","tsv"),
("Governmental administration","govadm","F29","man"),
("Governmental administration","govadm","F29","adm"),
("Governmental administration","govadm","F29","fdd"),
("Governmental administration","govadm","F29","fnd"),
("Governmental administration","govadm","F29","fen"),
("Governmental administration","govadm","F29","slg"),
("Governmental administration","govadm","F29","sle"),
("Governmental administration","govadm","F31","wrh"),
("Governmental administration","govadm","F31","pub"),
("Governmental administration","govadm","F31","mov"),
("Governmental administration","govadm","F31","brd"),
("Governmental administration","govadm","F31","dat"),
("Governmental administration","govadm","F31","hou"),
("Governmental administration","govadm","F31","ore"),
("Governmental administration","govadm","F31","rnt"),
("Governmental administration","govadm","F31","leg"),
("Governmental administration","govadm","F31","com"),
("Governmental administration","govadm","F31","tsv"),
("Governmental administration","govadm","F31","man"),
("Governmental administration","govadm","F31","adm"),
("Governmental administration","govadm","F31","fdd"),
("Governmental administration","govadm","F31","fnd"),
("Governmental administration","govadm","F31","fen"),
("Governmental administration","govadm","F31","slg"),
("Governmental administration","govadm","F31","sle"),
("Governmental administration","govadm","G23","wrh"),
("Governmental administration","govadm","G23","pub"),
("Governmental administration","govadm","G23","mov"),
("Governmental administration","govadm","G23","brd"),
("Governmental administration","govadm","G23","dat"),
("Governmental administration","govadm","G23","hou"),
("Governmental administration","govadm","G23","ore"),
("Governmental administration","govadm","G23","rnt"),
("Governmental administration","govadm","G23","leg"),
("Governmental administration","govadm","G23","com"),
("Governmental administration","govadm","G23","tsv"),
("Governmental administration","govadm","G23","man"),
("Governmental administration","govadm","G23","adm"),
("Governmental administration","govadm","G23","fdd"),
("Governmental administration","govadm","G23","fnd"),
("Governmental administration","govadm","G23","fen"),
("Governmental administration","govadm","G23","slg"),
("Governmental administration","govadm","G23","sle"),
("Governmental administration","govadm","G25","wrh"),
("Governmental administration","govadm","G25","pub"),
("Governmental administration","govadm","G25","mov"),
("Governmental administration","govadm","G25","brd"),
("Governmental administration","govadm","G25","dat"),
("Governmental administration","govadm","G25","hou"),
("Governmental administration","govadm","G25","ore"),
("Governmental administration","govadm","G25","rnt"),
("Governmental administration","govadm","G25","leg"),
("Governmental administration","govadm","G25","com"),
("Governmental administration","govadm","G25","tsv"),
("Governmental administration","govadm","G25","man"),
("Governmental administration","govadm","G25","adm"),
("Governmental administration","govadm","G25","fdd"),
("Governmental administration","govadm","G25","fnd"),
("Governmental administration","govadm","G25","fen"),
("Governmental administration","govadm","G25","slg"),
("Governmental administration","govadm","G25","sle"),
("Governmental administration","govadm","G26","wrh"),
("Governmental administration","govadm","G26","pub"),
("Governmental administration","govadm","G26","mov"),
("Governmental administration","govadm","G26","brd"),
("Governmental administration","govadm","G26","dat"),
("Governmental administration","govadm","G26","hou"),
("Governmental administration","govadm","G26","ore"),
("Governmental administration","govadm","G26","rnt"),
("Governmental administration","govadm","G26","leg"),
("Governmental administration","govadm","G26","com"),
("Governmental administration","govadm","G26","tsv"),
("Governmental administration","govadm","G26","man"),
("Governmental administration","govadm","G26","adm"),
("Governmental administration","govadm","G26","fdd"),
("Governmental administration","govadm","G26","fnd"),
("Governmental administration","govadm","G26","fen"),
("Governmental administration","govadm","G26","slg"),
("Governmental administration","govadm","G26","sle"),
("Governmental administration","govadm","G29","wrh"),
("Governmental administration","govadm","G29","pub"),
("Governmental administration","govadm","G29","mov"),
("Governmental administration","govadm","G29","brd"),
("Governmental administration","govadm","G29","dat"),
("Governmental administration","govadm","G29","hou"),
("Governmental administration","govadm","G29","ore"),
("Governmental administration","govadm","G29","rnt"),
("Governmental administration","govadm","G29","leg"),
("Governmental administration","govadm","G29","com"),
("Governmental administration","govadm","G29","tsv"),
("Governmental administration","govadm","G29","man"),
("Governmental administration","govadm","G29","adm"),
("Governmental administration","govadm","G29","fdd"),
("Governmental administration","govadm","G29","fnd"),
("Governmental administration","govadm","G29","fen"),
("Governmental administration","govadm","G29","slg"),
("Governmental administration","govadm","G29","sle"),
("Governmental administration","govadm","G31","wrh"),
("Governmental administration","govadm","G31","pub"),
("Governmental administration","govadm","G31","mov"),
("Governmental administration","govadm","G31","brd"),
("Governmental administration","govadm","G31","dat"),
("Governmental administration","govadm","G31","hou"),
("Governmental administration","govadm","G31","ore"),
("Governmental administration","govadm","G31","rnt"),
("Governmental administration","govadm","G31","leg"),
("Governmental administration","govadm","G31","com"),
("Governmental administration","govadm","G31","tsv"),
("Governmental administration","govadm","G31","man"),
("Governmental administration","govadm","G31","adm"),
("Governmental administration","govadm","G31","fdd"),
("Governmental administration","govadm","G31","fnd"),
("Governmental administration","govadm","G31","fen"),
("Governmental administration","govadm","G31","slg"),
("Governmental administration","govadm","G31","sle"),
("Governmental administration","govadm","M23","wrh"),
("Governmental administration","govadm","M23","pub"),
("Governmental administration","govadm","M23","mov"),
("Governmental administration","govadm","M23","brd"),
("Governmental administration","govadm","M23","dat"),
("Governmental administration","govadm","M23","hou"),
("Governmental administration","govadm","M23","ore"),
("Governmental administration","govadm","M23","rnt"),
("Governmental administration","govadm","M23","leg"),
("Governmental administration","govadm","M23","com"),
("Governmental administration","govadm","M23","tsv"),
("Governmental administration","govadm","M23","man"),
("Governmental administration","govadm","M23","adm"),
("Governmental administration","govadm","M23","fdd"),
("Governmental administration","govadm","M23","fnd"),
("Governmental administration","govadm","M23","fen"),
("Governmental administration","govadm","M23","slg"),
("Governmental administration","govadm","M23","sle"),
("Governmental administration","govadm","M25","wrh"),
("Governmental administration","govadm","M25","pub"),
("Governmental administration","govadm","M25","mov"),
("Governmental administration","govadm","M25","brd"),
("Governmental administration","govadm","M25","dat"),
("Governmental administration","govadm","M25","hou"),
("Governmental administration","govadm","M25","ore"),
("Governmental administration","govadm","M25","rnt"),
("Governmental administration","govadm","M25","leg"),
("Governmental administration","govadm","M25","com"),
("Governmental administration","govadm","M25","tsv"),
("Governmental administration","govadm","M25","man"),
("Governmental administration","govadm","M25","adm"),
("Governmental administration","govadm","M25","fdd"),
("Governmental administration","govadm","M25","fnd"),
("Governmental administration","govadm","M25","fen"),
("Governmental administration","govadm","M25","slg"),
("Governmental administration","govadm","M25","sle"),
("Governmental administration","govadm","M29","wrh"),
("Governmental administration","govadm","M29","pub"),
("Governmental administration","govadm","M29","mov"),
("Governmental administration","govadm","M29","brd"),
("Governmental administration","govadm","M29","dat"),
("Governmental administration","govadm","M29","hou"),
("Governmental administration","govadm","M29","ore"),
("Governmental administration","govadm","M29","rnt"),
("Governmental administration","govadm","M29","leg"),
("Governmental administration","govadm","M29","com"),
("Governmental administration","govadm","M29","tsv"),
("Governmental administration","govadm","M29","man"),
("Governmental administration","govadm","M29","adm"),
("Governmental administration","govadm","M29","fdd"),
("Governmental administration","govadm","M29","fnd"),
("Governmental administration","govadm","M29","fen"),
("Governmental administration","govadm","M29","slg"),
("Governmental administration","govadm","M29","sle"),
("Interest on general debt","intgen","I89","bnk"),
("Interest on general debt","intgen","I89","sec"),
("Interest on general debt","intgen","I89","ins"),
("Interest on general debt","intgen","I89","fin"),
("Other and unallocable","othuna","E01","pet"),
("Other and unallocable","othuna","E01","che"),
("Other and unallocable","othuna","E01","pla"),
("Other and unallocable","othuna","E01","nmp"),
("Other and unallocable","othuna","E01","pmt"),
("Other and unallocable","othuna","E01","fmt"),
("Other and unallocable","othuna","E01","mch"),
("Other and unallocable","othuna","E01","cep"),
("Other and unallocable","othuna","E01","eec"),
("Other and unallocable","othuna","E01","mot"),
("Other and unallocable","othuna","E01","ote"),
("Other and unallocable","othuna","E01","fpd"),
("Other and unallocable","othuna","E01","mmf"),
("Other and unallocable","othuna","E01","wht"),
("Other and unallocable","othuna","E01","mvt"),
("Other and unallocable","othuna","E01","gmt"),
("Other and unallocable","othuna","E01","ott"),
("Other and unallocable","othuna","E01","osv"),
("Other and unallocable","othuna","E01","use"),
("Other and unallocable","othuna","E01","oth"),
("Other and unallocable","othuna","E03","pet"),
("Other and unallocable","othuna","E03","che"),
("Other and unallocable","othuna","E03","pla"),
("Other and unallocable","othuna","E03","nmp"),
("Other and unallocable","othuna","E03","pmt"),
("Other and unallocable","othuna","E03","fmt"),
("Other and unallocable","othuna","E03","mch"),
("Other and unallocable","othuna","E03","cep"),
("Other and unallocable","othuna","E03","eec"),
("Other and unallocable","othuna","E03","mot"),
("Other and unallocable","othuna","E03","ote"),
("Other and unallocable","othuna","E03","fpd"),
("Other and unallocable","othuna","E03","mmf"),
("Other and unallocable","othuna","E03","wht"),
("Other and unallocable","othuna","E03","mvt"),
("Other and unallocable","othuna","E03","gmt"),
("Other and unallocable","othuna","E03","ott"),
("Other and unallocable","othuna","E03","osv"),
("Other and unallocable","othuna","E03","use"),
("Other and unallocable","othuna","E03","oth"),
("Other and unallocable","othuna","E22","pet"),
("Other and unallocable","othuna","E22","che"),
("Other and unallocable","othuna","E22","pla"),
("Other and unallocable","othuna","E22","nmp"),
("Other and unallocable","othuna","E22","pmt"),
("Other and unallocable","othuna","E22","fmt"),
("Other and unallocable","othuna","E22","mch"),
("Other and unallocable","othuna","E22","cep"),
("Other and unallocable","othuna","E22","eec"),
("Other and unallocable","othuna","E22","mot"),
("Other and unallocable","othuna","E22","ote"),
("Other and unallocable","othuna","E22","fpd"),
("Other and unallocable","othuna","E22","mmf"),
("Other and unallocable","othuna","E22","wht"),
("Other and unallocable","othuna","E22","mvt"),
("Other and unallocable","othuna","E22","gmt"),
("Other and unallocable","othuna","E22","ott"),
("Other and unallocable","othuna","E22","osv"),
("Other and unallocable","othuna","E22","use"),
("Other and unallocable","othuna","E22","oth"),
("Other and unallocable","othuna","E50","pet"),
("Other and unallocable","othuna","E50","che"),
("Other and unallocable","othuna","E50","pla"),
("Other and unallocable","othuna","E50","nmp"),
("Other and unallocable","othuna","E50","pmt"),
("Other and unallocable","othuna","E50","fmt"),
("Other and unallocable","othuna","E50","mch"),
("Other and unallocable","othuna","E50","cep"),
("Other and unallocable","othuna","E50","eec"),
("Other and unallocable","othuna","E50","mot"),
("Other and unallocable","othuna","E50","ote"),
("Other and unallocable","othuna","E50","fpd"),
("Other and unallocable","othuna","E50","mmf"),
("Other and unallocable","othuna","E50","wht"),
("Other and unallocable","othuna","E50","mvt"),
("Other and unallocable","othuna","E50","gmt"),
("Other and unallocable","othuna","E50","ott"),
("Other and unallocable","othuna","E50","osv"),
("Other and unallocable","othuna","E50","use"),
("Other and unallocable","othuna","E50","oth"),
("Other and unallocable","othuna","E52","pet"),
("Other and unallocable","othuna","E52","che"),
("Other and unallocable","othuna","E52","pla"),
("Other and unallocable","othuna","E52","nmp"),
("Other and unallocable","othuna","E52","pmt"),
("Other and unallocable","othuna","E52","fmt"),
("Other and unallocable","othuna","E52","mch"),
("Other and unallocable","othuna","E52","cep"),
("Other and unallocable","othuna","E52","eec"),
("Other and unallocable","othuna","E52","mot"),
("Other and unallocable","othuna","E52","ote"),
("Other and unallocable","othuna","E52","fpd"),
("Other and unallocable","othuna","E52","mmf"),
("Other and unallocable","othuna","E52","wht"),
("Other and unallocable","othuna","E52","mvt"),
("Other and unallocable","othuna","E52","gmt"),
("Other and unallocable","othuna","E52","ott"),
("Other and unallocable","othuna","E52","osv"),
("Other and unallocable","othuna","E52","use"),
("Other and unallocable","othuna","E52","oth"),
("Other and unallocable","othuna","E60","pet"),
("Other and unallocable","othuna","E60","che"),
("Other and unallocable","othuna","E60","pla"),
("Other and unallocable","othuna","E60","nmp"),
("Other and unallocable","othuna","E60","pmt"),
("Other and unallocable","othuna","E60","fmt"),
("Other and unallocable","othuna","E60","mch"),
("Other and unallocable","othuna","E60","cep"),
("Other and unallocable","othuna","E60","eec"),
("Other and unallocable","othuna","E60","mot"),
("Other and unallocable","othuna","E60","ote"),
("Other and unallocable","othuna","E60","fpd"),
("Other and unallocable","othuna","E60","mmf"),
("Other and unallocable","othuna","E60","wht"),
("Other and unallocable","othuna","E60","mvt"),
("Other and unallocable","othuna","E60","gmt"),
("Other and unallocable","othuna","E60","ott"),
("Other and unallocable","othuna","E60","osv"),
("Other and unallocable","othuna","E60","use"),
("Other and unallocable","othuna","E60","oth"),
("Other and unallocable","othuna","E66","pet"),
("Other and unallocable","othuna","E66","che"),
("Other and unallocable","othuna","E66","pla"),
("Other and unallocable","othuna","E66","nmp"),
("Other and unallocable","othuna","E66","pmt"),
("Other and unallocable","othuna","E66","fmt"),
("Other and unallocable","othuna","E66","mch"),
("Other and unallocable","othuna","E66","cep"),
("Other and unallocable","othuna","E66","eec"),
("Other and unallocable","othuna","E66","mot"),
("Other and unallocable","othuna","E66","ote"),
("Other and unallocable","othuna","E66","fpd"),
("Other and unallocable","othuna","E66","mmf"),
("Other and unallocable","othuna","E66","wht"),
("Other and unallocable","othuna","E66","mvt"),
("Other and unallocable","othuna","E66","gmt"),
("Other and unallocable","othuna","E66","ott"),
("Other and unallocable","othuna","E66","osv"),
("Other and unallocable","othuna","E66","use"),
("Other and unallocable","othuna","E66","oth"),
("Other and unallocable","othuna","E80","pet"),
("Other and unallocable","othuna","E80","che"),
("Other and unallocable","othuna","E80","pla"),
("Other and unallocable","othuna","E80","nmp"),
("Other and unallocable","othuna","E80","pmt"),
("Other and unallocable","othuna","E80","fmt"),
("Other and unallocable","othuna","E80","mch"),
("Other and unallocable","othuna","E80","cep"),
("Other and unallocable","othuna","E80","eec"),
("Other and unallocable","othuna","E80","mot"),
("Other and unallocable","othuna","E80","ote"),
("Other and unallocable","othuna","E80","fpd"),
("Other and unallocable","othuna","E80","mmf"),
("Other and unallocable","othuna","E80","wht"),
("Other and unallocable","othuna","E80","mvt"),
("Other and unallocable","othuna","E80","gmt"),
("Other and unallocable","othuna","E80","ott"),
("Other and unallocable","othuna","E80","osv"),
("Other and unallocable","othuna","E80","use"),
("Other and unallocable","othuna","E80","oth"),
("Other and unallocable","othuna","E81","pet"),
("Other and unallocable","othuna","E81","che"),
("Other and unallocable","othuna","E81","pla"),
("Other and unallocable","othuna","E81","nmp"),
("Other and unallocable","othuna","E81","pmt"),
("Other and unallocable","othuna","E81","fmt"),
("Other and unallocable","othuna","E81","mch"),
("Other and unallocable","othuna","E81","cep"),
("Other and unallocable","othuna","E81","eec"),
("Other and unallocable","othuna","E81","mot"),
("Other and unallocable","othuna","E81","ote"),
("Other and unallocable","othuna","E81","fpd"),
("Other and unallocable","othuna","E81","mmf"),
("Other and unallocable","othuna","E81","wht"),
("Other and unallocable","othuna","E81","mvt"),
("Other and unallocable","othuna","E81","gmt"),
("Other and unallocable","othuna","E81","ott"),
("Other and unallocable","othuna","E81","osv"),
("Other and unallocable","othuna","E81","use"),
("Other and unallocable","othuna","E81","oth"),
("Other and unallocable","othuna","E85","pet"),
("Other and unallocable","othuna","E85","che"),
("Other and unallocable","othuna","E85","pla"),
("Other and unallocable","othuna","E85","nmp"),
("Other and unallocable","othuna","E85","pmt"),
("Other and unallocable","othuna","E85","fmt"),
("Other and unallocable","othuna","E85","mch"),
("Other and unallocable","othuna","E85","cep"),
("Other and unallocable","othuna","E85","eec"),
("Other and unallocable","othuna","E85","mot"),
("Other and unallocable","othuna","E85","ote"),
("Other and unallocable","othuna","E85","fpd"),
("Other and unallocable","othuna","E85","mmf"),
("Other and unallocable","othuna","E85","wht"),
("Other and unallocable","othuna","E85","mvt"),
("Other and unallocable","othuna","E85","gmt"),
("Other and unallocable","othuna","E85","ott"),
("Other and unallocable","othuna","E85","osv"),
("Other and unallocable","othuna","E85","use"),
("Other and unallocable","othuna","E85","oth"),
("Other and unallocable","othuna","E87","pet"),
("Other and unallocable","othuna","E87","che"),
("Other and unallocable","othuna","E87","pla"),
("Other and unallocable","othuna","E87","nmp"),
("Other and unallocable","othuna","E87","pmt"),
("Other and unallocable","othuna","E87","fmt"),
("Other and unallocable","othuna","E87","mch"),
("Other and unallocable","othuna","E87","cep"),
("Other and unallocable","othuna","E87","eec"),
("Other and unallocable","othuna","E87","mot"),
("Other and unallocable","othuna","E87","ote"),
("Other and unallocable","othuna","E87","fpd"),
("Other and unallocable","othuna","E87","mmf"),
("Other and unallocable","othuna","E87","wht"),
("Other and unallocable","othuna","E87","mvt"),
("Other and unallocable","othuna","E87","gmt"),
("Other and unallocable","othuna","E87","ott"),
("Other and unallocable","othuna","E87","osv"),
("Other and unallocable","othuna","E87","use"),
("Other and unallocable","othuna","E87","oth"),
("Other and unallocable","othuna","E89","pet"),
("Other and unallocable","othuna","E89","che"),
("Other and unallocable","othuna","E89","pla"),
("Other and unallocable","othuna","E89","nmp"),
("Other and unallocable","othuna","E89","pmt"),
("Other and unallocable","othuna","E89","fmt"),
("Other and unallocable","othuna","E89","mch"),
("Other and unallocable","othuna","E89","cep"),
("Other and unallocable","othuna","E89","eec"),
("Other and unallocable","othuna","E89","mot"),
("Other and unallocable","othuna","E89","ote"),
("Other and unallocable","othuna","E89","fpd"),
("Other and unallocable","othuna","E89","mmf"),
("Other and unallocable","othuna","E89","wht"),
("Other and unallocable","othuna","E89","mvt"),
("Other and unallocable","othuna","E89","gmt"),
("Other and unallocable","othuna","E89","ott"),
("Other and unallocable","othuna","E89","osv"),
("Other and unallocable","othuna","E89","use"),
("Other and unallocable","othuna","E89","oth"),
("Other and unallocable","othuna","F01","pet"),
("Other and unallocable","othuna","F01","che"),
("Other and unallocable","othuna","F01","pla"),
("Other and unallocable","othuna","F01","nmp"),
("Other and unallocable","othuna","F01","pmt"),
("Other and unallocable","othuna","F01","fmt"),
("Other and unallocable","othuna","F01","mch"),
("Other and unallocable","othuna","F01","cep"),
("Other and unallocable","othuna","F01","eec"),
("Other and unallocable","othuna","F01","mot"),
("Other and unallocable","othuna","F01","ote"),
("Other and unallocable","othuna","F01","fpd"),
("Other and unallocable","othuna","F01","mmf"),
("Other and unallocable","othuna","F01","wht"),
("Other and unallocable","othuna","F01","mvt"),
("Other and unallocable","othuna","F01","gmt"),
("Other and unallocable","othuna","F01","ott"),
("Other and unallocable","othuna","F01","osv"),
("Other and unallocable","othuna","F01","use"),
("Other and unallocable","othuna","F01","oth"),
("Other and unallocable","othuna","F03","pet"),
("Other and unallocable","othuna","F03","che"),
("Other and unallocable","othuna","F03","pla"),
("Other and unallocable","othuna","F03","nmp"),
("Other and unallocable","othuna","F03","pmt"),
("Other and unallocable","othuna","F03","fmt"),
("Other and unallocable","othuna","F03","mch"),
("Other and unallocable","othuna","F03","cep"),
("Other and unallocable","othuna","F03","eec"),
("Other and unallocable","othuna","F03","mot"),
("Other and unallocable","othuna","F03","ote"),
("Other and unallocable","othuna","F03","fpd"),
("Other and unallocable","othuna","F03","mmf"),
("Other and unallocable","othuna","F03","wht"),
("Other and unallocable","othuna","F03","mvt"),
("Other and unallocable","othuna","F03","gmt"),
("Other and unallocable","othuna","F03","ott"),
("Other and unallocable","othuna","F03","osv"),
("Other and unallocable","othuna","F03","use"),
("Other and unallocable","othuna","F03","oth"),
("Other and unallocable","othuna","F22","pet"),
("Other and unallocable","othuna","F22","che"),
("Other and unallocable","othuna","F22","pla"),
("Other and unallocable","othuna","F22","nmp"),
("Other and unallocable","othuna","F22","pmt"),
("Other and unallocable","othuna","F22","fmt"),
("Other and unallocable","othuna","F22","mch"),
("Other and unallocable","othuna","F22","cep"),
("Other and unallocable","othuna","F22","eec"),
("Other and unallocable","othuna","F22","mot"),
("Other and unallocable","othuna","F22","ote"),
("Other and unallocable","othuna","F22","fpd"),
("Other and unallocable","othuna","F22","mmf"),
("Other and unallocable","othuna","F22","wht"),
("Other and unallocable","othuna","F22","mvt"),
("Other and unallocable","othuna","F22","gmt"),
("Other and unallocable","othuna","F22","ott"),
("Other and unallocable","othuna","F22","osv"),
("Other and unallocable","othuna","F22","use"),
("Other and unallocable","othuna","F22","oth"),
("Other and unallocable","othuna","F50","pet"),
("Other and unallocable","othuna","F50","che"),
("Other and unallocable","othuna","F50","pla"),
("Other and unallocable","othuna","F50","nmp"),
("Other and unallocable","othuna","F50","pmt"),
("Other and unallocable","othuna","F50","fmt"),
("Other and unallocable","othuna","F50","mch"),
("Other and unallocable","othuna","F50","cep"),
("Other and unallocable","othuna","F50","eec"),
("Other and unallocable","othuna","F50","mot"),
("Other and unallocable","othuna","F50","ote"),
("Other and unallocable","othuna","F50","fpd"),
("Other and unallocable","othuna","F50","mmf"),
("Other and unallocable","othuna","F50","wht"),
("Other and unallocable","othuna","F50","mvt"),
("Other and unallocable","othuna","F50","gmt"),
("Other and unallocable","othuna","F50","ott"),
("Other and unallocable","othuna","F50","osv"),
("Other and unallocable","othuna","F50","use"),
("Other and unallocable","othuna","F50","oth"),
("Other and unallocable","othuna","F52","pet"),
("Other and unallocable","othuna","F52","che"),
("Other and unallocable","othuna","F52","pla"),
("Other and unallocable","othuna","F52","nmp"),
("Other and unallocable","othuna","F52","pmt"),
("Other and unallocable","othuna","F52","fmt"),
("Other and unallocable","othuna","F52","mch"),
("Other and unallocable","othuna","F52","cep"),
("Other and unallocable","othuna","F52","eec"),
("Other and unallocable","othuna","F52","mot"),
("Other and unallocable","othuna","F52","ote"),
("Other and unallocable","othuna","F52","fpd"),
("Other and unallocable","othuna","F52","mmf"),
("Other and unallocable","othuna","F52","wht"),
("Other and unallocable","othuna","F52","mvt"),
("Other and unallocable","othuna","F52","gmt"),
("Other and unallocable","othuna","F52","ott"),
("Other and unallocable","othuna","F52","osv"),
("Other and unallocable","othuna","F52","use"),
("Other and unallocable","othuna","F52","oth"),
("Other and unallocable","othuna","F60","pet"),
("Other and unallocable","othuna","F60","che"),
("Other and unallocable","othuna","F60","pla"),
("Other and unallocable","othuna","F60","nmp"),
("Other and unallocable","othuna","F60","pmt"),
("Other and unallocable","othuna","F60","fmt"),
("Other and unallocable","othuna","F60","mch"),
("Other and unallocable","othuna","F60","cep"),
("Other and unallocable","othuna","F60","eec"),
("Other and unallocable","othuna","F60","mot"),
("Other and unallocable","othuna","F60","ote"),
("Other and unallocable","othuna","F60","fpd"),
("Other and unallocable","othuna","F60","mmf"),
("Other and unallocable","othuna","F60","wht"),
("Other and unallocable","othuna","F60","mvt"),
("Other and unallocable","othuna","F60","gmt"),
("Other and unallocable","othuna","F60","ott"),
("Other and unallocable","othuna","F60","osv"),
("Other and unallocable","othuna","F60","use"),
("Other and unallocable","othuna","F60","oth"),
("Other and unallocable","othuna","F66","pet"),
("Other and unallocable","othuna","F66","che"),
("Other and unallocable","othuna","F66","pla"),
("Other and unallocable","othuna","F66","nmp"),
("Other and unallocable","othuna","F66","pmt"),
("Other and unallocable","othuna","F66","fmt"),
("Other and unallocable","othuna","F66","mch"),
("Other and unallocable","othuna","F66","cep"),
("Other and unallocable","othuna","F66","eec"),
("Other and unallocable","othuna","F66","mot"),
("Other and unallocable","othuna","F66","ote"),
("Other and unallocable","othuna","F66","fpd"),
("Other and unallocable","othuna","F66","mmf"),
("Other and unallocable","othuna","F66","wht"),
("Other and unallocable","othuna","F66","mvt"),
("Other and unallocable","othuna","F66","gmt"),
("Other and unallocable","othuna","F66","ott"),
("Other and unallocable","othuna","F66","osv"),
("Other and unallocable","othuna","F66","use"),
("Other and unallocable","othuna","F66","oth"),
("Other and unallocable","othuna","F80","pet"),
("Other and unallocable","othuna","F80","che"),
("Other and unallocable","othuna","F80","pla"),
("Other and unallocable","othuna","F80","nmp"),
("Other and unallocable","othuna","F80","pmt"),
("Other and unallocable","othuna","F80","fmt"),
("Other and unallocable","othuna","F80","mch"),
("Other and unallocable","othuna","F80","cep"),
("Other and unallocable","othuna","F80","eec"),
("Other and unallocable","othuna","F80","mot"),
("Other and unallocable","othuna","F80","ote"),
("Other and unallocable","othuna","F80","fpd"),
("Other and unallocable","othuna","F80","mmf"),
("Other and unallocable","othuna","F80","wht"),
("Other and unallocable","othuna","F80","mvt"),
("Other and unallocable","othuna","F80","gmt"),
("Other and unallocable","othuna","F80","ott"),
("Other and unallocable","othuna","F80","osv"),
("Other and unallocable","othuna","F80","use"),
("Other and unallocable","othuna","F80","oth"),
("Other and unallocable","othuna","F81","pet"),
("Other and unallocable","othuna","F81","che"),
("Other and unallocable","othuna","F81","pla"),
("Other and unallocable","othuna","F81","nmp"),
("Other and unallocable","othuna","F81","pmt"),
("Other and unallocable","othuna","F81","fmt"),
("Other and unallocable","othuna","F81","mch"),
("Other and unallocable","othuna","F81","cep"),
("Other and unallocable","othuna","F81","eec"),
("Other and unallocable","othuna","F81","mot"),
("Other and unallocable","othuna","F81","ote"),
("Other and unallocable","othuna","F81","fpd"),
("Other and unallocable","othuna","F81","mmf"),
("Other and unallocable","othuna","F81","wht"),
("Other and unallocable","othuna","F81","mvt"),
("Other and unallocable","othuna","F81","gmt"),
("Other and unallocable","othuna","F81","ott"),
("Other and unallocable","othuna","F81","osv"),
("Other and unallocable","othuna","F81","use"),
("Other and unallocable","othuna","F81","oth"),
("Other and unallocable","othuna","F85","pet"),
("Other and unallocable","othuna","F85","che"),
("Other and unallocable","othuna","F85","pla"),
("Other and unallocable","othuna","F85","nmp"),
("Other and unallocable","othuna","F85","pmt"),
("Other and unallocable","othuna","F85","fmt"),
("Other and unallocable","othuna","F85","mch"),
("Other and unallocable","othuna","F85","cep"),
("Other and unallocable","othuna","F85","eec"),
("Other and unallocable","othuna","F85","mot"),
("Other and unallocable","othuna","F85","ote"),
("Other and unallocable","othuna","F85","fpd"),
("Other and unallocable","othuna","F85","mmf"),
("Other and unallocable","othuna","F85","wht"),
("Other and unallocable","othuna","F85","mvt"),
("Other and unallocable","othuna","F85","gmt"),
("Other and unallocable","othuna","F85","ott"),
("Other and unallocable","othuna","F85","osv"),
("Other and unallocable","othuna","F85","use"),
("Other and unallocable","othuna","F85","oth"),
("Other and unallocable","othuna","F87","pet"),
("Other and unallocable","othuna","F87","che"),
("Other and unallocable","othuna","F87","pla"),
("Other and unallocable","othuna","F87","nmp"),
("Other and unallocable","othuna","F87","pmt"),
("Other and unallocable","othuna","F87","fmt"),
("Other and unallocable","othuna","F87","mch"),
("Other and unallocable","othuna","F87","cep"),
("Other and unallocable","othuna","F87","eec"),
("Other and unallocable","othuna","F87","mot"),
("Other and unallocable","othuna","F87","ote"),
("Other and unallocable","othuna","F87","fpd"),
("Other and unallocable","othuna","F87","mmf"),
("Other and unallocable","othuna","F87","wht"),
("Other and unallocable","othuna","F87","mvt"),
("Other and unallocable","othuna","F87","gmt"),
("Other and unallocable","othuna","F87","ott"),
("Other and unallocable","othuna","F87","osv"),
("Other and unallocable","othuna","F87","use"),
("Other and unallocable","othuna","F87","oth"),
("Other and unallocable","othuna","F89","pet"),
("Other and unallocable","othuna","F89","che"),
("Other and unallocable","othuna","F89","pla"),
("Other and unallocable","othuna","F89","nmp"),
("Other and unallocable","othuna","F89","pmt"),
("Other and unallocable","othuna","F89","fmt"),
("Other and unallocable","othuna","F89","mch"),
("Other and unallocable","othuna","F89","cep"),
("Other and unallocable","othuna","F89","eec"),
("Other and unallocable","othuna","F89","mot"),
("Other and unallocable","othuna","F89","ote"),
("Other and unallocable","othuna","F89","fpd"),
("Other and unallocable","othuna","F89","mmf"),
("Other and unallocable","othuna","F89","wht"),
("Other and unallocable","othuna","F89","mvt"),
("Other and unallocable","othuna","F89","gmt"),
("Other and unallocable","othuna","F89","ott"),
("Other and unallocable","othuna","F89","osv"),
("Other and unallocable","othuna","F89","use"),
("Other and unallocable","othuna","F89","oth"),
("Other and unallocable","othuna","G01","pet"),
("Other and unallocable","othuna","G01","che"),
("Other and unallocable","othuna","G01","pla"),
("Other and unallocable","othuna","G01","nmp"),
("Other and unallocable","othuna","G01","pmt"),
("Other and unallocable","othuna","G01","fmt"),
("Other and unallocable","othuna","G01","mch"),
("Other and unallocable","othuna","G01","cep"),
("Other and unallocable","othuna","G01","eec"),
("Other and unallocable","othuna","G01","mot"),
("Other and unallocable","othuna","G01","ote"),
("Other and unallocable","othuna","G01","fpd"),
("Other and unallocable","othuna","G01","mmf"),
("Other and unallocable","othuna","G01","wht"),
("Other and unallocable","othuna","G01","mvt"),
("Other and unallocable","othuna","G01","gmt"),
("Other and unallocable","othuna","G01","ott"),
("Other and unallocable","othuna","G01","osv"),
("Other and unallocable","othuna","G01","use"),
("Other and unallocable","othuna","G01","oth"),
("Other and unallocable","othuna","G03","pet"),
("Other and unallocable","othuna","G03","che"),
("Other and unallocable","othuna","G03","pla"),
("Other and unallocable","othuna","G03","nmp"),
("Other and unallocable","othuna","G03","pmt"),
("Other and unallocable","othuna","G03","fmt"),
("Other and unallocable","othuna","G03","mch"),
("Other and unallocable","othuna","G03","cep"),
("Other and unallocable","othuna","G03","eec"),
("Other and unallocable","othuna","G03","mot"),
("Other and unallocable","othuna","G03","ote"),
("Other and unallocable","othuna","G03","fpd"),
("Other and unallocable","othuna","G03","mmf"),
("Other and unallocable","othuna","G03","wht"),
("Other and unallocable","othuna","G03","mvt"),
("Other and unallocable","othuna","G03","gmt"),
("Other and unallocable","othuna","G03","ott"),
("Other and unallocable","othuna","G03","osv"),
("Other and unallocable","othuna","G03","use"),
("Other and unallocable","othuna","G03","oth"),
("Other and unallocable","othuna","G22","pet"),
("Other and unallocable","othuna","G22","che"),
("Other and unallocable","othuna","G22","pla"),
("Other and unallocable","othuna","G22","nmp"),
("Other and unallocable","othuna","G22","pmt"),
("Other and unallocable","othuna","G22","fmt"),
("Other and unallocable","othuna","G22","mch"),
("Other and unallocable","othuna","G22","cep"),
("Other and unallocable","othuna","G22","eec"),
("Other and unallocable","othuna","G22","mot"),
("Other and unallocable","othuna","G22","ote"),
("Other and unallocable","othuna","G22","fpd"),
("Other and unallocable","othuna","G22","mmf"),
("Other and unallocable","othuna","G22","wht"),
("Other and unallocable","othuna","G22","mvt"),
("Other and unallocable","othuna","G22","gmt"),
("Other and unallocable","othuna","G22","ott"),
("Other and unallocable","othuna","G22","osv"),
("Other and unallocable","othuna","G22","use"),
("Other and unallocable","othuna","G22","oth"),
("Other and unallocable","othuna","G50","pet"),
("Other and unallocable","othuna","G50","che"),
("Other and unallocable","othuna","G50","pla"),
("Other and unallocable","othuna","G50","nmp"),
("Other and unallocable","othuna","G50","pmt"),
("Other and unallocable","othuna","G50","fmt"),
("Other and unallocable","othuna","G50","mch"),
("Other and unallocable","othuna","G50","cep"),
("Other and unallocable","othuna","G50","eec"),
("Other and unallocable","othuna","G50","mot"),
("Other and unallocable","othuna","G50","ote"),
("Other and unallocable","othuna","G50","fpd"),
("Other and unallocable","othuna","G50","mmf"),
("Other and unallocable","othuna","G50","wht"),
("Other and unallocable","othuna","G50","mvt"),
("Other and unallocable","othuna","G50","gmt"),
("Other and unallocable","othuna","G50","ott"),
("Other and unallocable","othuna","G50","osv"),
("Other and unallocable","othuna","G50","use"),
("Other and unallocable","othuna","G50","oth"),
("Other and unallocable","othuna","G52","pet"),
("Other and unallocable","othuna","G52","che"),
("Other and unallocable","othuna","G52","pla"),
("Other and unallocable","othuna","G52","nmp"),
("Other and unallocable","othuna","G52","pmt"),
("Other and unallocable","othuna","G52","fmt"),
("Other and unallocable","othuna","G52","mch"),
("Other and unallocable","othuna","G52","cep"),
("Other and unallocable","othuna","G52","eec"),
("Other and unallocable","othuna","G52","mot"),
("Other and unallocable","othuna","G52","ote"),
("Other and unallocable","othuna","G52","fpd"),
("Other and unallocable","othuna","G52","mmf"),
("Other and unallocable","othuna","G52","wht"),
("Other and unallocable","othuna","G52","mvt"),
("Other and unallocable","othuna","G52","gmt"),
("Other and unallocable","othuna","G52","ott"),
("Other and unallocable","othuna","G52","osv"),
("Other and unallocable","othuna","G52","use"),
("Other and unallocable","othuna","G52","oth"),
("Other and unallocable","othuna","G60","pet"),
("Other and unallocable","othuna","G60","che"),
("Other and unallocable","othuna","G60","pla"),
("Other and unallocable","othuna","G60","nmp"),
("Other and unallocable","othuna","G60","pmt"),
("Other and unallocable","othuna","G60","fmt"),
("Other and unallocable","othuna","G60","mch"),
("Other and unallocable","othuna","G60","cep"),
("Other and unallocable","othuna","G60","eec"),
("Other and unallocable","othuna","G60","mot"),
("Other and unallocable","othuna","G60","ote"),
("Other and unallocable","othuna","G60","fpd"),
("Other and unallocable","othuna","G60","mmf"),
("Other and unallocable","othuna","G60","wht"),
("Other and unallocable","othuna","G60","mvt"),
("Other and unallocable","othuna","G60","gmt"),
("Other and unallocable","othuna","G60","ott"),
("Other and unallocable","othuna","G60","osv"),
("Other and unallocable","othuna","G60","use"),
("Other and unallocable","othuna","G60","oth"),
("Other and unallocable","othuna","G66","pet"),
("Other and unallocable","othuna","G66","che"),
("Other and unallocable","othuna","G66","pla"),
("Other and unallocable","othuna","G66","nmp"),
("Other and unallocable","othuna","G66","pmt"),
("Other and unallocable","othuna","G66","fmt"),
("Other and unallocable","othuna","G66","mch"),
("Other and unallocable","othuna","G66","cep"),
("Other and unallocable","othuna","G66","eec"),
("Other and unallocable","othuna","G66","mot"),
("Other and unallocable","othuna","G66","ote"),
("Other and unallocable","othuna","G66","fpd"),
("Other and unallocable","othuna","G66","mmf"),
("Other and unallocable","othuna","G66","wht"),
("Other and unallocable","othuna","G66","mvt"),
("Other and unallocable","othuna","G66","gmt"),
("Other and unallocable","othuna","G66","ott"),
("Other and unallocable","othuna","G66","osv"),
("Other and unallocable","othuna","G66","use"),
("Other and unallocable","othuna","G66","oth"),
("Other and unallocable","othuna","G80","pet"),
("Other and unallocable","othuna","G80","che"),
("Other and unallocable","othuna","G80","pla"),
("Other and unallocable","othuna","G80","nmp"),
("Other and unallocable","othuna","G80","pmt"),
("Other and unallocable","othuna","G80","fmt"),
("Other and unallocable","othuna","G80","mch"),
("Other and unallocable","othuna","G80","cep"),
("Other and unallocable","othuna","G80","eec"),
("Other and unallocable","othuna","G80","mot"),
("Other and unallocable","othuna","G80","ote"),
("Other and unallocable","othuna","G80","fpd"),
("Other and unallocable","othuna","G80","mmf"),
("Other and unallocable","othuna","G80","wht"),
("Other and unallocable","othuna","G80","mvt"),
("Other and unallocable","othuna","G80","gmt"),
("Other and unallocable","othuna","G80","ott"),
("Other and unallocable","othuna","G80","osv"),
("Other and unallocable","othuna","G80","use"),
("Other and unallocable","othuna","G80","oth"),
("Other and unallocable","othuna","G81","pet"),
("Other and unallocable","othuna","G81","che"),
("Other and unallocable","othuna","G81","pla"),
("Other and unallocable","othuna","G81","nmp"),
("Other and unallocable","othuna","G81","pmt"),
("Other and unallocable","othuna","G81","fmt"),
("Other and unallocable","othuna","G81","mch"),
("Other and unallocable","othuna","G81","cep"),
("Other and unallocable","othuna","G81","eec"),
("Other and unallocable","othuna","G81","mot"),
("Other and unallocable","othuna","G81","ote"),
("Other and unallocable","othuna","G81","fpd"),
("Other and unallocable","othuna","G81","mmf"),
("Other and unallocable","othuna","G81","wht"),
("Other and unallocable","othuna","G81","mvt"),
("Other and unallocable","othuna","G81","gmt"),
("Other and unallocable","othuna","G81","ott"),
("Other and unallocable","othuna","G81","osv"),
("Other and unallocable","othuna","G81","use"),
("Other and unallocable","othuna","G81","oth"),
("Other and unallocable","othuna","G85","pet"),
("Other and unallocable","othuna","G85","che"),
("Other and unallocable","othuna","G85","pla"),
("Other and unallocable","othuna","G85","nmp"),
("Other and unallocable","othuna","G85","pmt"),
("Other and unallocable","othuna","G85","fmt"),
("Other and unallocable","othuna","G85","mch"),
("Other and unallocable","othuna","G85","cep"),
("Other and unallocable","othuna","G85","eec"),
("Other and unallocable","othuna","G85","mot"),
("Other and unallocable","othuna","G85","ote"),
("Other and unallocable","othuna","G85","fpd"),
("Other and unallocable","othuna","G85","mmf"),
("Other and unallocable","othuna","G85","wht"),
("Other and unallocable","othuna","G85","mvt"),
("Other and unallocable","othuna","G85","gmt"),
("Other and unallocable","othuna","G85","ott"),
("Other and unallocable","othuna","G85","osv"),
("Other and unallocable","othuna","G85","use"),
("Other and unallocable","othuna","G85","oth"),
("Other and unallocable","othuna","G87","pet"),
("Other and unallocable","othuna","G87","che"),
("Other and unallocable","othuna","G87","pla"),
("Other and unallocable","othuna","G87","nmp"),
("Other and unallocable","othuna","G87","pmt"),
("Other and unallocable","othuna","G87","fmt"),
("Other and unallocable","othuna","G87","mch"),
("Other and unallocable","othuna","G87","cep"),
("Other and unallocable","othuna","G87","eec"),
("Other and unallocable","othuna","G87","mot"),
("Other and unallocable","othuna","G87","ote"),
("Other and unallocable","othuna","G87","fpd"),
("Other and unallocable","othuna","G87","mmf"),
("Other and unallocable","othuna","G87","wht"),
("Other and unallocable","othuna","G87","mvt"),
("Other and unallocable","othuna","G87","gmt"),
("Other and unallocable","othuna","G87","ott"),
("Other and unallocable","othuna","G87","osv"),
("Other and unallocable","othuna","G87","use"),
("Other and unallocable","othuna","G87","oth"),
("Other and unallocable","othuna","G89","pet"),
("Other and unallocable","othuna","G89","che"),
("Other and unallocable","othuna","G89","pla"),
("Other and unallocable","othuna","G89","nmp"),
("Other and unallocable","othuna","G89","pmt"),
("Other and unallocable","othuna","G89","fmt"),
("Other and unallocable","othuna","G89","mch"),
("Other and unallocable","othuna","G89","cep"),
("Other and unallocable","othuna","G89","eec"),
("Other and unallocable","othuna","G89","mot"),
("Other and unallocable","othuna","G89","ote"),
("Other and unallocable","othuna","G89","fpd"),
("Other and unallocable","othuna","G89","mmf"),
("Other and unallocable","othuna","G89","wht"),
("Other and unallocable","othuna","G89","mvt"),
("Other and unallocable","othuna","G89","gmt"),
("Other and unallocable","othuna","G89","ott"),
("Other and unallocable","othuna","G89","osv"),
("Other and unallocable","othuna","G89","use"),
("Other and unallocable","othuna","G89","oth"),
("Other and unallocable","othuna","M01","pet"),
("Other and unallocable","othuna","M01","che"),
("Other and unallocable","othuna","M01","pla"),
("Other and unallocable","othuna","M01","nmp"),
("Other and unallocable","othuna","M01","pmt"),
("Other and unallocable","othuna","M01","fmt"),
("Other and unallocable","othuna","M01","mch"),
("Other and unallocable","othuna","M01","cep"),
("Other and unallocable","othuna","M01","eec"),
("Other and unallocable","othuna","M01","mot"),
("Other and unallocable","othuna","M01","ote"),
("Other and unallocable","othuna","M01","fpd"),
("Other and unallocable","othuna","M01","mmf"),
("Other and unallocable","othuna","M01","wht"),
("Other and unallocable","othuna","M01","mvt"),
("Other and unallocable","othuna","M01","gmt"),
("Other and unallocable","othuna","M01","ott"),
("Other and unallocable","othuna","M01","osv"),
("Other and unallocable","othuna","M01","use"),
("Other and unallocable","othuna","M01","oth"),
("Other and unallocable","othuna","M50","pet"),
("Other and unallocable","othuna","M50","che"),
("Other and unallocable","othuna","M50","pla"),
("Other and unallocable","othuna","M50","nmp"),
("Other and unallocable","othuna","M50","pmt"),
("Other and unallocable","othuna","M50","fmt"),
("Other and unallocable","othuna","M50","mch"),
("Other and unallocable","othuna","M50","cep"),
("Other and unallocable","othuna","M50","eec"),
("Other and unallocable","othuna","M50","mot"),
("Other and unallocable","othuna","M50","ote"),
("Other and unallocable","othuna","M50","fpd"),
("Other and unallocable","othuna","M50","mmf"),
("Other and unallocable","othuna","M50","wht"),
("Other and unallocable","othuna","M50","mvt"),
("Other and unallocable","othuna","M50","gmt"),
("Other and unallocable","othuna","M50","ott"),
("Other and unallocable","othuna","M50","osv"),
("Other and unallocable","othuna","M50","use"),
("Other and unallocable","othuna","M50","oth"),
("Other and unallocable","othuna","M52","pet"),
("Other and unallocable","othuna","M52","che"),
("Other and unallocable","othuna","M52","pla"),
("Other and unallocable","othuna","M52","nmp"),
("Other and unallocable","othuna","M52","pmt"),
("Other and unallocable","othuna","M52","fmt"),
("Other and unallocable","othuna","M52","mch"),
("Other and unallocable","othuna","M52","cep"),
("Other and unallocable","othuna","M52","eec"),
("Other and unallocable","othuna","M52","mot"),
("Other and unallocable","othuna","M52","ote"),
("Other and unallocable","othuna","M52","fpd"),
("Other and unallocable","othuna","M52","mmf"),
("Other and unallocable","othuna","M52","wht"),
("Other and unallocable","othuna","M52","mvt"),
("Other and unallocable","othuna","M52","gmt"),
("Other and unallocable","othuna","M52","ott"),
("Other and unallocable","othuna","M52","osv"),
("Other and unallocable","othuna","M52","use"),
("Other and unallocable","othuna","M52","oth"),
("Other and unallocable","othuna","M60","pet"),
("Other and unallocable","othuna","M60","che"),
("Other and unallocable","othuna","M60","pla"),
("Other and unallocable","othuna","M60","nmp"),
("Other and unallocable","othuna","M60","pmt"),
("Other and unallocable","othuna","M60","fmt"),
("Other and unallocable","othuna","M60","mch"),
("Other and unallocable","othuna","M60","cep"),
("Other and unallocable","othuna","M60","eec"),
("Other and unallocable","othuna","M60","mot"),
("Other and unallocable","othuna","M60","ote"),
("Other and unallocable","othuna","M60","fpd"),
("Other and unallocable","othuna","M60","mmf"),
("Other and unallocable","othuna","M60","wht"),
("Other and unallocable","othuna","M60","mvt"),
("Other and unallocable","othuna","M60","gmt"),
("Other and unallocable","othuna","M60","ott"),
("Other and unallocable","othuna","M60","osv"),
("Other and unallocable","othuna","M60","use"),
("Other and unallocable","othuna","M60","oth"),
("Other and unallocable","othuna","M66","pet"),
("Other and unallocable","othuna","M66","che"),
("Other and unallocable","othuna","M66","pla"),
("Other and unallocable","othuna","M66","nmp"),
("Other and unallocable","othuna","M66","pmt"),
("Other and unallocable","othuna","M66","fmt"),
("Other and unallocable","othuna","M66","mch"),
("Other and unallocable","othuna","M66","cep"),
("Other and unallocable","othuna","M66","eec"),
("Other and unallocable","othuna","M66","mot"),
("Other and unallocable","othuna","M66","ote"),
("Other and unallocable","othuna","M66","fpd"),
("Other and unallocable","othuna","M66","mmf"),
("Other and unallocable","othuna","M66","wht"),
("Other and unallocable","othuna","M66","mvt"),
("Other and unallocable","othuna","M66","gmt"),
("Other and unallocable","othuna","M66","ott"),
("Other and unallocable","othuna","M66","osv"),
("Other and unallocable","othuna","M66","use"),
("Other and unallocable","othuna","M66","oth"),
("Other and unallocable","othuna","M80","pet"),
("Other and unallocable","othuna","M80","che"),
("Other and unallocable","othuna","M80","pla"),
("Other and unallocable","othuna","M80","nmp"),
("Other and unallocable","othuna","M80","pmt"),
("Other and unallocable","othuna","M80","fmt"),
("Other and unallocable","othuna","M80","mch"),
("Other and unallocable","othuna","M80","cep"),
("Other and unallocable","othuna","M80","eec"),
("Other and unallocable","othuna","M80","mot"),
("Other and unallocable","othuna","M80","ote"),
("Other and unallocable","othuna","M80","fpd"),
("Other and unallocable","othuna","M80","mmf"),
("Other and unallocable","othuna","M80","wht"),
("Other and unallocable","othuna","M80","mvt"),
("Other and unallocable","othuna","M80","gmt"),
("Other and unallocable","othuna","M80","ott"),
("Other and unallocable","othuna","M80","osv"),
("Other and unallocable","othuna","M80","use"),
("Other and unallocable","othuna","M80","oth"),
("Other and unallocable","othuna","M81","pet"),
("Other and unallocable","othuna","M81","che"),
("Other and unallocable","othuna","M81","pla"),
("Other and unallocable","othuna","M81","nmp"),
("Other and unallocable","othuna","M81","pmt"),
("Other and unallocable","othuna","M81","fmt"),
("Other and unallocable","othuna","M81","mch"),
("Other and unallocable","othuna","M81","cep"),
("Other and unallocable","othuna","M81","eec"),
("Other and unallocable","othuna","M81","mot"),
("Other and unallocable","othuna","M81","ote"),
("Other and unallocable","othuna","M81","fpd"),
("Other and unallocable","othuna","M81","mmf"),
("Other and unallocable","othuna","M81","wht"),
("Other and unallocable","othuna","M81","mvt"),
("Other and unallocable","othuna","M81","gmt"),
("Other and unallocable","othuna","M81","ott"),
("Other and unallocable","othuna","M81","osv"),
("Other and unallocable","othuna","M81","use"),
("Other and unallocable","othuna","M81","oth"),
("Other and unallocable","othuna","M87","pet"),
("Other and unallocable","othuna","M87","che"),
("Other and unallocable","othuna","M87","pla"),
("Other and unallocable","othuna","M87","nmp"),
("Other and unallocable","othuna","M87","pmt"),
("Other and unallocable","othuna","M87","fmt"),
("Other and unallocable","othuna","M87","mch"),
("Other and unallocable","othuna","M87","cep"),
("Other and unallocable","othuna","M87","eec"),
("Other and unallocable","othuna","M87","mot"),
("Other and unallocable","othuna","M87","ote"),
("Other and unallocable","othuna","M87","fpd"),
("Other and unallocable","othuna","M87","mmf"),
("Other and unallocable","othuna","M87","wht"),
("Other and unallocable","othuna","M87","mvt"),
("Other and unallocable","othuna","M87","gmt"),
("Other and unallocable","othuna","M87","ott"),
("Other and unallocable","othuna","M87","osv"),
("Other and unallocable","othuna","M87","use"),
("Other and unallocable","othuna","M87","oth"),
("Other and unallocable","othuna","M89","pet"),
("Other and unallocable","othuna","M89","che"),
("Other and unallocable","othuna","M89","pla"),
("Other and unallocable","othuna","M89","nmp"),
("Other and unallocable","othuna","M89","pmt"),
("Other and unallocable","othuna","M89","fmt"),
("Other and unallocable","othuna","M89","mch"),
("Other and unallocable","othuna","M89","cep"),
("Other and unallocable","othuna","M89","eec"),
("Other and unallocable","othuna","M89","mot"),
("Other and unallocable","othuna","M89","ote"),
("Other and unallocable","othuna","M89","fpd"),
("Other and unallocable","othuna","M89","mmf"),
("Other and unallocable","othuna","M89","wht"),
("Other and unallocable","othuna","M89","mvt"),
("Other and unallocable","othuna","M89","gmt"),
("Other and unallocable","othuna","M89","ott"),
("Other and unallocable","othuna","M89","osv"),
("Other and unallocable","othuna","M89","use"),
("Other and unallocable","othuna","M89","oth"),
("Other and unallocable","othuna","S89","pet"),
("Other and unallocable","othuna","S89","che"),
("Other and unallocable","othuna","S89","pla"),
("Other and unallocable","othuna","S89","nmp"),
("Other and unallocable","othuna","S89","pmt"),
("Other and unallocable","othuna","S89","fmt"),
("Other and unallocable","othuna","S89","mch"),
("Other and unallocable","othuna","S89","cep"),
("Other and unallocable","othuna","S89","eec"),
("Other and unallocable","othuna","S89","mot"),
("Other and unallocable","othuna","S89","ote"),
("Other and unallocable","othuna","S89","fpd"),
("Other and unallocable","othuna","S89","mmf"),
("Other and unallocable","othuna","S89","wht"),
("Other and unallocable","othuna","S89","mvt"),
("Other and unallocable","othuna","S89","gmt"),
("Other and unallocable","othuna","S89","ott"),
("Other and unallocable","othuna","S89","osv"),
("Other and unallocable","othuna","S89","use"),
("Other and unallocable","othuna","S89","oth"),
("Utility expenditure","utlexp","E91","uti"),
("Utility expenditure","utlexp","E91","fdd"),
("Utility expenditure","utlexp","E91","fnd"),
("Utility expenditure","utlexp","E91","fen"),
("Utility expenditure","utlexp","E91","slg"),
("Utility expenditure","utlexp","E91","sle"),
("Utility expenditure","utlexp","E92","uti"),
("Utility expenditure","utlexp","E92","fdd"),
("Utility expenditure","utlexp","E92","fnd"),
("Utility expenditure","utlexp","E92","fen"),
("Utility expenditure","utlexp","E92","slg"),
("Utility expenditure","utlexp","E92","sle"),
("Utility expenditure","utlexp","E93","uti"),
("Utility expenditure","utlexp","E93","fdd"),
("Utility expenditure","utlexp","E93","fnd"),
("Utility expenditure","utlexp","E93","fen"),
("Utility expenditure","utlexp","E93","slg"),
("Utility expenditure","utlexp","E93","sle"),
("Utility expenditure","utlexp","E94","uti"),
("Utility expenditure","utlexp","E94","fdd"),
("Utility expenditure","utlexp","E94","fnd"),
("Utility expenditure","utlexp","E94","fen"),
("Utility expenditure","utlexp","E94","slg"),
("Utility expenditure","utlexp","E94","sle"),
("Utility expenditure","utlexp","F91","uti"),
("Utility expenditure","utlexp","F91","fdd"),
("Utility expenditure","utlexp","F91","fnd"),
("Utility expenditure","utlexp","F91","fen"),
("Utility expenditure","utlexp","F91","slg"),
("Utility expenditure","utlexp","F91","sle"),
("Utility expenditure","utlexp","F92","uti"),
("Utility expenditure","utlexp","F92","fdd"),
("Utility expenditure","utlexp","F92","fnd"),
("Utility expenditure","utlexp","F92","fen"),
("Utility expenditure","utlexp","F92","slg"),
("Utility expenditure","utlexp","F92","sle"),
("Utility expenditure","utlexp","F93","uti"),
("Utility expenditure","utlexp","F93","fdd"),
("Utility expenditure","utlexp","F93","fnd"),
("Utility expenditure","utlexp","F93","fen"),
("Utility expenditure","utlexp","F93","slg"),
("Utility expenditure","utlexp","F93","sle"),
("Utility expenditure","utlexp","F94","uti"),
("Utility expenditure","utlexp","F94","fdd"),
("Utility expenditure","utlexp","F94","fnd"),
("Utility expenditure","utlexp","F94","fen"),
("Utility expenditure","utlexp","F94","slg"),
("Utility expenditure","utlexp","F94","sle"),
("Utility expenditure","utlexp","G91","uti"),
("Utility expenditure","utlexp","G91","fdd"),
("Utility expenditure","utlexp","G91","fnd"),
("Utility expenditure","utlexp","G91","fen"),
("Utility expenditure","utlexp","G91","slg"),
("Utility expenditure","utlexp","G91","sle"),
("Utility expenditure","utlexp","G92","uti"),
("Utility expenditure","utlexp","G92","fdd"),
("Utility expenditure","utlexp","G92","fnd"),
("Utility expenditure","utlexp","G92","fen"),
("Utility expenditure","utlexp","G92","slg"),
("Utility expenditure","utlexp","G92","sle"),
("Utility expenditure","utlexp","G93","uti"),
("Utility expenditure","utlexp","G93","fdd"),
("Utility expenditure","utlexp","G93","fnd"),
("Utility expenditure","utlexp","G93","fen"),
("Utility expenditure","utlexp","G93","slg"),
("Utility expenditure","utlexp","G93","sle"),
("Utility expenditure","utlexp","G94","uti"),
("Utility expenditure","utlexp","G94","fdd"),
("Utility expenditure","utlexp","G94","fnd"),
("Utility expenditure","utlexp","G94","fen"),
("Utility expenditure","utlexp","G94","slg"),
("Utility expenditure","utlexp","G94","sle"),
("Utility expenditure","utlexp","I91","uti"),
("Utility expenditure","utlexp","I91","fdd"),
("Utility expenditure","utlexp","I91","fnd"),
("Utility expenditure","utlexp","I91","fen"),
("Utility expenditure","utlexp","I91","slg"),
("Utility expenditure","utlexp","I91","sle"),
("Utility expenditure","utlexp","I92","uti"),
("Utility expenditure","utlexp","I92","fdd"),
("Utility expenditure","utlexp","I92","fnd"),
("Utility expenditure","utlexp","I92","fen"),
("Utility expenditure","utlexp","I92","slg"),
("Utility expenditure","utlexp","I92","sle"),
("Utility expenditure","utlexp","I93","uti"),
("Utility expenditure","utlexp","I93","fdd"),
("Utility expenditure","utlexp","I93","fnd"),
("Utility expenditure","utlexp","I93","fen"),
("Utility expenditure","utlexp","I93","slg"),
("Utility expenditure","utlexp","I93","sle"),
("Utility expenditure","utlexp","I94","uti"),
("Utility expenditure","utlexp","I94","fdd"),
("Utility expenditure","utlexp","I94","fnd"),
("Utility expenditure","utlexp","I94","fen"),
("Utility expenditure","utlexp","I94","slg"),
("Utility expenditure","utlexp","I94","sle"),
("Utility expenditure","utlexp","M91","uti"),
("Utility expenditure","utlexp","M91","fdd"),
("Utility expenditure","utlexp","M91","fnd"),
("Utility expenditure","utlexp","M91","fen"),
("Utility expenditure","utlexp","M91","slg"),
("Utility expenditure","utlexp","M91","sle"),
("Utility expenditure","utlexp","M92","uti"),
("Utility expenditure","utlexp","M92","fdd"),
("Utility expenditure","utlexp","M92","fnd"),
("Utility expenditure","utlexp","M92","fen"),
("Utility expenditure","utlexp","M92","slg"),
("Utility expenditure","utlexp","M92","sle"),
("Utility expenditure","utlexp","M93","uti"),
("Utility expenditure","utlexp","M93","fdd"),
("Utility expenditure","utlexp","M93","fnd"),
("Utility expenditure","utlexp","M93","fen"),
("Utility expenditure","utlexp","M93","slg"),
("Utility expenditure","utlexp","M93","sle"),
("Utility expenditure","utlexp","M94","uti"),
("Utility expenditure","utlexp","M94","fdd"),
("Utility expenditure","utlexp","M94","fnd"),
("Utility expenditure","utlexp","M94","fen"),
("Utility expenditure","utlexp","M94","slg"),
("Utility expenditure","utlexp","M94","sle"),
("Liquor stores expenditure","liqexp","E90","fbp"),
("Liquor stores expenditure","liqexp","E90","fbt"),
("Liquor stores expenditure","liqexp","E90","res"),
("Liquor stores expenditure","liqexp","F90","fbp"),
("Liquor stores expenditure","liqexp","F90","fbt"),
("Liquor stores expenditure","liqexp","F90","res"),
("Liquor stores expenditure","liqexp","G90","fbp"),
("Liquor stores expenditure","liqexp","G90","fbt"),
("Liquor stores expenditure","liqexp","G90","res"),
],[:sgf_category,:sgf_cat,:item_code,:i])
push!(notations, notation_link(:item_code,sgf_codes,:item_code,:i,:i))
return notations
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 15307 |
function state_dissagregation(GU::GamsUniverse)
#Construct new universe
G = GamsUniverse()
sets_to_transfer = Dict(
:yr => :yr,
:m => :m,
:i => :s,
:r => :r
)
#yr,r,s,m,gm,
for (s,new_name) in sets_to_transfer
elements = [e for e in GU[s].elements if e.active]
add_set(G,new_name,GamsSet(elements,GU[s].description))
end
alias(G,:s,:g)
@parameters(G,begin
#Production Data
ys0_, (:yr, :r, :s, :g), (description = "Regional sectoral output",)
ld0_, (:yr, :r, :s), (description = "Labor demand",)
kd0_, (:yr, :r, :s), (description = "Capital demand",)
id0_, (:yr, :r, :g, :s), (description = "Regional intermediate demand",)
ty0_, (:yr, :r, :s), (description = "Production tax rate",)
#Consumption Data
yh0_, (:yr, :r, :s), (description = "Household production",)
fe0_, (:yr, :r), (description = "Total factor supply",)
cd0_, (:yr, :r, :s), (description = "Consumption demand",)
c0_, (:yr, :r), (description = "Total final household consumption",)
i0_, (:yr, :r, :s), (description = "Investment demand",)
g0_, (:yr, :r, :s), (description = "Government demand",)
bopdef0_, (:yr, :r), (description = "Balance of payments (closure parameter)",)
hhadj0_, (:yr, :r), (description = "Household adjustment parameter",)
#Trade Data
s0_, (:yr, :r, :g), (description = "Total supply",)
xd0_, (:yr, :r, :g), (description = "Regional supply to local market",)
xn0_, (:yr, :r, :g), (description = "Regional supply to national market",)
x0_, (:yr, :r, :g), (description = "Foreign Exports",)
rx0_, (:yr, :r, :g), (description = "Re-exports",)
a0_, (:yr, :r, :g), (description = "Domestic absorption",)
nd0_, (:yr, :r, :g), (description = "Regional demand from national market",)
dd0_, (:yr, :r, :g), (description = "Regional demand from local market",)
m0_, (:yr, :r, :g), (description = "Foreign Imports",)
ta0_, (:yr, :r, :g), (description = "Absorption taxes",)
tm0_, (:yr, :r, :g), (description = "Import taxes",)
#Margins
md0_, (:yr, :r, :m, :g), (description = "Margin demand",)
dm0_, (:yr, :r, :g, :m), (description = "Margin supply from the local market",)
nm0_, (:yr, :r, :g, :m), (description = "Margin demand from the national market",)
#GDP
gdp0_, (:yr, :r), (description = "Aggregate GDP",)
end);
#Regionalize production data using iomacro shares and GSP data:
va0_ = GamsStructure.Parameter(G,(:yr,:r,:s);description = "Value Added")
for r∈G[:r],s∈G[:s],g∈G[:g]
G[:ys0_][:yr,[r],[s],[g]] = GU[:region_shr][:yr,[r],[s]] .* GU[:ys0][:yr,[s],[g]]
G[:id0_][:yr,[r],[g],[s]] = GU[:region_shr][:yr,[r],[s]] .* GU[:id0][:yr,[g],[s]]
end
for r∈G[:r]
va0_[:yr,[r],:s] = GU[:region_shr][:yr,[r],:i] .* (GU[:va0][:yr,[:compen],:i] .+ GU[:va0][:yr,[:surplus],:i])
G[:ty0_][:yr,[r],:s] = GU[:ty0][:yr,:i];
G[:ld0_][:yr,[r],:s] = GU[:labor_shr][:yr,[r],:i] .* va0_[:yr,[r],:s]
G[:kd0_][:yr,[r],:s] = va0_[:yr,[r],:s] - G[:ld0_][:yr,[r],:s];
end
#sum(abs.(sum(G[:ys0_][:yr,:r,:s,[g]] for g∈G[:g]) .* (1 .- G[:ty0_][:yr,:r,:s]) .- (G[:ld0_][:yr,:r,:s] + G[:kd0_][:yr,:r,:s] + sum(G[:id0_][:yr,:r,[g],:s] for g∈G[:g]))))
# Aggregate final demand categories:
g_cat = [:defense,:def_structures,:def_equipment,:def_intelprop,:nondefense,:fed_structures,:fed_equipment,:fed_intelprop,:state_consume,:state_invest,:state_equipment,:state_intelprop]
i_cat = [:structures,:equipment,:intelprop,:residential,:changinv]
for r∈G[:r]
G[:yh0_][:yr,[r],:s] = GU[:fs0][:yr,:i] .* GU[:region_shr][:yr,[r],:i]
G[:fe0_][:yr,[r]] = sum(va0_[:yr,[r],[s]] for s∈G[:s])
#* Use PCE and government demand data rather than region_shr:
G[:cd0_][:yr,[r],:g] = GU[:pce_shr][:yr,[r],:j] .* sum(GU[:fd0][:yr,:j,[:pce]],dims=3);
G[:g0_][:yr,[r],:g] = GU[:sgf_shr][:yr,[r],:j] .* sum(GU[:fd0][:yr,:j,[fd]] for fd∈g_cat)
G[:i0_][:yr,[r],:g] = GU[:region_shr][:yr,[r],:j] .* sum(GU[:fd0][:yr,:j,[fd]] for fd∈i_cat)
G[:c0_][:yr,[r]] = sum(G[:cd0_][:yr,[r],[g]] for g∈G[:g])
end
# Use export shares from USA Trade Online for included sectors. For those
# not included, use gross state product shares:
for yr∈G[:yr],g∈G[:g]
if sum(GU[:usatrd_shr][[yr],:r,[g],[:exports]]) != 0
G[:x0_][[yr],:r,[g]] = GU[:usatrd_shr][[yr],:r,[g],[:exports]] .* GU[:x0][[yr],[g]]
else
G[:x0_][[yr],:r,[g]] = GU[:region_shr][[yr],:r,[g]] * GU[:x0][[yr],[g]]
end
end
# No longer subtracting margin supply from gross output. This will be allocated
# through the national and local markets.
for r∈G[:r]
G[:s0_][:yr,[r],:g] = sum(G[:ys0_][:yr,[r],[s],:g] for s∈G[:s]) + G[:yh0_][:yr,[r],:g]
G[:a0_][:yr,[r],:g] = G[:cd0_][:yr,[r],:g] + G[:g0_][:yr,[r],:g] + G[:i0_][:yr,[r],:g] + sum(G[:id0_][:yr,[r],:g,[s]] for s∈G[:s]);
G[:tm0_][:yr,[r],:g] = GU[:tm0][:yr,:i]
G[:ta0_][:yr,[r],:g] = GU[:ta0][:yr,:i]
end
thetaa = GamsStructure.Parameter(G,(:yr,:r,:g);description = "Share of regional absorption")
for yr∈G[:yr],g∈G[:g]
if sum((1 .- G[:ta0_][[yr],[r],[g]]) .* G[:a0_][[yr],[r],[g]] for r∈G[:r]) !=0
thetaa[[yr],:r,[g]] = G[:a0_][[yr],:r,[g]] ./ sum(G[:a0_][[yr],[r],[g]] for r∈G[:r])
end
end
for r∈G[:r]
G[:m0_][:yr,[r],:g] = thetaa[:yr,[r],:g] .* GU[:m0][:yr,:i]
end
for r∈G[:r],m∈G[:m]
G[:md0_][:yr,[r],[m],:g] = thetaa[:yr,[r],:g] .* GU[:md0][:yr,[m],:i];
end
# Note that s0_ - x0_ is negative for the other category. md0 is zero for that
# category and: a + x = s + m. This means that some part of the other goods
# imports are directly re-exported. Note, re-exports are defined as the maximum
# between s0_-x0_ and the zero profit condition for the Armington
# composite. This is due to balancing issues when defining domestic and national
# demands. Particularly in the other goods sector which is a composite of the
# "fudge" factor in the national IO accounts.
#return G
mask = Mask(G,(:yr,:r,:g))
mask[:yr,:r,:g] = (G[:s0_][:yr,:r,:g] .- G[:x0_][:yr,:r,:g] .< 0)
G[:rx0_][mask] = G[:x0_][mask] .- G[:s0_][mask];
# Initial level of rx0_ makes the armington supply zero profit condition
# negative meaning it is too small (imports + margins > supply +
# re-exports). Adjust rx0_ upward for these enough to make these conditions
# zeroed out. Then subsequently adjust parameters through the circular economy.
diff = GamsStructure.Parameter(G,(:yr,:r,:g);description = "Negative numbers still exist due to sharing parameter")
diff[:yr,:r,:g] = X = - min.(0,(1 .- G[:ta0_][:yr,:r,:g]).*G[:a0_][:yr,:r,:g] .+ G[:rx0_][:yr,:r,:g] .- ((1 .+G[:tm0_][:yr,:r,:g]).*G[:m0_][:yr,:r,:g] .+ sum(G[:md0_][:yr,:r,[m],:g] for m∈G[:m])))
G[:rx0_][:yr,:r,:g] = G[:rx0_][:yr,:r,:g] + diff[:yr,:r,:g]
G[:x0_][:yr,:r,:g] = G[:x0_][:yr,:r,:g] + diff[:yr,:r,:g]
G[:s0_][:yr,:r,:g] = G[:s0_][:yr,:r,:g] + diff[:yr,:r,:g]
G[:yh0_][:yr,:r,:g] = G[:yh0_][:yr,:r,:g] + diff[:yr,:r,:g]
G[:bopdef0_][:yr,:r] = sum(G[:m0_][:yr,:r,[g]] - G[:x0_][:yr,:r,[g]] for g∈G[:g]);
s = [G[:g][e] for e∈G[:g] if (.!isapprox.(sum(GU[:ms0][[yr],[e],[m]] for yr∈G[:yr],m∈G[:m]),0,atol=1e-6)) .|| (.!isapprox.(sum(GU[:md0][[yr],[m],[e]] for yr∈GU[:yr],m∈GU[:m]),0,atol=1e-6))]
add_set(G,:gm,GamsSet(s,"Commodities employed in margin supply"));
dd0max = GamsStructure.Parameter(G,(:yr,:r,:g);description = "Maximum regional demand from local market")
dd0max[:yr,:r,:g] = min.((1 .- G[:ta0_][:yr,:r,:g]).*G[:a0_][:yr,:r,:g] .+ G[:rx0_][:yr,:r,:g] .-
((1 .+ G[:tm0_][:yr,:r,:g]).*G[:m0_][:yr,:r,:g] + sum(G[:md0_][:yr,:r,[m],:g] for m∈G[:m])),
G[:s0_][:yr,:r,:g] - (G[:x0_][:yr,:r,:g] - G[:rx0_][:yr,:r,:g]));
rpc = GamsStructure.Parameter(G,(:yr,:r,:g);description = "Regional purchase coefficients")
rpc[:yr,:r,:g] = GU[:rpc][:yr,:r,:i]
G[:dd0_][:yr,:r,:g] = rpc[:yr,:r,:g] .* dd0max[:yr,:r,:g]
G[:nd0_][:yr,:r,:g] = (1 .- G[:ta0_][:yr,:r,:g]).*G[:a0_][:yr,:r,:g] + G[:rx0_][:yr,:r,:g] -
(G[:dd0_][:yr,:r,:g] + G[:m0_][:yr,:r,:g].*(1 .+ G[:tm0_][:yr,:r,:g])
+ sum(G[:md0_][:yr,:r,[m],:g] for m∈G[:m]));
# Assume margins come both from local and national production. Assign like
# dd0. Use information on national margin supply to enforce other identities.
totmargsupply = GamsStructure.Parameter(G,(:yr,:r,:m,:g);description = "Designate total supply of margins")
margshr = GamsStructure.Parameter(G, (:yr,:r,:m);description = "Share of margin demand by region")
shrtrd = GamsStructure.Parameter(G, (:yr,:r,:m,:g);description = "Share of margin total by margin type")
#$sum((g,rr), md0_(yr,rr,m,g))
margshr[:yr,:r,:m] = permutedims(permutedims(sum(G[:md0_][:yr,:r,:m,[g]] for g∈G[:g]),(1,3,2)) ./ sum( G[:md0_][:yr,[r],:m,[g]] for r∈G[:r],g∈G[:g]),(1,3,2))
for m∈G[:m],g∈G[:g]
totmargsupply[:yr,:r,[m],[g]] = margshr[:yr,:r,[m]] .* GU[:ms0][:yr,[g],[m]]
end
for yr∈G[:yr],r∈G[:r],gm∈G[:gm]
t = sum(totmargsupply[[yr],[r],[m],[gm]] for m∈G[:m])
if t!=0
#shrtrd[:yr,:r,:m,:gm] = permutedims(permutedims(totmargsupply[:yr,:r,:m,:gm],(1,2,4,3)) ./ sum(totmargsupply[:yr,:r,[m],:gm] for m∈G[:m]),(1,2,4,3));
shrtrd[[yr],[r],:m,[gm]] = totmargsupply[[yr],[r],:m,[gm]] ./ sum(totmargsupply[[yr],[r],[m],[gm]] for m∈G[:m]);
end
end
for m∈G[:m]
G[:dm0_][:yr,:r,:gm,[m]] = min.( rpc[:yr,:r,:gm].*totmargsupply[:yr,:r,[m],:gm],
shrtrd[:yr,:r,[m],:gm].*(G[:s0_][:yr,:r,:gm] - G[:x0_][:yr,:r,:gm] + G[:rx0_][:yr,:r,:gm] - G[:dd0_][:yr,:r,:gm]));
end
G[:nm0_][:yr,:r,:gm,:m] = permutedims(totmargsupply[:yr,:r,:m,:gm],(1,2,4,3)) - G[:dm0_][:yr,:r,:gm,:m];
G[:xd0_][:yr,:r,:g] = sum(G[:dm0_][:yr,:r,:g,[m]] for m∈G[:m]) + G[:dd0_][:yr,:r,:g]
G[:xn0_][:yr,:r,:g] = G[:s0_][:yr,:r,:g] + G[:rx0_][:yr,:r,:g] - G[:xd0_][:yr,:r,:g] - G[:x0_][:yr,:r,:g]
# Remove small numbers
for (name,parm) in parameters(G)
d = domain(parm)
mask = Mask(G, d)
mask[d...] = isapprox.(parm[d...],0,atol=1e-8)
parm[mask] = 0
end
#Set Household adjustments
ibal_inc = GamsStructure.Parameter(G,(:yr,:r))
ibal_inc[:yr,:r] = sum(va0_[:yr,:r,[s]] for s∈G[:s]) + #E_RA_PL + E_RA_PK
sum(G[:yh0_][:yr,:r,[s]] for s∈G[:s]) + #E_RA_PY
G[:bopdef0_][:yr,:r] - # + hhadj[[r]] # E_RA_PFX
sum(G[:g0_][:yr,:r,[s]] + G[:i0_][:yr,:r,[s]] for s∈G[:s]) #E_RA_PA
ibal_taxrev = GamsStructure.Parameter(G,(:yr,:r))
ibal_taxrev[:yr,:r] = sum(
G[:ta0_][:yr,:r,[s]] .* G[:a0_][:yr,:r,[s]] + G[:tm0_][:yr,:r,[s]].*G[:m0_][:yr,:r,[s]] + #R_A_RA
G[:ty0_][:yr,:r,[s]] .* sum(G[:ys0_][:yr,:r,[s],[g]] for g∈G[:g]) #R_Y_RA
for s∈G[:s])
ibal_balance = GamsStructure.Parameter(G,(:yr,:r))
ibal_balance[:yr,:r] = G[:c0_][:yr,:r] .- ibal_inc[:yr,:r] .- ibal_taxrev[:yr,:r]
G[:hhadj0_][:yr,:r] = ibal_balance[:yr,:r]
G[:gdp0_][:yr,:r] = G[:c0_][:yr,:r] + sum(G[:i0_][:yr,:r,:g] + G[:g0_][:yr,:r,:g],dims=3) - G[:hhadj0_][:yr,:r] - G[:bopdef0_][:yr,:r];
Y,A,X,M = _state_zero_profit(G)
@assert isapprox(Y,0,atol=1e-4) "State Level Zero Profit fails. Check Y -> $Y."
@assert isapprox(A,0,atol=1e-4) "State Level Zero Profit fails. Check A -> $A."
@assert isapprox(X,0,atol=1e-4) "State Level Zero Profit fails. Check X -> $X."
@assert isapprox(M,0,atol=1e-4) "State Level Zero Profit fails. Check M -> $M."
I = _state_income_balance(G,va0_)
@assert isapprox(I,0,atol=1e-4) "State Level Income Balance fails. Check I -> $I."
PA,PN,PY,PFX = _state_market_clearance(G)
@assert isapprox(PA,0,atol=1e-4) "State Level Market Clearance fails. Check PA -> $PA."
@assert isapprox(PN,0,atol=1e-4) "State Level Market Clearance fails. Check PN -> $PN."
@assert isapprox(PY,0,atol=1e-4) "State Level Market Clearance fails. Check PY -> $PY."
@assert isapprox(PFX,0,atol=1e-4) "State Level Market Clearance fails. Check PFX -> $PFX."
return G
end
function _state_zero_profit(G::GamsUniverse)
Y = sum(abs.(1 .- G[:ty0_][:yr,:r,:s]) .* sum(G[:ys0_][:yr,:r,:s,[g]] for g∈G[:g]) - sum(G[:id0_][:yr,:r,[g],:s] for g∈G[:g]) - G[:ld0_][:yr,:r,:s] - G[:kd0_][:yr,:r,:s])
A = sum(abs.((1 .- G[:ta0_][:yr,:r,:g]).*G[:a0_][:yr,:r,:g] + G[:rx0_][:yr,:r,:g] -
(G[:nd0_][:yr,:r,:g] + G[:dd0_][:yr,:r,:g] + (1 .+ G[:tm0_][:yr,:r,:g]).*G[:m0_][:yr,:r,:g] + sum(G[:md0_][:yr,:r,[m],:g] for m∈G[:m]))))
X = sum(abs.(G[:s0_][:yr,:r,:g] - G[:xd0_][:yr,:r,:g] - G[:xn0_][:yr,:r,:g] - G[:x0_][:yr,:r,:g] + G[:rx0_][:yr,:r,:g]))
M = sum(abs.(sum(G[:nm0_][:yr,:r,[s],:m] + G[:dm0_][:yr,:r,[s],:m] for s∈G[:s]) - sum(G[:md0_][:yr,:r,:m,[g]] for g∈G[:g])))
return (Y,A,X,M)
end
function _state_income_balance(G::GamsUniverse,va0_::GamsStructure.Parameter)
ibal_inc = GamsStructure.Parameter(G,(:yr,:r))
ibal_inc[:yr,:r] = sum(va0_[:yr,:r,[s]] for s∈G[:s]) + #E_RA_PL + E_RA_PK
sum(G[:yh0_][:yr,:r,[s]] for s∈G[:s]) + #E_RA_PY
G[:bopdef0_][:yr,:r] - # + hhadj[[r]] # E_RA_PFX
sum(G[:g0_][:yr,:r,[s]] + G[:i0_][:yr,:r,[s]] for s∈G[:s]) + #E_RA_PA
G[:hhadj0_][:yr,:r]
# Tax revenues are expressed as values per unit activity, so we
# need multiply these by the activity level to compute total income:
ibal_taxrev = GamsStructure.Parameter(G,(:yr,:r))
ibal_taxrev[:yr,:r] = sum(
G[:ta0_][:yr,:r,[s]] .* G[:a0_][:yr,:r,[s]] + G[:tm0_][:yr,:r,[s]].*G[:m0_][:yr,:r,[s]] + #R_A_RA
G[:ty0_][:yr,:r,[s]] .* sum(G[:ys0_][:yr,:r,[s],[g]] for g∈G[:g]) #R_Y_RA
for s∈G[:s])
ibal_balance = GamsStructure.Parameter(G,(:yr,:r))
ibal_balance[:yr,:r] = G[:c0_][:yr,:r] - ibal_inc[:yr,:r] - ibal_taxrev[:yr,:r]
return sum(abs.(ibal_balance[:yr,:r]))
end
function _state_market_clearance(G::GamsUniverse)
PA = sum(abs.(G[:a0_][:yr,:r,:g] - (sum(G[:id0_][:yr,:r,:g,[s]] for s∈G[:s]) + G[:cd0_][:yr,:r,:g] + G[:g0_][:yr,:r,:g] + G[:i0_][:yr,:r,:g])))
PN = sum(abs.(sum(G[:xn0_][:yr,[r],:g] for r∈G[:r]) - sum(G[:nm0_][:yr,[r],:g,[m]] for r∈G[:r],m∈G[:m]) - sum(G[:nd0_][:yr,[r],:g] for r∈G[:r])))
PY = sum(abs.(sum(G[:ys0_][:yr,:r,[s],:g] for s∈G[:s]) + G[:yh0_][:yr,:r,:g] - G[:s0_][:yr,:r,:g]))
PFX = sum(abs.(sum(sum(G[:x0_][:yr,[r],[s]] for s∈G[:s]) + G[:hhadj0_][:yr,[r]] + G[:bopdef0_][:yr,[r]] - sum(G[:m0_][:yr,[r],[s]] for s∈G[:s]) for r∈G[:r])))
return (PA,PN,PY,PFX)
end
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 1813 |
"""
get_bea_io_years(api_key::String)
Return a string containing all available years of BEA Input/Output data.
"""
function get_bea_io_years(api_key::String)
url = "https://apps.bea.gov/api/data/?&UserID=$(api_key)&method=GetParameterValues&DataSetName=InputOutput&ParameterName=Year&ResultFormat=json"
response = HTTP.post(url)#, headers, JSON.json(req))
response_text = String(response.body)
data = JSON.parse(response_text)
years = [elm["Key"] for elm in data["BEAAPI"]["Results"]["ParamValue"]]
years = join(years,",")
end
function parse_missing(val::Number)
return val
end
function parse_missing(val::String)
try
return parse(Float64,val)
catch
return missing
end
end
"""
get_bea_io_table(api_key::String, code::Int)
Return a dataframe containing the BEA table correspoding to the code.
code - use table = 259, supply_table = 262
"""
function get_bea_io_table(api_key::String, table::Symbol)
table ∈ [:supply,:use] || error("table must be either :supply or :use. Given $table.")
code = table == :use ? 259 : 262
years = get_bea_io_years(api_key)
url = "https://apps.bea.gov/api/data/?&UserID=$(api_key)&method=GetData&DataSetName=InputOutput&Year=$years&tableID=$code&ResultFormat=json"
response = HTTP.post(url)
response_text = String(response.body)
json_obj = JSON.parse(response_text)
for elm in json_obj["BEAAPI"]["Results"][1]["Data"]
if "DataValue" ∉ keys(elm)
elm["DataValue"] = 0
end
end
df = DataFrame(json_obj["BEAAPI"]["Results"][1]["Data"])
df[!,:DataValue] = parse_missing.(df[!,:DataValue])
df[!,:DataValue] = df[!,:DataValue]./1_000
df[!,:value] = df[!,:DataValue]
return df[!,[:Year,:RowCode,:ColCode,:value]]
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 8790 | #include("./data_defines.jl")
function load_bea_gsp!(GU,data_dir,gsp_info)
@parameters(GU,begin
region_shr, (:yr,:r,:i), (description = "Regional share of value added",)
labor_shr, (:yr,:r,:i), (description = "Estimated share of regional value added due to labor",)
end)
df = load_raw_bea_gsp(data_dir,1997:2021,gsp_info)
df = clean_raw_bea_gsp(df)
df = unstack(df,:gdpcat,:value);
# Region Shares
df[!,:gdp_calc] = df[!,:cmp] + df[!,:gos] + df[!,:taxsbd]
df[!,:gdp_diff] = df[!,:gdp] - df[!,:gdp_calc];
X = df[!,[:region_abbv,:year,:i,:gdp]]
Y = groupby(X,[:year,:i])
C = combine(Y,:gdp=>sum)
Y = leftjoin(X,C,on = [:year,:i])
df[!,:region_shr] = Y[!,:gdp]./Y[!,:gdp_sum]
for row in eachrow(df)
d = [[row[e]] for e∈[:year,:region_abbv,:i]]
GU[:region_shr][d...] = row[:region_shr]
end
klshare = create_klshare(GU,df)
models = Dict()
for yr∈GU[:yr],s∈GU[:i]
function filter_cond(year,i)
year==yr && i==s
end
klshare_l = GamsStructure.Parameter(GU,(:r,:yr))
klshare_k = GamsStructure.Parameter(GU,(:r,))
klshare_l_nat = GamsStructure.Parameter(GU,(:r,))
klshare_k_nat = GamsStructure.Parameter(GU,(:r,))
for y∈rolling_average_years(yr,8)
X = filter([:year,:i]=> (year,i) -> year==y && i==s, klshare)
for row∈eachrow(X)
r = row[:region_abbv]
klshare_l[[r],[y]] = row[:l]
end
end
X = filter([:year,:i]=>filter_cond, klshare)
for row∈eachrow(X)
r = row[:region_abbv]
klshare_k[[r]] = row[:k]
klshare_l_nat[[r]] = row[:l_nat]
klshare_k_nat[[r]] = row[:k_nat]
end
gspbal = GamsStructure.Parameter(GU,(:r,))
X = filter([:year,:i]=>filter_cond,df)
for row∈eachrow(X)
r = row[:region_abbv]
gspbal[[r]] = row[:gdp]
end
ld0 = GU[:va0][[yr],[:compen],[s]]
kd0 = GU[:va0][[yr],[:surplus],[s]]
region_shr_ = GamsStructure.Parameter(GU,(:r,))
X = filter([:year,:i]=>filter_cond,df)
for row∈eachrow(X)
r = row[:region_abbv]
region_shr_[[r]] = row[:region_shr]
end
m = gsp_share_calibrate(GU,yr,gspbal,region_shr_,klshare_l,ld0,kd0,klshare_k,klshare_l_nat,klshare_k_nat)
set_silent(m)
optimize!(m)
models[yr,s] = m
GU[:labor_shr][[yr],:r,[s]] = value.(m[:L_SHR])
end
return (GU,models)
end
function load_bea_gsp_file(file_path::String,years::UnitRange,nrows::Int,ComponentName,rename_dict)
df = DataFrame(CSV.File(file_path,silencewarnings=true,stringtype=String)[1:nrows]);
df = stack(df,Symbol.(years),variable_name = :year)
function parse_missing(val::Number)
return val
end
function parse_missing(val::String)
try
return parse(Float64,val)
catch
return missing
end
end
df[!,:value] = parse_missing.(df[!,:value])
df[!,:value] = coalesce.(df[!,:value],0)
#replace!(df[!,:value], missing => 0)
df[!,:GeoFIPS] = parse.(Int,df[!,:GeoFIPS])
df[!,:ComponentName] .= ComponentName
df[!,:GeoName] = String.(strip.(replace.(df[!,:GeoName], "*"=>"")))
rename!(df, :LineCode => :IndustryID)
rename!(df,rename_dict)
return df[!,["GeoFIPS","state","region","TableName","IndustryID","IndustryClassification","Description","ComponentName","units","year","value"]]
end
function load_raw_bea_gsp(data_dir,years,gsp_data)
column_rename_dict = Dict(
:GeoFIPS=> :GeoFIPS,
:GeoName=> :state,
:Region=> :region,
:TableName=> :TableName,
:IndustryId=> :IndustryId,
:IndustryClassification=> :IndustryClassification,
:Description=> :Description,
:Unit=> :units,
:year=> :year,
:value=> :value,
:ComponentName=> :ComponentName
)
df = DataFrame()
for (a,gsp_info) ∈ gsp_data
df1 = load_bea_gsp_file(joinpath(data_dir,gsp_info["path"]),
years,
gsp_info["nrows"],
gsp_info["ComponenentName"],
column_rename_dict);
df = vcat(df,df1)
end
return df
end
function clean_raw_bea_gsp(df)
#notations = []
#push!(notations,notation_link(gsp_states,:state,:region_fullname))
##push!(notations,notation_link(gsp_industry_id,:IndustryID,:gsp_industry_id))
#push!(notations,notation_link(bea_gsp_mapsec,:IndustryID,:gdp_industry_id))
#push!(notations,notation_link(bea_gsp_map,:ComponentName,:bea_code))
notations = bea_gsp_notations()
df = apply_notations(df,notations)
df = df[!,[:region_abbv,:year,:gdpcat,:i,:units,:value]]
base_units = unique(df[!,:units])
df = unstack(df,:units,:value)
df[!,"Thousands of dollars"] = df[!,"Thousands of dollars"]./1_000
df = dropmissing(stack(df,base_units,variable_name=:units,value_name=:value))
df[!,:units] = replace(df[!,:units],
"Thousands of dollars" => "millions of us dollars (USD)",
"Millions of current dollars" => "millions of us dollars (USD)"
)
function _filter_out(units,regions)
out = units == "millions of us dollars (USD)" &&
regions != "US"
return out
end
filter!([:units,:region_abbv] => _filter_out,df)
df[!,:year] = Symbol.(df[!,:year])
df[!,:region_abbv] = Symbol.(df[!,:region_abbv])
df[!,:i] = Symbol.(df[!,:i])
return select(df,Not(:units))
end
function create_klshare(GU,df)
klshare = df[!,[:year,:region_abbv,:i]]
klshare[!,:l] = df[!,:cmp] ./ (df[!,:gdp_diff] .+ df[!,:gos] .+ df[!,:cmp])
#klshare[!,:l_nat] =
kl = GamsStructure.Parameter(GU,(:yr,:i))
kl[:yr,:i] = GU[:va0][:yr,[:compen],:i] ./ (GU[:va0][:yr,[:compen],:i] .+ GU[:va0][:yr,[:surplus],:i])
kl = DataFrame(vec([(yr,i,kl[[yr],[i]]) for yr∈GU[:yr],i∈GU[:i]]),[:year,:i,:l_nat]);
klshare = leftjoin(klshare,kl,on = [:year,:i])
klshare[!,:k] = 1 .- klshare[!,:l]
klshare[!,:k_nat] = 1 .- klshare[!,:l_nat]
Y = combine(groupby(df,[:year,:i]),:cmp=>sum,:gdp_diff=>sum,:gos=>sum)
chk_national_shares = Y[!,[:year,:i]]
chk_national_shares[!,:gsp] = Y[!,:cmp_sum] ./ (Y[!,:gdp_diff_sum] + Y[!,:gos_sum] + Y[!,:cmp_sum])
chk_national_shares = leftjoin(chk_national_shares,kl,on = [:year,:i])
chk_national_shares[!,:shr] = chk_national_shares[!,:l_nat]./chk_national_shares[!,:gsp]
klshare = leftjoin(klshare,chk_national_shares[!,[:year,:i,:shr]],on = [:year,:i])
klshare[!,:l_diff] = klshare[!,:l].*klshare[!,:shr]
klshare[!,:l] = klshare[!,:l].*klshare[!,:shr]
klshare[!,:k] = 1 .- klshare[!,:l]
prob_tot = klshare[!,:k] .<0 .||
klshare[!,:k] .>=1 .||
abs.(klshare[!,:k] - klshare[!,:k_nat]) .>.75
klshare[df[!,:region_shr] .!=0 .&& prob_tot,:l] .= klshare[df[!,:region_shr] .!=0 .&& prob_tot,:l_nat]
klshare[df[!,:region_shr] .!=0, :k] = 1 .-klshare[df[!,:region_shr] .!=0, :l]
for c ∈ eachcol(klshare)
replace!(c, NaN => 0.0)
end
return klshare
end
function gsp_share_calibrate(GU,yr,gspbal,region_shr_,klshare_l,ld0,kd0,klshare_k,klshare_l_nat,klshare_k_nat)
m = JuMP.Model(Ipopt.Optimizer)
R = [r for r∈GU[:r]]
YR = [yr for yr∈GU[:yr]]
@variables(m, begin
K_SHR[r=R]>=.25*klshare_k_nat[[r]], (start = klshare_k[[r]],)
L_SHR[r=R]>=.25*klshare_l_nat[[r]], (start = klshare_l[[r],yr],)
end)
for r∈R
if region_shr_[[r]] == 0
fix(K_SHR[r],0,force=true)
fix(L_SHR[r],0,force=true)
end
end
@constraints(m,begin
shrdef[r=R; region_shr_[[r]]!=0],
L_SHR[r] + K_SHR[r] == 1
lshrdef,
sum(L_SHR[r]*region_shr_[[r]]*(ld0+kd0) for r∈R) == ld0
kshrdef,
sum(K_SHR[r]*region_shr_[[r]]*(ld0+kd0) for r∈R) == kd0
end)
@objective(m, Min,
sum(abs(gspbal[[r]]) * (L_SHR[r]/klshare_l[[r],[yr]]-1)^2 for r∈R,yr∈YR if klshare_l[[r],[yr]]!=0 && region_shr_[[r]]!=0)
)
return m
end
function rolling_average_years(yr,numyears;min=1997,max=2021)
yr = parse(Int,string(yr))
return Symbol.([yr+y for y∈-Int(numyears/2):Int(numyears/2) if min<=yr+y<=max])
end
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 9585 | #include("./bea_api/bea_api.jl")
include("./calibrate.jl")
#include("./data_defines.jl")
function _bea_io_initialize_universe!(GU)
@parameters(GU,begin
#Use
id0, (:yr,:i,:j), (description = "Intermediate Demand",)
fd0, (:yr,:i,:fd), (description = "Final Demand",)
x0, (:yr,:i), (description = "Exports",)
va0, (:yr, :va,:j), (description = "Value Added",)
ts0, (:yr,:ts,:j), (description = "Taxes and Subsidies",)
othtax, (:yr,:j), (description = "Other taxes",)
#Supply
ys0, (:yr,:j,:i), (description = "Intermediate Supply",)
m0, (:yr,:i), (description = "Imports",)
mrg0, (:yr,:i), (description = "Trade Margins",)
trn0, (:yr,:i), (description = "Transportation Costs",)
cif0, (:yr,:i)
duty0,(:yr,:i), (description = "Import Duties",)
tax0, (:yr,:i), (description = "Taxes on Products",)
sbd0, (:yr,:i), (description = "Subsidies",)
end);
return GU
end
"""
load_bea_data_api(GU::GamsUniverse,api_key::String)
Load the the BEA data using the BEA API.
In order to use this you must have an api key from the BEA. [Register here](https://apps.bea.gov/api/signup/)
to obtain an key.
Currently (Septerber 28, 2023) this will only return years 2017-2022 due
to the BEA restricting the API.
"""
function load_bea_data_api(GU::GamsUniverse,api_key::String)
_bea_io_initialize_universe!(GU)
load_supply_use_api!(GU,api_key)
_bea_data_break!(GU)
calibrate_national!(GU)
return GU
end
"""
load_bea_io!(GU::GamsUniverse,
data_dir::String,
info_dict
)
Load the BEA data from a local XLSX file. This data is available
[at the WiNDC webpage](https://windc.wisc.edu/downloads.html). The use table is
windc_2021/BEA/IO/Use_SUT_Framework_1997-2021_SUM.xlsx
and the supply table is
windc_2021/BEA/IO/Supply_Tables_1997-2021_SUM.xlsx
"""
function load_bea_io!(GU::GamsUniverse,
data_dir::String,
info_dict
)
_bea_io_initialize_universe!(GU)
use_path = joinpath(data_dir,info_dict["use"])
use = _load_table_local(use_path)
supply_path = joinpath(data_dir,info_dict["supply"])
supply = _load_table_local(supply_path)
_bea_apply_notations!(GU,use,supply)
_bea_data_break!(GU)
calibrate_national!(GU)
return GU
end
function load_supply_use_api!(GU,api_key::String)
use = get_bea_io_table(api_key,:use)
supply = get_bea_io_table(api_key,:supply);
_bea_apply_notations!(GU,use,supply)
return GU
end
function _bea_apply_notations!(GU,use,supply)
notations = bea_io_notations()
use = apply_notations(use,notations)
supply = apply_notations(supply,notations)
use[!,:industry] = Symbol.(use[!,:industry])
use[!,:commodity] = Symbol.(use[!,:commodity])
use[!,:Year] = Symbol.(use[!,:Year]);
supply[!,:industry] = Symbol.(supply[!,:industry])
supply[!,:commodity] = Symbol.(supply[!,:commodity])
supply[!,:Year] = Symbol.(supply[!,:Year]);
col_set_link = Dict(:yr => :Year,
:j => :industry,
:i => :commodity,
:fd => :industry,
:va => :commodity,
:ts => :commodity
)
additional_filters = Dict(
:othtax => (:commodity,:othtax),
:x0 => (:industry, :exports),
:m0 => (:industry, :imports),
:mrg0 => (:industry, :Margins),
:trn0 => (:industry, :TrnCost),
:cif0 => (:industry, :ciffob),
:duty0 => (:industry, :Duties),
:tax0 => (:industry, :Tax),
:sbd0 => (:industry, :Subsidies)
)
#Use
for parm in [:id0,:fd0,:va0,:ts0,:othtax,:x0]
fill_parameter!(GU, use, parm, col_set_link, additional_filters)
end
#Supply
for parm in [:ys0,:m0,:mrg0,:trn0,:cif0,:duty0,:tax0,:sbd0]
fill_parameter!(GU, supply, parm, col_set_link, additional_filters)
end
GU[:sbd0][:yr,:i] = - GU[:sbd0][:yr,:i]
return GU
end
function _load_table_local(path::String)
X = XLSX.readxlsx(path);
df = DataFrame()
for sheet in XLSX.sheetnames(X)
Y = X[sheet][:]
rows,cols = size(Y)
Y[(Y .== "...") .& (.!ismissing.(Y))] .= missing
col_names = ["RowCode","RowDescription"]
append!(col_names,vec(Y[6,3:cols]))
df1 = DataFrame(Y[8:rows,1:cols], col_names)
df1 = stack(df1, Not([:RowCode,:RowDescription]),variable_name = :ColCode, value_name = :value)
df1[!,:Year] .= sheet
df1 = df1[.!ismissing.(df1[!,:value]),[:Year,:RowCode,:ColCode,:value]]
df1[!,:value] = df1[!,:value]./1_000
df = vcat(df,df1)
end
return df
end
function _bea_data_break!(GU)
# Define parameters
GU[:ys0][:yr,:j,:i] = GU[:ys0][:yr,:j,:i] - min.(0,permutedims(GU[:id0][:yr,:i,:j],[1,3,2]))
GU[:id0][:yr,:i,:j] = max.(0,GU[:id0][:yr,:i,:j])
GU[:ts0][:yr,[:subsidies],:j] = -GU[:ts0][:yr,[:subsidies],:j]
# Adjust transport margins for transport sectors according to CIF/FOB
# adjustments. Insurance imports are specified as net of adjustments.
iₘ = [e for e ∈GU[:i] if e!=:ins]
GU[:trn0][:yr,iₘ] = GU[:trn0][:yr,iₘ] .+ GU[:cif0][:yr,iₘ]
GU[:m0][:yr,[:ins]] = GU[:m0][:yr,[:ins]] .+ GU[:cif0][:yr,[:ins]]
# Second phase
# More parameters
@parameters(GU,begin
s0, (:yr,:j), (description = "Aggregate Supply",)
ms0, (:yr,:i,:m), (description = "Margin Supply",)
md0, (:yr,:m,:i), (description = "Margin Demand",)
fs0, (:yr,:i), (description = "Household Supply",)
y0, (:yr,:i), (description = "Gross Output",)
a0, (:yr,:i), (description = "Armington Supply",)
tm0, (:yr,:i), (description = "Tax net subsidy rate on intermediate demand",)
ta0, (:yr,:i), (description = "Import Tariff",)
ty0, (:yr,:j), (description = "Output tax rate",)
end);
GU[:s0][:yr,:j] = sum(GU[:ys0][:yr,:j,:i],dims=2);
GU[:ms0][:yr,:i,[:trd]] = -min.(0, GU[:mrg0][:yr,:i])
GU[:ms0][:yr,:i,[:trn]] = -min.(0, GU[:trn0][:yr,:i])
GU[:md0][:yr,[:trd],:i] = max.(0, GU[:mrg0][:yr,:i])
GU[:md0][:yr,[:trn],:i] = max.(0, GU[:trn0][:yr,:i])
GU[:fs0][:yr,:i] = -min.(0, GU[:fd0][:yr,:i,[:pce]])
GU[:y0][:yr,:i] = dropdims(sum(GU[:ys0][:yr,:j,:i],dims=2),dims=2) + GU[:fs0][:yr,:i] - dropdims(sum(GU[:ms0][:yr,:i,:m],dims=3),dims=3)
GU[:a0][:yr,:i] = sum(GU[:id0][:yr,:i,:j],dims=3) + sum(GU[:fd0][:yr,:i,:fd],dims=3)
IMRG = [:mvt,:fbt,:gmt]
GU[:y0][:yr,IMRG] = 0*GU[:y0][:yr,IMRG]
GU[:a0][:yr,IMRG] = 0*GU[:a0][:yr,IMRG]
GU[:tax0][:yr,IMRG] = 0*GU[:tax0][:yr,IMRG]
GU[:sbd0][:yr,IMRG] = 0*GU[:sbd0][:yr,IMRG]
GU[:x0][:yr,IMRG] = 0*GU[:x0][:yr,IMRG]
GU[:m0][:yr,IMRG] = 0*GU[:m0][:yr,IMRG]
GU[:md0][:yr,:m,IMRG] = 0*GU[:md0][:yr,:m,IMRG]
GU[:duty0][:yr,IMRG] = 0*GU[:duty0][:yr,IMRG]
#mask = GU[:m0][:yr,:i] .>0
#mask = Mask(GU,(:yr,:i))
#mask[:yr,:i] = (GU[:m0][:yr,:i] .> 0)
#GU[:tm0][mask] = GU[:duty0][mask]./GU[:m0][mask]
#mask = GU[:a0][:yr,:i] .!= 0
#mask[:yr,:i] = (GU[:a0][:yr,:i] .!= 0)
#GU[:ta0][mask] = (GU[:tax0][mask] - GU[:sbd0][mask]) ./ GU[:a0][mask]
for yr∈GU[:yr],i∈GU[:i]
if GU[:m0][yr,i] > 0
GU[:tm0][yr,i] = GU[:duty0][yr,i]/GU[:m0][yr,i]
end
if GU[:a0][yr,i] != 0
GU[:ta0][yr,i] = (GU[:tax0][yr,i] - GU[:sbd0][yr,i]) / GU[:a0][yr,i]
end
end
#####################
## Negative Values ##
#####################
GU[:id0][:yr,:i,:j] = GU[:id0][:yr,:i,:j] .- permutedims(min.(0,GU[:ys0][:yr,:j,:i]),[1,3,2])
GU[:ys0][:yr,:j,:i] = max.(0,GU[:ys0][:yr,:j,:i])
GU[:a0][:yr,:i] = max.(0, GU[:a0][:yr,:i])
GU[:x0][:yr,:i] = max.(0, GU[:x0][:yr,:i])
GU[:y0][:yr,:i] = max.(0, GU[:y0][:yr,:i])
GU[:fd0][:yr,:i,[:pce]] = max.(0, GU[:fd0][:yr,:i,[:pce]]);
#THis is stupid.
#GU[:duty0][GU[:m0].==0] = (GU[:duty0][GU[:m0].==0] .=1);
for yr∈GU[:yr],i∈GU[:i]
if GU[:m0][yr,i] == 0
GU[:duty0][yr,i] = 1
end
end
m_shr = GamsStructure.Parameter(GU,(:i,))
va_shr = GamsStructure.Parameter(GU,(:j,:va))
deactivate(GU,:i,:use,:oth)
deactivate(GU,:j,:use,:oth)
m_shr[:i] = transpose(sum(GU[:m0][:yr,:i],dims = 1)) ./ sum(GU[:m0][:yr,:i])
va_shr[:j,:va] = permutedims(sum(GU[:va0][:yr,:va,:j],dims=1)./ sum(GU[:va0][:yr,:va,:j],dims=(1,2)),(3,2,1))
for yr∈GU[:yr],i∈GU[:i]
GU[:m0][[yr],[i]] = GU[:m0][[yr],[i]]<0 ? m_shr[[i]]*sum(GU[:m0][[yr],:i]) : GU[:m0][[yr],[i]]
end
for year∈GU[:yr],va∈GU[:va], j∈GU[:j]
GU[:va0][[year],[va],[j]] = GU[:va0][[year],[va],[j]]<0 ? va_shr[[j],[va]]*sum(GU[:va0][[year],:va,[j]]) : GU[:va0][[year],[va],[j]]
end
# Non-tracked marginal categories.
IMRG = [:mvt,:fbt,:gmt]
for yr∈GU[:yr],i∈IMRG
GU[:y0][[yr],[i]] = 0
GU[:a0][[yr],[i]] = 0
GU[:tax0][[yr],[i]] = 0
GU[:sbd0][[yr],[i]] = 0
GU[:x0][[yr],[i]] = 0
GU[:m0][[yr],[i]] = 0
GU[:duty0][[yr],[i]] = 0
for m∈GU[:m]
GU[:md0][[yr],[m],[i]] = 0
end
end
GU[:ty0][:yr,:j] = GU[:othtax][:yr,:j] ./ sum(GU[:ys0][:yr,:j,:i],dims=3)
for yr∈GU[:yr],j∈GU[:j]
GU[:va0][[yr],[:othtax],[j]] = 0
end
return GU
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 9696 |
"""
calibrate_national!(GU::GamsUniverse)
Calibrate the national BEA IO data.
"""
function calibrate_national!(GU::GamsUniverse)
parms_to_update = [(:ys0,:ys0_),
(:id0,:id0_),
(:ms0,:ms0_),
(:y0,:y0_),
(:fd0,:fd0_),
(:a0,:a0_),
(:x0,:x0_),
(:m0,:m0_),
(:md0,:md0_),
(:va0,:va0_),
(:fs0,:fs0_)
]
for year∈GU[:yr]
m = calibrate_national_model(GU,year)
set_silent(m)
optimize!(m)
for (old,new)∈parms_to_update
sets = [[elm for elm in GU[s]] for s∈domain(GU[old])[2:end]]
for element in Iterators.product(sets...)
elm = [[year]]
push!(elm,[[e] for e∈element]...)
GU[old][elm...] = value(m[new][element...])
end
end
end
# A couple of parameters get created/updated after calibration
@parameters(GU,begin
bopdef0, (:yr,)
end)
for yr∈GU[:yr]
GU[:bopdef0][[yr]] = sum(GU[:m0][[yr],[i]]-GU[:x0][[yr],[i]] for i∈GU[:i] if GU[:a0][[yr],[i]]!=0;init=0)
for j∈GU[:j]
GU[:s0][[yr],[j]] = sum(GU[:ys0][[yr],[j],:i])
end
end
P = calibrate_zero_profit(GU)
@assert sum(abs.(P[:yr,:j,:tmp])) ≈ 0 "Calibration has failed to satisfy the zero profit condition."
P = calibrate_market_clearance(GU)
@assert sum(abs.(P[:yr,:i,:tmp])) ≈ 0 "Calibration has failed to satisfy the market clearance condition."
return GU
end
function calibrate_national_model(GU::GamsUniverse,year::Symbol)
#year = Symbol(1997)
#May go elsewhere
deactivate(GU,:i,:use,:oth)
deactivate(GU,:j,:use,:oth)
I = [i for i in GU[:i]]
J = [j for j in GU[:j]]
M = [m_ for m_ in GU[:m]]
FD = [fd for fd in GU[:fd]]
VA = [va for va in GU[:va]]
PCE_FD = [:pce]
OTHFD = [fd for fd in GU[:fd] if fd != :pce]
IMRG = [:mvt,:fbt,:gmt]
ys0 = GU[:ys0]
id0 = GU[:id0]
fd0 = GU[:fd0]
va0 = GU[:va0]
fs0 = GU[:fs0]
ms0 = GU[:ms0]
y0 = GU[:y0]
id0 = GU[:id0]
a0 = GU[:a0]
x0 = GU[:x0]
m0 = GU[:m0]
md0 = GU[:md0]
ty0 = GU[:ty0]
ta0 = GU[:ta0]
tm0 = GU[:tm0]
lob = 0.01 #Lower bound ratio
upb = 10 #upper bound ratio
newnzpenalty = 1e3
m = JuMP.Model(Ipopt.Optimizer)
@variables(m,begin
ys0_[j=J,i=I] >= max(0,lob*ys0[[year],[j],[i]]) #"Calibrated variable ys0."
ms0_[i=I,m_=M] >= max(0,lob*ms0[[year],[i],[m_]]) #"Calibrated variable ms0."
y0_[i=I] >= max(0,lob*y0[[year],[i]]) #"Calibrated variable y0."
id0_[i=I,j=J] >= max(0,lob*id0[[year],[i],[j]]) #"Calibrated variable id0."
fd0_[i=I,fd=FD] >= max(0,lob*fd0[[year],[i],[fd]]) #"Calibrated variable fd0."
a0_[i=I] >= max(0,lob*a0[[year],[i]]) #"Calibrated variable a0."
x0_[i=I] >= max(0,lob*x0[[year],[i]]) #"Calibrated variable x0."
m0_[i=I] >= max(0,lob*m0[[year],[i]]) #"Calibrated variable m0."
md0_[m_=M,i=I] >= max(0,lob*md0[[year],[m_],[i]]) #"Calibrated variable md0."
va0_[va=VA,j=J] >= max(0,lob*va0[[year],[va],[j]]) #"Calibrated variable va0."
fs0_[I] >= 0 #"Calibrated variable fs0."
end)
function _set_upb(var,parm,sets...)
for idx ∈ Iterators.product(sets...)
ind = [[e] for e in idx]
if parm[[year],ind...] != 0
set_upper_bound(var[idx...],abs(upb*parm[[year],ind...]))
end
end
end
_set_upb(ys0_,ys0,J,I)
_set_upb(ms0_,ms0,I,M)
_set_upb(y0_,y0,I)
_set_upb(id0_,id0,I,J)
_set_upb(fd0_,fd0,I,FD)
_set_upb(a0_,a0,I)
_set_upb(x0_,x0,I)
_set_upb(m0_,m0,I)
_set_upb(md0_,md0,M,I)
_set_upb(va0_,va0,VA,J)
function _fix(var,parm,sets...)
for idx ∈ Iterators.product(sets...)
ind = [[e] for e in idx]
if parm[[year],ind...] == 0
fix(var[idx...],0,force=true)
end
end
end
# Assume zero values remain zero values for multi-dimensional parameters:
_fix(ys0_,ys0,J,I)
_fix(id0_,id0,I,J)
_fix(fd0_,fd0,I,FD)
_fix(ms0_,ms0,I,M)
_fix(va0_,va0,VA,J)
# Fix certain parameters -- exogenous portions of final demand, value
# added, imports, exports and household supply.
for i∈I
fix.(fs0_[i],fs0[year,i],force=true)
fix.(m0_[i] ,m0[year,i] ,force=true)
fix.(x0_[i] ,x0[year,i] ,force=true)
end
# Fix labor compensation to target NIPA table totals.
fix.(va0_[:compen,J],va0[[year],[:compen],J],force=true)
# No margin inputs to goods which only provide margins:
fix.(md0_[M,IMRG] ,0,force=true)
fix.(y0_[IMRG] ,0,force=true)
fix.(m0_[IMRG] ,0,force=true)
fix.(x0_[IMRG] ,0,force=true)
fix.(a0_[IMRG] ,0,force=true)
fix.(id0_[IMRG,J] ,0,force=true)
fix.(fd0_[IMRG,FD],0,force=true)
@expression(m,NEWNZ,
sum(ys0_[j,i] for j∈J,i∈I if ys0[[year],[j],[i]]==0 )
+ sum(fs0_[i] for i∈I if fs0[[year],[i]]==0 )
+ sum(ms0_[i,m_] for i∈I,m_∈M if ms0[[year],[i],[m_]]==0 )
+ sum(y0_[i] for i∈I if y0[[year],[i]]==0 )
+ sum(id0_[i,j] for i∈I,j∈J if id0[[year],[i],[j]]==0 )
+ sum(fd0_[i,fd] for i∈I,fd∈FD if fd0[[year],[i],[fd]]==0 )
+ sum(va0_[va,j] for va∈VA,j∈J if va0[[year],[va],[j]]==0 )
+ sum(a0_[i] for i∈I if a0[[year],[i]]==0 )
+ sum(x0_[i] for i∈I if x0[[year],[i]]==0 )
+ sum(m0_[i] for i∈I if m0[[year],[i]]==0 )
+ sum(md0_[m_,i] for m_∈M,i∈I if md0[[year],[m_],[i]]==0 )
)
@objective(m,Min,
sum(abs(ys0[[year],[j],[i]]) * (ys0_[j,i]/ys0[[year],[j],[i]]-1)^2 for i∈I,j∈J if ys0[[year],[j],[i]]!=0 )
+ sum(abs(id0[[year],[i],[j]]) * (id0_[i,j]/id0[[year],[i],[j]]-1)^2 for i∈I,j∈J if id0[[year],[i],[j]]!=0 )
+ sum(abs(fd0[[year],[i],[fd]]) * (fd0_[i,fd]/fd0[[year],[i],[fd]]-1)^2 for i∈I,fd∈PCE_FD if fd0[[year],[i],[fd]]!=0 )
+ sum(abs(va0[[year],[va],[j]]) * (va0_[va,j]/va0[[year],[va],[j]]-1)^2 for va∈VA,j∈J if va0[[year],[va],[j]]!=0 )
+ sum(abs(fd0[[year],[i],[fd]]) * (fd0_[i,fd]/fd0[[year],[i],[fd]]-1)^2 for i∈I,fd∈OTHFD if fd0[[year],[i],[fd]]!=0 )
+ sum(abs(fs0[[year],[i]]) * (fs0_[i]/fs0[[year],[i]]-1)^2 for i∈I if fs0[[year],[i]]!=0 )
+ sum(abs(ms0[[year],[i],[m_]]) * (ms0_[i,m_]/ms0[[year],[i],[m_]]-1)^2 for i∈I,m_∈M if ms0[[year],[i],[m_]]!=0 )
+ sum(abs(y0[[year],[i]]) * (y0_[i]/y0[[year],[i]]-1)^2 for i∈I if y0[[year],[i]]!=0 )
+ sum(abs(a0[[year],[i]]) * (a0_[i]/a0[[year],[i]]-1)^2 for i∈I if a0[[year],[i]]!=0 )
+ sum(abs(x0[[year],[i]]) * (x0_[i]/x0[[year],[i]]-1)^2 for i∈I if x0[[year],[i]]!=0 )
+ sum(abs(m0[[year],[i]]) * (m0_[i]/m0[[year],[i]]-1)^2 for i∈I if m0[[year],[i]]!=0 )
+ sum(abs(md0[[year],[m_],[i]]) * (md0_[m_,i]/md0[[year],[m_],[i]]-1)^2 for m_∈M,i∈I if md0[[year],[m_],[i]]!=0 )
+ newnzpenalty * NEWNZ
)
@constraints(m,begin
mkt_py[i=I],
sum(ys0_[J,i]) + fs0_[i] == sum(ms0_[i,M]) + y0_[i]
mkt_pa[i=I],
a0_[i] == sum(id0_[i,J]) + sum(fd0_[i,FD])
mkt_pm[m_=M],
sum(ms0_[I,m_]) == sum(md0_[m_,I])
prf_y[j=J],
(1-ty0[[year],[j]])*sum(ys0_[j,I]) == sum(id0_[I,j]) + sum(va0_[VA,j])
prf_a[i=I],
a0_[i]*(1-ta0[[year],[i]]) + x0_[i] == y0_[i] + m0_[i]*(1+tm0[[year],[i]]) + sum(md0_[M,i])
end)
1;
return m
end
function calibrate_zero_profit(GU::GamsUniverse)
G = deepcopy(GU)
@set(G,tmp,"tmp",begin
Y,""
A,""
end)
@parameters(G,begin
profit, (:yr,:j,:tmp), (description = "Zero profit condidtions",)
end)
YR = G[:yr]
J = G[:j]
I = G[:i]
VA = G[:va]
M = G[:m]
parm = G[:profit]
for yr∈YR,j∈J
parm[[yr],[j],[:Y]] = G[:s0][[yr],[j]] !=0 ? round((1-G[:ty0][[yr],[j]]) * sum(G[:ys0][[yr],[j],I]) - sum(G[:id0][[yr],I,[j]]) - sum(G[:va0][[yr],VA,[j]]),digits = 6) : 0
parm[[yr],[j],[:A]] = round(G[:a0][[yr],[j]]*(1-G[:ta0][[yr],[j]]) + G[:x0][[yr],[j]] - G[:y0][[yr],[j]] - G[:m0][[yr],[j]]*(1+G[:tm0][[yr],[j]]) - sum(G[:md0][[yr],M,[j]]), digits = 6)
end
return parm
end
function calibrate_market_clearance(GU::GamsUniverse)
G = deepcopy(GU)
@set(G,tmp,"tmp",begin
PA,""
PY,""
end)
@parameters(G,begin
market, (:yr,:i,:tmp), (description = "Market clearance condition",)
end)
YR = G[:yr]
J = G[:j]
I = G[:i]
FD = G[:fd]
M = G[:m]
parm = G[:market]
for yr∈YR,i∈I
parm[[yr],[i],[:PA]] = round( G[:a0][[yr],[i]] - sum(G[:fd0][[yr],[i],FD];init=0)- sum(G[:id0][[yr],[i],[j]] for j∈J if G[:s0][[yr],[j]]!=0;init=0),digits = 6)
parm[[yr],[i],[:PY]] = round( sum(G[:ys0][[yr],[j],[i]] for j∈J if G[:s0][[yr],[j]]!=0;init=0) + G[:fs0][[yr],[i]] - G[:y0][[yr],[i]] - sum(G[:ms0][[yr],[i],M];init=0),digits=6)
end
return parm
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 1349 | #include("./data_defines.jl")
function load_bea_pce!(GU,data_dir,info_dict)
info = info_dict["saexp1"]
data_path = "$data_dir\\$(info["path"])"
nrows = info["nrows"]
notations = bea_pce_notations()
df = DataFrame(CSV.File(data_path;limit = nrows,stringtype=String)) |>
x -> select(x,Not([:Unit,:IndustryClassification,:GeoFIPS,:Region,:TableName,:LineCode])) |>
x -> transform(x,
:Description => (y -> string.(strip.(y))) => :Description
) |>
x -> apply_notations(x,notations) |>
x -> stack(x, Not([:r,:i]),variable_name = :year,value_name = :value)
df = df |>
x -> groupby(x,[:year,:i]) |>
x -> combine(x, :value => sum) |>
x -> leftjoin(df,x, on = [:year,:i]) |>
x -> transform(x,
[:value,:value_sum] => ((v,vs) -> v./vs) => :value,
:i => (i -> Symbol.(i)) => :i,
:r => (i -> Symbol.(i)) => :r,
:year => (i -> Symbol.(i)) => :year
)
@parameters(GU,begin
pce_shr, (:yr,:r,:i), (description = "Regional shares of final consumption",)
end)
col_set_link = Dict(:yr => :year,
:r => :r,
:i => :i
)
fill_parameter!(GU, df, :pce_shr, col_set_link, Dict())
return GU
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 3444 | #include("./data_defines.jl")
function sgf_parse_line(s)
out = ( government_code = string(s[1:14]),
item_code = string(s[15:17]),
amount = string(s[18:29]),
survey_year = string(s[30:31]),
year = string(s[32:33]),
origin = string(s[34:35])
)
return out
end
function sgf_parse_line_1999(s)
out = ( government_code = string(s[1:14]),
origin = string(s[18:19]),
item_code = string(s[22:24]),
amount = string(s[25:35]),
survey_year = "99",
year = "99",
)
return out
end
function sgf_load_clean_year(year,data_dir,path)
data_path = joinpath(data_dir,path)
s = open(data_path) do f
s = read(f,String)
end
if year == "1999"
f = sgf_parse_line_1999
else
f = sgf_parse_line
end
notations = sgf_notations()
#notations = []
#push!(notations,WiNDC.notation_link(sgf_state_codes,:government_code,:code))
#push!(notations,WiNDC.notation_link(sgf_states, :state, :region_fullname))
#push!(notations,WiNDC.notation_link(item_codes, :item_code,:item_code));
#push!(notations,WiNDC.notation_link(sgf_map, :item_name,:sgf_category));
#push!(notations,WiNDC.notation_link(sgf_gams_map, :i,:sgf_category));
L = f.([e for e in split(s,'\n') if e!=""])
df = DataFrame(L) |>
x -> apply_notations(x,notations) |>
x -> transform(x,
:amount => (y -> parse.(Int,y)) => :amount
) |>
x -> groupby(x,[:i,:region_abbv]) |>
x -> combine(x, :amount => sum) |>
x -> transform(x,
:amount_sum => (y -> Symbol(year)) => :year,
:amount_sum => (a -> a./1_000) => :value,
:i => (i -> Symbol.(i)) => :i,
:region_abbv => (r -> Symbol.(r)) => :region_abbv
)
#df = apply_notations(df,notations)
#df[!,:amount] = parse.(Int,df[!,:amount])
#df = combine(groupby(df,[:i,:region_abbv]),:amount => sum);
#df[!,:year] .= year;
#df[!,:value] = df[!,:amount_sum]./1_000
#df[!,:year] = Symbol.(df[!,:year])
#df[!,:i] = Symbol.(df[!,:i])
#df[!,:region_abbv] = Symbol.(df[!,:region_abbv])
return df
end
function load_sgf_data!(GU,data_dir,info_dict)
@parameters(GU,begin
sgf_shr, (:yr,:r,:i), (description = "Regional shares of final consumption",)
end)
df = DataFrame()
for (year,path) in info_dict
small_df = sgf_load_clean_year(year,data_dir,path)
df = vcat(df,small_df)
end
#Add DC in regions
df = df |>
x -> select(x, [:i,:region_abbv,:year,:value]) |>
x -> unstack(x, :region_abbv, :value) |>
x -> transform(x, :MD => (y->y) => :DC) |>
x -> stack(x, Not(:i,:year),variable_name = :region_abbv) |>
x -> transform(x, :region_abbv => (y->Symbol.(y)) => :region_abbv)|>
x -> dropmissing(x)
#return df
df = df |>
x -> groupby(x, [:i,:year]) |>
x -> combine(x, :value=> sum) |>
x -> leftjoin(df, x, on = [:i,:year]) |>
x -> transform(x,
[:value,:value_sum] => ((v,vs) -> v./vs) => :value)
#return df
col_set_link = Dict(:yr => :year,
:r => :region_abbv,
:i => :i
)
WiNDC.fill_parameter!(GU, df, :sgf_shr, col_set_link, Dict())
return GU
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 3964 | #include("./data_defines.jl")
function load_raw_faf_data(file_path)
df = DataFrame(CSV.File(file_path,stringtype=String))
cols_to_keep = ["dms_origst","dms_destst","dms_mode","sctg2"]
push!(cols_to_keep,[ col for col in names(df) if occursin(r"^value_",col)]...)
df = df |>
x -> filter(:trade_type => y-> y==1, x) |>
x -> select(x, cols_to_keep) |>
x -> stack(x,
Not(["dms_origst","dms_destst","dms_mode","sctg2"]),
value_name = :value,
variable_name = :year
) |>
x -> transform(x,
:dms_origst => (y -> string.(y)) => :dms_origst,
:dms_destst => (y -> string.(y)) => :dms_destst,
:year => (y -> replace.(y,"value_" => "")) => :year
) |>
x -> groupby(x, [:dms_origst,:dms_destst,:sctg2,:year]) |>
x -> combine(x, :value=>sum=>:value)
return df
end
function load_faf_data!(GU,data_dir,info_dict)
current_file_path = joinpath(data_dir,info_dict["current"])
history_file_path = joinpath(data_dir,info_dict["history"])
df_cur = load_raw_faf_data(current_file_path)
df_hist = load_raw_faf_data(history_file_path)
#notations = []
#push!(notations,WiNDC.notation_link(orig,:dms_origst,:state_fips))
#push!(notations,WiNDC.notation_link(dest,:dms_destst,:state_fips))
#push!(notations,WiNDC.notation_link(sctg2,:sctg2,:sctg2))
#push!(notations,WiNDC.notation_link(years,:year,:faf_year))
notations = faf_notations()
df = vcat(df_cur,df_hist) |>
x -> apply_notations(x,notations) |>
x -> groupby(x,[:dms_dest,:dms_orig,:year,:i]) |>
x -> combine(x, :value => sum => :value)
single_region = df |>
x-> filter([:dms_orig,:dms_dest] => (a,b) -> a==b, x) |>
x-> select(x, [:dms_dest,:year,:i,:value]) |>
x-> rename(x, :dms_dest => :r, :value=>:local_supply)
multi_region = filter([:dms_orig,:dms_dest] => (a,b) -> a!=b, df)
#exports
single_region = multi_region |>
x -> groupby(x, [:dms_orig,:year,:i]) |>
x -> combine(x, :value => sum => :exports) |>
x -> outerjoin(single_region, x, on = [:r=>:dms_orig,:year,:i])
#Imports
single_region = multi_region |>
x -> groupby(x, [:dms_dest,:year,:i]) |>
x -> combine(x, :value => sum => :demand) |>
x -> outerjoin(single_region, x, on = [:r=>:dms_dest,:year,:i])
single_region = coalesce.(single_region,0)
function mean(x)
sum(x)/length(x)
end
Y = single_region |>
x -> groupby(x, [:r,:year]) |>
x -> combine(x,
:local_supply=> mean =>:local_supply,
:exports => mean => :exports,
:demand => mean => :demand
)
# Make a dataframe with all the goods not present in the FAF data
X = Symbol.(unique(single_region[!,:i])) |>
x -> [i for i∈GU[:i] if i∉ x] |>
x -> DataFrame([x],[:i])
#X = DataFrame([[i for i∈GU[:i] if i∉ Symbol.(unique(single_region[!,:i]))]],[:i])
single_region = vcat(single_region,crossjoin(X,Y));
single_region[!,:value] = single_region[!,:local_supply] ./ (single_region[!,:local_supply] .+ single_region[!,:demand])
single_region = single_region |>
x -> select(x,[:r,:year,:i,:value]) |>
x -> unstack(x,:i,:value) |>
x -> transform(x,
:uti => (y -> .9) => :uti
) |>
x -> stack(x,Not(:r,:year),variable_name = :i,value_name = :value)
@parameters(GU,begin
rpc, (:yr,:r,:i), (description = "Regional purchase coefficient",)
end)
col_set_link = Dict(:yr => :year,
:r => :r,
:i => :i
)
single_region[!,[:r,:i,:year]] = Symbol.(single_region[!,[:r,:i,:year]])
fill_parameter!(GU, single_region, :rpc, col_set_link, Dict())
return GU
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 8592 |
function initialize_sets(years = 1997:2021)
GU = GamsUniverse()
initialize_sets!(GU,years)
return GU
end
function initialize_sets!(GU, years = 1997:2021)
margins!(GU)
bea_value_added!(GU)
bea_final_demand!(GU)
bea_taxes_subsidies!(GU)
bea_goods_sectors!(GU)
alias(GU,:i,:j)
WiNDC_regions!(GU)
years!(GU, years)
return GU
end
function margins!(GU)
@set(GU,m,"Margins",begin
trn, "Transport"
trd, "Trade"
end)
GU
end
function bea_value_added!(GU)
@set(GU, va, "BEA Value added categories",begin
othtax, "Other taxes on production (T00OTOP)"
surplus, "Gross operating surplus (V003)"
compen, "Compensation of employees (V001)"
end)
GU
end
function bea_final_demand!(GU)
@set(GU, fd, "BEA Final demand categories",begin
fed_structures, "Federal nondefense: Gross investment in structures"
def_equipment, "Federal national defense: Gross investment in equipment"
changinv, "Change in private inventories"
def_structures, "Federal national defense: Gross investment in structures"
state_equipment, "State and local: Gross investment in equipment"
def_intelprop, "Federal national defense: Gross investment in intellectual"
nondefense, "Nondefense: Consumption expenditures"
fed_equipment, "Federal nondefense: Gross investment in equipment"
state_invest, "State and local: Gross investment in structures"
structures, "Nonresidential private fixed investment in structures"
defense, "National defense: Consumption expenditures"
residential, "Residential private fixed investment"
equipment, "Nonresidential private fixed investment in equipment"
state_intelprop, "State and local: Gross investment in intellectual"
intelprop, "Nonresidential private fixed investment in intellectual"
pce, "Personal consumption expenditures"
state_consume, "State and local government consumption expenditures"
fed_intelprop, "Federal nondefense: Gross investment in intellectual prop"
end)
GU
end
function bea_taxes_subsidies!(GU)
TS = GamsSet([
GamsElement(:taxes, "taxes"),
GamsElement(:subsidies, "subsidies")
], "BEA Taxes and subsidies categories")
add_set(GU,:ts, TS)
GU
end
function years!(GU, years)
year_set = GamsSet(GamsElement.(years),"Years in dataset")
add_set(GU, :yr, year_set)
end
function bea_goods_sectors!(GU)
add_set(GU, :i, GamsSet([
GamsElement(:ppd, "Paper products manufacturing (322)"),
GamsElement(:res, "Food services and drinking places (722)"),
GamsElement(:com, "Computer systems design and related services (5415)"),
GamsElement(:amb, "Ambulatory health care services (621)"),
GamsElement(:fbp, "Food and beverage and tobacco products manufacturing (311-312)"),
GamsElement(:rec, "Amusements, gambling, and recreation industries (713)"),
GamsElement(:con, "Construction (23)"),
GamsElement(:agr, "Farms (111-112)"),
GamsElement(:eec, "Electrical equipment, appliance, and components manufacturing (335)"),
GamsElement(:use, "Scrap, used and secondhand goods"),
GamsElement(:fnd, "Federal general government (nondefense) (GFGN)"),
GamsElement(:pub, "Publishing industries, except Internet (includes software) (511)"),
GamsElement(:hou, "Housing (HS)"),
GamsElement(:fbt, "Food and beverage stores (445)"),
GamsElement(:ins, "Insurance carriers and related activities (524)"),
GamsElement(:tex, "Textile mills and textile product mills (313-314)"),
GamsElement(:leg, "Legal services (5411)"),
GamsElement(:fen, "Federal government enterprises (GFE)"),
GamsElement(:uti, "Utilities (22)"),
GamsElement(:nmp, "Nonmetallic mineral products manufacturing (327)"),
GamsElement(:brd, "Broadcasting and telecommunications (515, 517)"),
GamsElement(:bnk, "Federal Reserve banks, credit intermediation, and related services (521-522)"),
GamsElement(:ore, "Other real estate (ORE)"),
GamsElement(:edu, "Educational services (61)"),
GamsElement(:ote, "Other transportation equipment manufacturing (3364-3366, 3369)"),
GamsElement(:man, "Management of companies and enterprises (55)"),
GamsElement(:mch, "Machinery manufacturing (333)"),
GamsElement(:dat, "Data processing, internet publishing, and other information services (518, 519)"),
GamsElement(:amd, "Accommodation (721)"),
GamsElement(:oil, "Oil and gas extraction (211)"),
GamsElement(:hos, "Hospitals (622)"),
GamsElement(:rnt, "Rental and leasing services and lessors of intangible assets (532-533)"),
GamsElement(:pla, "Plastics and rubber products manufacturing (326)"),
GamsElement(:fof, "Forestry, fishing, and related activities (113-115)"),
GamsElement(:fin, "Funds, trusts, and other financial vehicles (525)"),
GamsElement(:tsv, "Miscellaneous professional, scientific, and technical services (5412-5414, 5416-5419)"),
GamsElement(:nrs, "Nursing and residential care facilities (623)"),
GamsElement(:sec, "Securities, commodity contracts, and investments (523)"),
GamsElement(:art, "Performing arts, spectator sports, museums, and related activities (711-712)"),
GamsElement(:mov, "Motion picture and sound recording industries (512)"),
GamsElement(:fpd, "Furniture and related products manufacturing (337)"),
GamsElement(:slg, "State and local general government (GSLG)"),
GamsElement(:pri, "Printing and related support activities (323)"),
GamsElement(:grd, "Transit and ground passenger transportation (485)"),
GamsElement(:pip, "Pipeline transportation (486)"),
GamsElement(:sle, "State and local government enterprises (GSLE)"),
GamsElement(:osv, "Other services, except government (81)"),
GamsElement(:trn, "Rail transportation (482)"),
GamsElement(:smn, "Support activities for mining (213)"),
GamsElement(:fmt, "Fabricated metal products (332)"),
GamsElement(:pet, "Petroleum and coal products manufacturing (324)"),
GamsElement(:mvt, "Motor vehicle and parts dealers (441)"),
GamsElement(:cep, "Computer and electronic products manufacturing (334)"),
GamsElement(:wst, "Waste management and remediation services (562)"),
GamsElement(:mot, "Motor vehicles, bodies and trailers, and parts manufacturing (3361-3363)"),
GamsElement(:adm, "Administrative and support services (561)"),
GamsElement(:soc, "Social assistance (624)"),
GamsElement(:alt, "Apparel and leather and allied products manufacturing (315-316)"),
GamsElement(:pmt, "Primary metals manufacturing (331)"),
GamsElement(:trk, "Truck transportation (484)"),
GamsElement(:fdd, "Federal general government (defense) (GFGD)"),
GamsElement(:gmt, "General merchandise stores (452)"),
GamsElement(:wtt, "Water transportation (483)"),
GamsElement(:wpd, "Wood products manufacturing (321)"),
GamsElement(:wht, "Wholesale trade (42)"),
GamsElement(:oth, "Noncomparable imports and rest-of-the-world adjustment"),
GamsElement(:wrh, "Warehousing and storage (493)"),
GamsElement(:ott, "Other retail (4A0)"),
GamsElement(:che, "Chemical products manufacturing (325)"),
GamsElement(:air, "Air transportation (481)"),
GamsElement(:mmf, "Miscellaneous manufacturing (339)"),
GamsElement(:otr, "Other transportation and support activities (487-488, 492)"),
GamsElement(:min, "Mining, except oil and gas (212)"),],
"BEA Goods and sectors categories"
))
GU
end
function WiNDC_regions!(GU)
@set(GU, r,"States in the WiNDC database",begin
AL, "Alabama"
AK, "Alaska"
AZ, "Arizona"
AR, "Arkansas"
CA, "California"
CO, "Colorado"
CT, "Connecticut"
DE, "Delaware"
DC, "District of Columbia"
FL, "Florida"
GA, "Georgia"
HI, "Hawaii"
ID, "Idaho"
IL, "Illinois"
IN, "Indiana"
IA, "Iowa"
KS, "Kansas"
KY, "Kentucky"
LA, "Louisiana"
ME, "Maine"
MD, "Maryland"
MA, "Massachusetts"
MI, "Michigan"
MN, "Minnesota"
MS, "Mississippi"
MO, "Missouri"
MT, "Montana"
NE, "Nebraska"
NV, "Nevada"
NH, "New Hampshire"
NJ, "New Jersey"
NM, "New Mexico"
NY, "New York"
NC, "North Carolina"
ND, "North Dakota"
OH, "Ohio"
OK, "Oklahoma"
OR, "Oregon"
PA, "Pennsylvania"
RI, "Rhode Island"
SC, "South Carolina"
SD, "South Dakota"
TN, "Tennessee"
TX, "Texas"
UT, "Utah"
VT, "Vermont"
VA, "Virginia"
WA, "Washington"
WV, "West Virginia"
WI, "Wisconsin"
WY, "Wyoming"
end)
GU
end | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | code | 6027 | #include("./data_defines.jl")
function load_usa_trade!(GU,data_dir,info_dict)
df = load_raw_usa_trade(data_dir,info_dict)
usda = load_raw_usda_trade_shares(data_dir,info_dict)
function mean(x)
sum(x)/length(x)
end
# Fill out all missing years/values
regions = DataFrame([unique(df[!,:r])],[:r])
i = DataFrame([unique(df[!,:i])],[:i])
flows = DataFrame([unique(df[!,:flow])],[:flow])
years = DataFrame([unique(df[!,:year])],[:year])
X = crossjoin(regions,i,years,flows)
df = df |>
x -> outerjoin(x,X, on = [:r,:i,:year,:flow]) |>
x -> coalesce.(x,0) #|>
#x -> filter(:i => i->i∉[:oth,:use],x)
# Make year sums
Y = df |>
x -> groupby(x,[:i,:flow,:r]) |>
x -> combine(x, :value => sum => :yr_sum)
# Make year/region sums
X = df |>
x -> groupby(x, [:i,:flow]) |>
x -> combine(x, :value => sum => :yr_r_sum)
# Make value sums and add in year sums
df = df |>
x -> groupby(x, [:year,:flow,:i]) |>
x -> combine(x,
:value=> sum ,
) |>
x -> leftjoin(df,x, on = [:i,:flow,:year]) |>
x -> leftjoin(x, X, on = [:i,:flow]) |>
x -> leftjoin(x, Y, on = [:i,:flow,:r])
function f(value,value_sum,yr_sum,yr_r_sum)
if value_sum !=0
return value/value_sum
else
return yr_sum/yr_r_sum
end
end
usda = usda |>
x -> select(x, [:r,:year,:flow,:share])
df = df |>
x-> transform(x,
[:value,:value_sum,:yr_sum,:yr_r_sum] => ((v,vs,ys,yrs) -> f.(v,vs,ys,yrs))=>:value
) |>
x -> select(x, [:r,:i,:year,:flow,:value]) |>
x -> unstack(x, :i,:value) |>
x -> outerjoin(x,usda, on = [:r, :year,:flow]) |>
x -> transform(x,
[:flow,:agr,:share] => ((f,a,s) -> ifelse.(f.=="exports",s,a)) => :agr
) |>
x -> select(x,Not(:share)) |>
x ->stack(x, Not(:r,:year,:flow),variable_name=:i,value_name=:value) |>
x -> transform(x,
:flow => (y->Symbol.(y)) => :flow,
:i => (y->Symbol.(y)) => :i
) |>
x -> dropmissing(x)
col_set_link = Dict(
:yr => :year,
:r => :r,
:i => :i,
:flow => :flow,
)
@set(GU,flow,"Trade Flow",begin
imports, "Imports"
exports, "Exports"
end)
@parameters(GU,begin
usatrd_shr, (:yr, :r,:i,:flow), (description = "Share of total trade by region",)
end)
fill_parameter!(GU, df, :usatrd_shr, col_set_link, Dict())
# Relate years of data to available trade shares
ag_years = Symbol.(1997:2000)
years = Symbol.(1997:2001)
s = [e for e in GU[:i] if e!=:agr]
for year in years
GU[:usatrd_shr][[year],:r,s,[:exports]] = GU[:usatrd_shr][[Symbol(2002)],:r,s,[:exports]]
GU[:usatrd_shr][[year],:r,:i,[:imports]] = GU[:usatrd_shr][[Symbol(2002)],:r,:i,[:imports]]
end
for year in ag_years
GU[:usatrd_shr][[year],:r,[:agr],[:exports]] = GU[:usatrd_shr][[Symbol(2000)],:r,[:agr],[:exports]]
end
return GU
end
function load_raw_usa_trade(data_dir, info_dict)
out = DataFrame()
notations = usatrd_notations()
#notations = []
#push!(notations, WiNDC.notation_link(usatrd_states,:State,:region_fullname));
#push!(notations, WiNDC.notation_link(naics_map,:naics,:naics));
for flow in ["exports","imports"]
dict = info_dict[flow]
file_path = dict["path"]
col_rename = dict["col_rename"]
df = DataFrame(CSV.File(joinpath(data_dir,file_path),header=4,select=1:5,stringtype=String,silencewarnings=true)) |>
x -> rename(x, col_rename => "value") |>
x -> filter(:Time => y-> !occursin("through",y), x) |>
x -> filter(:Country => y-> y=="World Total", x) |>
x -> transform(x,
:value => (y -> parse.(Int,replace.(y,","=>""))/1_000_000) => :value,
:Time => (y -> parse.(Int,y)) => :year,
:Commodity => (y -> [String(e[1]) for e in split.(y)]) => :naics,
:value => (y -> flow) => :flow
) |>
x -> filter(:year => y->y<=2021, x) |>
x -> apply_notations(x, notations) |>
x -> groupby(x, [:i, :region_abbv,:year,:flow]) |>
x -> combine(x, :value => sum => :value) |>
x -> transform(x,
:region_abbv => (y->Symbol.(y)) => :r,
:year => (y-> Symbol.(y)) => :year,
) |>
x -> select(x, [:r,:i,:year,:flow,:value])
out = vcat(out,df)
end
return out
end
function load_raw_usda_trade_shares(data_dir,info_dict)
file_path = info_dict["detail"]
#notations = []
#push!(notations, WiNDC.notation_link(usatrd_states,:State,:region_fullname));
notations = usatrd_shares_notations()
X = XLSX.readdata(joinpath(data_dir,file_path),"Total exports","A3:W55")
X[1,1] = "State"
X = DataFrame(X[4:end,:], X[1,:]) |>
x -> apply_notations(x,notations) |>
x -> stack(x, Not(:region_abbv), variable_name = :year,value_name =:value) |>
x -> transform(x,
:year => (y -> parse.(Int,y)) => :year,
#:value => (y -> parse.(Float64,y)) => :value
)
X = X |>
x -> groupby(x, [:year]) |>
x -> combine(x, :value => sum => :value_sum) |>
x -> leftjoin(X,x, on = :year) |>
x -> transform(x,
[:value,:value_sum] => ((v,r) -> v./r) => :share,
:region_abbv => (a -> :agr) => :i,
:region_abbv => (a -> "exports") => :flow,
:region_abbv => (a -> Symbol.(a)) => :r,
:year => (a -> Symbol.(a)) => :year,
) |>
x -> select(x, [:r,:year,:i,:flow,:value,:value_sum,:share])
return X
end
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 111 | # WiNDC.jl
WiNDC Build Stream created in Julia
[Documentation here](https://uw-windc.github.io/WiNDC.jl/dev/)
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 1171 | # Introduction
Currently the entire Core module is implemented. This includes:
* Building the WiNDC database from raw-data
* The national model
* The state-level disaggregation.
# Example
This data is hosted on the [WiNDC website](https://windc.wisc.edu/downloads/version_4_0/windc_2021_julia.zip).
You must download and extract this data. The exact path will be used
when loading the data.
## State Level Disaggregation
Code to run the state-level disaggregation and model. Currently,
this is set up to run the the counter-factual calculation where
import tariffs are zero.
We are currently implementing a method to modify inputs and run
different shocks.
```
using WiNDC
using JuMP
using GamsStructure
using DataFrames
data_dir = "path/to/data"
GU = WiNDC.load_state_data(data_dir)
year = Symbol(2017)
m = state_disaggregation_model_mcp_year(GU,year)
# Fix an income level to normalize prices in the MCP model
fix(m[:RA][:CA],GU[:c0_][[year],[:CA]],force=true)
set_attribute(m, "cumulative_iteration_limit", 10_000)
optimize!(m)
```
## API Version
The API version is under development. It is being worked on and
will be available in early 2024.
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 404 | # National Disaggregation Model
```@docs
national_model_mcp_year(GU::GamsUniverse,year::Symbol;solver = PATHSolver.Optimizer)
national_model_mcp(GU::GamsUniverse;solver = PATHSolver.Optimizer)
```
To Do:
1. Create documentation explaining exactly what the model is doing
2. Currently this model is hard-coded to be the benchmark
verification. Need to make modifications to also run a
counterfactual.
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 10514 | # [National Dataset](@id core_national_dataset)
## Sets
|Set Name | Description |
|---|---|
|[yr](@ref core_national_years) | Years in dataset|
|[i,j](@ref core_national_sectors) | BEA Goods and sectors categories|
|[va](@ref core_national_va)| BEA Value added categories|
|[fd](@ref core_national_fd) | BEA Final demand categories|
|[ts](@ref core_national_ts) | BEA Taxes and subsidies categories|
|[m](@ref core_national_margins) | Margins|
## Parameters
|Parameter Name| Domain | Description |
|---|---|---|
|id0 |yr, i, j | Intermediate Demand|
|ys0 |yr, j, i | Intermediate Supply|
|fd0 |yr, i, fd | Final Demand|
|va0 |yr, va, j | Value Added|
|md0 |yr, m, i | Margin Demand|
|s0 |yr, j | Aggregate Supply|
|m0 |yr, i | Imports|
|trn0 |yr, i | Transportation Costs|
|tm0 |yr, i | Tax net subsidy rate on intermediate demand|
|ta0 |yr, i | Import Tariff|
|othtax |yr, j | Other taxes|
|y0 |yr, i | Gross Output|
|mrg0 |yr, i | Trade Margins|
|bopdef0 |yr | |
|x0 |yr, i | Exports|
|tax0 |yr, i | Taxes on Products|
|ms0 |yr, i, m | Margin Supply|
|duty0 |yr, i | Import Duties|
|fs0 |yr, i | Household Supply|
|ts0 |yr, ts, j | Taxes and Subsidies|
|cif0 |yr, i | |
|sbd0 |yr, i | Subsidies|
|a0 |yr, i | Armington Supply|
|ty0 |yr, j | Output tax rate|
# Set Listing
## [Years in WiNDC Database](@id core_national_years)
|yr| |yr|
|---|---|---|
|1997| |2010|
|1998| |2011|
|1999| |2011|
|2000| |2012|
|2001| |2013|
|2002| |2014|
|2003| |2015|
|2004| |2016|
|2005| |2017|
|2006| |2018|
|2007| |2019|
|2008| |2020|
|2009| |2021|
## [BEA Goods and sectors categories & Commodities employed in margin supply](@id core_national_sectors)
| i, j | Description |
|:------|:--------------------------------------------------------------------------------------|
| agr | Farms (111-112) |
| fof | Forestry, fishing, and related activities (113-115) |
| oil | Oil and gas extraction (211) |
| min | Mining, except oil and gas (212) |
| smn | Support activities for mining (213) |
| uti | Utilities (22) |
| con | Construction (23) |
| wpd | Wood products manufacturing (321) |
| nmp | Nonmetallic mineral products manufacturing (327) |
| pmt | Primary metals manufacturing (331) |
| fmt | Fabricated metal products (332) |
| mch | Machinery manufacturing (333) |
| cep | Computer and electronic products manufacturing (334) |
| eec | Electrical equipment, appliance, and components manufacturing (335) |
| mot | Motor vehicles, bodies and trailers, and parts manufacturing (3361-3363) |
| ote | Other transportation equipment manufacturing (3364-3366, 3369) |
| fpd | Furniture and related products manufacturing (337) |
| mmf | Miscellaneous manufacturing (339) |
| fbp | Food and beverage and tobacco products manufacturing (311-312) |
| tex | Textile mills and textile product mills (313-314) |
| alt | Apparel and leather and allied products manufacturing (315-316) |
| ppd | Paper products manufacturing (322) |
| pri | Printing and related support activities (323) |
| pet | Petroleum and coal products manufacturing (324) |
| che | Chemical products manufacturing (325) |
| pla | Plastics and rubber products manufacturing (326) |
| wht | Wholesale trade (42) |
| mvt | Motor vehicle and parts dealers (441) |
| fbt | Food and beverage stores (445) |
| gmt | General merchandise stores (452) |
| ott | Other retail (4A0) |
| air | Air transportation (481) |
| trn | Rail transportation (482) |
| wtt | Water transportation (483) |
| trk | Truck transportation (484) |
| grd | Transit and ground passenger transportation (485) |
| pip | Pipeline transportation (486) |
| otr | Other transportation and support activities (487-488, 492) |
| wrh | Warehousing and storage (493) |
| pub | Publishing industries, except Internet (includes software) (511) |
| mov | Motion picture and sound recording industries (512) |
| brd | Broadcasting and telecommunications (515, 517) |
| dat | Data processing, internet publishing, and other information services (518, 519) |
| bnk | Federal Reserve banks, credit intermediation, and related services (521-522) |
| sec | Securities, commodity contracts, and investments (523) |
| ins | Insurance carriers and related activities (524) |
| fin | Funds, trusts, and other financial vehicles (525) |
| hou | Housing (HS) |
| ore | Other real estate (ORE) |
| rnt | Rental and leasing services and lessors of intangible assets (532-533) |
| leg | Legal services (5411) |
| com | Computer systems design and related services (5415) |
| tsv | Miscellaneous professional, scientific, and technical services (5412-5414, 5416-5419) |
| man | Management of companies and enterprises (55) |
| adm | Administrative and support services (561) |
| wst | Waste management and remediation services (562) |
| edu | Educational services (61) |
| amb | Ambulatory health care services (621) |
| hos | Hospitals (622) |
| nrs | Nursing and residential care facilities (623) |
| soc | Social assistance (624) |
| art | Performing arts, spectator sports, museums, and related activities (711-712) |
| rec | Amusements, gambling, and recreation industries (713) |
| amd | Accommodation (721) |
| res | Food services and drinking places (722) |
| osv | Other services, except government (81) |
| fdd | Federal general government (defense) (GFGD) |
| fnd | Federal general government (nondefense) (GFGN) |
| fen | Federal government enterprises (GFE) |
| slg | State and local general government (GSLG) |
| sle | State and local government enterprises (GSLE) |
## [BEA Value added categories](@id core_national_va)
|va | Description|
|---|---|
|othtax | Other taxes on production (T00OTOP)|
|surplus | Gross operating surplus (V003)|
|compen | Compensation of employees (V001)|
## [BEA Final demand categories](@id core_national_fd)
|fd | Description|
|---|---|
|fed_structures | Federal nondefense: Gross investment in structures|
|def_equipment | Federal national defense: Gross investment in equipment|
|changinv | Change in private inventories|
|def_structures | Federal national defense: Gross investment in structures|
|state_equipment | State and local: Gross investment in equipment|
|def_intelprop | Federal national defense: Gross investment in intellectual|
|nondefense | Nondefense: Consumption expenditures|
|fed_equipment | Federal nondefense: Gross investment in equipment|
|state_invest | State and local: Gross investment in structures|
|structures | Nonresidential private fixed investment in structures|
|defense | National defense: Consumption expenditures|
|residential | Residential private fixed investment|
|equipment | Nonresidential private fixed investment in equipment|
|state_intelprop | State and local: Gross investment in intellectual|
|intelprop | Nonresidential private fixed investment in intellectual|
|pce | Personal consumption expenditures|
|state_consume | State and local government consumption expenditures|
|fed_intelprop | Federal nondefense: Gross investment in intellectual prop|
## [BEA Taxes and subsidies categories](@id core_national_ts)
|ts | Description|
|---|---|
|taxes | taxes|
|subsidies | subsidies|
## [Margins](@id core_national_margins)
|m | Description|
|---|---|
|trn | Transport|
|trd | Trade|
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 500 | # Core Module Overview
We provide methods to build two datasets, the `national` dataset
and `state level` dataset. The `national` dataset is based on the
BEA summary IO tables. The `state level` dataset uses the remaining
[data sources](@ref core_data_sources) to disaggregate the national
dataset to a the state-level.
## National Dataset
To Do: Discuss creation and assignment of the national dataset.
## State Level Dataset
To Do: Discuss creation and assignment of the State level dataset. | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 11032 | # [State Level Disaggregation](@id core_state_disaggregation)
## Sets
|Set Name|Description|
|---|---|
|[yr](@ref core_years)|Years in WiNDC Database|
|[r](@ref core_regions)|Regions in WiNDC Database|
|[s, g](@ref core_sectors) |BEA Goods and sectors categories|
|[m](@ref core_margins)|Margins (trade or transport)|
|[gm](@ref core_sectors)|Commodities employed in margin supply|
## Parameters
|Parameter Name|Domain|Description|
|---|---|---|
|ys0_|yr, r, s, g|Regional sectoral output|
|ld0_|yr, r, s|Labor demand|
|kd0_|yr, r, s|Capital demand|
|id0_|yr, r, g, s|Regional intermediate demand|
|ty0_|yr, r, s|Production tax rate|
|yh0_|yr, r, s|Household production|
|fe0_|yr, r|Total factor supply|
|cd0_|yr, r, s|Consumption demand|
|c0_|yr, r|Total final household consumption|
|i0_|yr, r, s|Investment demand|
|g0_|yr, r, s|Government demand|
|bopdef0_|yr, r|Balance of payments (closure parameter)|
|hhadj0_|yr, r|Household adjustment parameter|
|s0_|yr, r, g|Total supply|
|xd0_|yr, r, g|Regional supply to local market|
|xn0_|yr, r, g|Regional supply to national market|
|x0_|yr, r, g|Foreign Exports|
|rx0_|yr, r, g|Re-exports|
|a0_|yr, r, g|Domestic absorption|
|nd0_|yr, r, g|Regional demand from national marke|
|dd0_|yr, r, g|Regional demand from local market|
|m0_|yr, r, g|Foreign Imports|
|ta0_|yr, r, g|Absorption taxes|
|tm0_|yr, r, g|Import taxes|
|md0_|yr, r, m, g|Margin demand|
|nm0_|yr, r, g, m|Margin demand from the national market|
|dm0_|yr, r, g, m|Margin supply from the local market|
|gdp0_|yr, r|Aggregate GDP|
# Set Listing
## [Years in WiNDC Database](@id core_years)
|yr| |yr|
|---|---|---|
|1997| |2010|
|1998| |2011|
|1999| |2011|
|2000| |2012|
|2001| |2013|
|2002| |2014|
|2003| |2015|
|2004| |2016|
|2005| |2017|
|2006| |2018|
|2007| |2019|
|2008| |2020|
|2009| |2021|
## [Regions in WiNDC Database](@id core_regions)
|r |Description | |r |Description|
|---|--- |---|---|---|
|AK |Alaska | |MT |Montana|
|AL |Alabama | |NC |North Carolina|
|AR |Arkansas | |ND |North Dakota|
|AZ |Arizona | |NE |Nebraska|
|CA |California | |NH |New Hampshire|
|CO |Colorado | |NJ |New Jersey|
|CT |Connecticut | |NM |New Mexico|
|DC |District of Columbia| |NV |Nevada|
|DE |Delaware | |NY |New York|
|FL |Florida | |OH |Ohio|
|GA |Georgia | |OK |Oklahoma|
|HI |Hawaii | |OR |Oregon|
|IA |Iowa | |PA |Pennsylvania|
|ID |Idaho | |RI |Rhode Island|
|IL |Illinois | |SC |South Carolina|
|IN |Indiana | |SD |South Dakota|
|KS |Kansas | |TN |Tennessee|
|KY |Kentucky | |TX |Texas|
|LA |Louisiana | |UT |Utah|
|MA |Massachusetts | |VA |Virginia|
|MD |Maryland | |VT |Vermont|
|ME |Maine | |WA |Washington|
|MI |Michigan | |WI |Wisconsin|
|MN |Minnesota | |WV |West Virginia|
|MO |Missouri | |WY |Wyoming|
|MS |Mississippi | | ||
## [BEA Goods and sectors categories & Commodities employed in margin supply](@id core_sectors)
| s, g | gm | Description |
|:------|:-----:|:--------------------------------------------------------------------------------------|
| agr | agr | Farms (111-112) |
| fof | fof | Forestry, fishing, and related activities (113-115) |
| oil | oil | Oil and gas extraction (211) |
| min | min | Mining, except oil and gas (212) |
| smn | - | Support activities for mining (213) |
| uti | - | Utilities (22) |
| con | - | Construction (23) |
| wpd | wpd | Wood products manufacturing (321) |
| nmp | nmp | Nonmetallic mineral products manufacturing (327) |
| pmt | pmt | Primary metals manufacturing (331) |
| fmt | fmt | Fabricated metal products (332) |
| mch | mch | Machinery manufacturing (333) |
| cep | cep | Computer and electronic products manufacturing (334) |
| eec | eec | Electrical equipment, appliance, and components manufacturing (335) |
| mot | mot | Motor vehicles, bodies and trailers, and parts manufacturing (3361-3363) |
| ote | ote | Other transportation equipment manufacturing (3364-3366, 3369) |
| fpd | fpd | Furniture and related products manufacturing (337) |
| mmf | mmf | Miscellaneous manufacturing (339) |
| fbp | fbp | Food and beverage and tobacco products manufacturing (311-312) |
| tex | tex | Textile mills and textile product mills (313-314) |
| alt | alt | Apparel and leather and allied products manufacturing (315-316) |
| ppd | ppd | Paper products manufacturing (322) |
| pri | pri | Printing and related support activities (323) |
| pet | pet | Petroleum and coal products manufacturing (324) |
| che | che | Chemical products manufacturing (325) |
| pla | pla | Plastics and rubber products manufacturing (326) |
| wht | wht | Wholesale trade (42) |
| mvt | mvt | Motor vehicle and parts dealers (441) |
| fbt | fbt | Food and beverage stores (445) |
| gmt | gmt | General merchandise stores (452) |
| ott | ott | Other retail (4A0) |
| air | air | Air transportation (481) |
| trn | trn | Rail transportation (482) |
| wtt | wtt | Water transportation (483) |
| trk | trk | Truck transportation (484) |
| grd | - | Transit and ground passenger transportation (485) |
| pip | pip | Pipeline transportation (486) |
| otr | otr | Other transportation and support activities (487-488, 492) |
| wrh | - | Warehousing and storage (493) |
| pub | pub | Publishing industries, except Internet (includes software) (511) |
| mov | mov | Motion picture and sound recording industries (512) |
| brd | - | Broadcasting and telecommunications (515, 517) |
| dat | - | Data processing, internet publishing, and other information services (518, 519) |
| bnk | - | Federal Reserve banks, credit intermediation, and related services (521-522) |
| sec | - | Securities, commodity contracts, and investments (523) |
| ins | - | Insurance carriers and related activities (524) |
| fin | - | Funds, trusts, and other financial vehicles (525) |
| hou | - | Housing (HS) |
| ore | - | Other real estate (ORE) |
| rnt | - | Rental and leasing services and lessors of intangible assets (532-533) |
| leg | - | Legal services (5411) |
| com | - | Computer systems design and related services (5415) |
| tsv | - | Miscellaneous professional, scientific, and technical services (5412-5414, 5416-5419) |
| man | - | Management of companies and enterprises (55) |
| adm | - | Administrative and support services (561) |
| wst | - | Waste management and remediation services (562) |
| edu | - | Educational services (61) |
| amb | - | Ambulatory health care services (621) |
| hos | - | Hospitals (622) |
| nrs | - | Nursing and residential care facilities (623) |
| soc | - | Social assistance (624) |
| art | - | Performing arts, spectator sports, museums, and related activities (711-712) |
| rec | - | Amusements, gambling, and recreation industries (713) |
| amd | - | Accommodation (721) |
| res | - | Food services and drinking places (722) |
| osv | - | Other services, except government (81) |
| fdd | - | Federal general government (defense) (GFGD) |
| fnd | - | Federal general government (nondefense) (GFGN) |
| fen | - | Federal government enterprises (GFE) |
| slg | - | State and local general government (GSLG) |
| sle | - | State and local government enterprises (GSLE) |
## [Margins (trade or transport)](@id core_margins)
| m | Description |
|:------|:--------------|
| trn | transport |
| trd | trade |
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 365 | # State Disaggregation Model
```@docs
state_disaggregation_model_mcp_year(GU::GamsUniverse,year::Symbol)
state_disaggregation_model_mcp(GU::GamsUniverse)
```
To Do:
1. Create documentation explaining exactly what the model is doing
2. Currently this model is hard-coded to be the benchmark
verification. Need to make modifications to also run a
counterfactual.
| WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 1837 |
# [Core Data Sources](@id core_data_sources)
As of November 9, 2023, the BEA is restricting their data to be 2017 - Present.
This is due to the release of the detailed 2017 IO table. They are using the
detailed table to back-update the summary tables.
## Bureau of Economic Analysis - Summary Input/Output Tables
[Link](https://www.bea.gov/industry/input-output-accounts-data)
## Bureau of Economic Analysis - Gross Domestic Product by State
[Link](https://apps.bea.gov/regional/downloadzip.cfm)
In the `Gross Domestic Product (GDP)`, select the `SAGDP: annual GDP by state` option.
## Bureau of Economic Analysis -- Personal Consumer Expenditures
[Link](https://apps.bea.gov/regional/downloadzip.cfm)
In the `Personal consumption expenditures (PCE) by state`, select the
`SAPCE: personal consumption expenditures (PCE) by state` option.
## US Census Bureau - Annual Survey of State Government Finances
[Link](https://www.census.gov/programs-surveys/state/data/datasets.All.List_75006027.html)
Heavily encoded TXT files.
## Bureau of Transportation Statistics - Freight Analysis Framework
[Link](https://www.bts.gov/faf)
We use two data files, `FAF5.5.1_State.zip` and `FAF5.5.1_Reprocessed_1997-2012_State.zip`
Currently, we are using version 5.5.1.
## US Census Bureau - USA Trade Online
[Link](https://usatrade.census.gov/)
This requires a log-in. For both `Imports` and `Exports` we want NAICS data. When
selecting data, we want every state (this is different that All States), the most
disaggregated commodities (third level), and for `Exports` we want `World Total`
and `Imports` we want both `World Total` and `Canada` in the Countries column.
There is one more file we use, [Commodity\_detail\_by\_state\_cy.xlsx](https://www.ers.usda.gov/webdocs/DataFiles/100812/)
This is probably a fragile link. | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.1.1 | b6abfe114a70cd41a38c07f032ba381aee6ff104 | docs | 624 | # Data Module
We have assembled all of this data for [download](https://windc.wisc.edu/downloads/version_4_0/windc_2021_julia.zip)
to run locally. This information is provided if you are interested in updating
data early, without using the API.
When manually updating data, you may need to modify the file `data_information.json` with
updated paths to the files. A JSON file is raw text and can be modified in any text editor.
It should be straight forward to open the file and determine what needs updating.
# API Access
This is currently not available, but under active development. Expect updates in early 2024. | WiNDC | https://github.com/uw-windc/WiNDC.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 2209 | module LightBSON
using DataStructures
using Dates
using DecFP
using FNVHash
using Sockets
using StructTypes
using Transducers
using UnsafeArrays
using UUIDs
using WeakRefStrings
export BSONConversionError
export AbstractBSONReader, BSONReader, BSONWriter, BSONWriteBuffer
export BSONValidator, StrictBSONValidator, LightBSONValidator, UncheckedBSONValidator
export BSONConversionRules, DefaultBSONConversions, NumericBSONConversions
export BSONIndex, IndexedBSONReader
export BSONObjectId, BSONObjectIdGenerator
export BSONTimestamp
export BSONCode, BSONCodeWithScope, BSONSymbol
export BSONBinary, UnsafeBSONBinary
export BSONRegex, UnsafeBSONString
export BSONMinKey, BSONMaxKey
export BSONUndefined
export BSONUUIDOld
export BSONDBPointer
export BSON_TYPE_DOUBLE,
BSON_TYPE_STRING,
BSON_TYPE_DOCUMENT,
BSON_TYPE_ARRAY,
BSON_TYPE_BINARY,
BSON_TYPE_UNDEFINED,
BSON_TYPE_OBJECTID,
BSON_TYPE_BOOL,
BSON_TYPE_DATETIME,
BSON_TYPE_NULL,
BSON_TYPE_REGEX,
BSON_TYPE_DB_POINTER,
BSON_TYPE_CODE,
BSON_TYPE_SYMBOL,
BSON_TYPE_CODE_WITH_SCOPE,
BSON_TYPE_INT32,
BSON_TYPE_TIMESTAMP,
BSON_TYPE_INT64,
BSON_TYPE_DECIMAL128
export BSON_SUBTYPE_GENERIC_BINARY,
BSON_SUBTYPE_FUNCTION,
BSON_SUBTYPE_BINARY_OLD,
BSON_SUBTYPE_UUID_OLD,
BSON_SUBTYPE_UUID,
BSON_SUBTYPE_MD5,
BSON_SUBTYPE_ENCRYPTED
export bson_simple
export bson_read, bson_read_simple, bson_read_structtype, bson_read_unversioned, bson_read_versioned
export bson_write, bson_write_simple, bson_write_structtype
export bson_schema_version, bson_schema_version_field
export bson_object_id_range
bson_schema_version(::Type{T}) where T = nothing
bson_schema_version_field(::Type{T}) where T = "_v"
# bson_simple(::Type{T}) where T = StructTypes.StructType(T) == StructTypes.NoStructType()
# bson_simple(::Type{<:NamedTuple}) = true
bson_simple(::Type{T}) where T = true
include("object_id.jl")
include("types.jl")
include("representations.jl")
include("exceptions.jl")
include("validator.jl")
include("reader.jl")
include("index.jl")
include("indexed_reader.jl")
include("writer.jl")
include("write_buffer.jl")
include("convenience.jl")
include("fileio.jl")
end
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 1813 | """
bson_read([T=Any], src::Union{IO, DenseVector{UInt8}})
Read an object from the BSON document encoded in `src`.
"""
bson_read(::Type{T}, bytes::DenseVector{UInt8}; kwargs...) where T = BSONReader(bytes; kwargs...)[T]
"""
bson_read([T=Any], path::AbstractString)
Read an object from the BSON document at `path`.
"""
bson_read(::Type{T}, path::AbstractString; kwargs...) where T = bson_read(T, read(path); kwargs...)
function bson_read(::Type{T}, io::IO; kwargs...) where T
buf = UInt8[]
readbytes!(io, buf, typemax(Int))
bson_read(T, buf; kwargs...)
end
bson_read(bytes::DenseVector{UInt8}; kwargs...) = bson_read(Any, bytes; kwargs...)
bson_read(path::AbstractString; kwargs...) = bson_read(Any, path; kwargs...)
bson_read(io::IO; kwargs...) = bson_read(Any, io; kwargs...)
"""
bson_write(dst::Union{IO, DenseVector{UInt8}}, x)
bson_write(dst::Union{IO, DenseVector{UInt8}}, xs::Pair...)
Encode `x` or each element of `xs` as a BSON document in `dst` and return `dst`.
"""
function bson_write(buf::DenseVector{UInt8}, x; kwargs...)
writer = BSONWriter(buf; kwargs...)
writer[] = x
close(writer)
buf
end
function bson_write(buf::DenseVector{UInt8}, xs::Pair...; kwargs...)
writer = BSONWriter(buf; kwargs...)
for (k, v) in xs
writer[k] = v
end
close(writer)
buf
end
function bson_write(io::IO, x...; kwargs...)
buf = UInt8[]
bson_write(buf, x...; kwargs...)
write(io, buf)
io
end
"""
bson_write(path::AbstractString, x)
bson_write(path::AbstractString, xs::Pair...)
Encode `x` or each element of `xs` as fields of a BSON document and write to `path`.
"""
function bson_write(path::AbstractString, x...; kwargs...)
open(path, "w") do io
bson_write(io, x...; kwargs...)
end
nothing
end
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 295 | struct BSONConversionError <: Exception
src_type::UInt8
src_subtype::Union{Nothing, UInt8}
dst_type::DataType
end
BSONConversionError(src_type::UInt8, dst_type::DataType) = BSONConversionError(src_type, nothing, dst_type)
struct BSONValidationError <: Exception
msg::String
end | LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 541 | function fileio_save(f, x; kwargs...)
get(kwargs, :plain, false) || error("Pass plain = true to select LigthBSON.jl over BSON.jl")
bson_write(f.filename, x)
nothing
end
function fileio_load(f)
buf = read(f.filename)
reader = BSONReader(buf)
hastag = false
hastype = false
foreach(reader) do field
hastag |= field.first == "tag"
hastype |= field.first == "type"
nothing
end
hastag && hastype && error("BSON.jl document detected, aborting LightBSON.jl load")
reader[Any]
end | LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 2931 | struct BSONIndexKey
name_p::Ptr{UInt8}
name_len::Int32
parent_offset::Int32
end
@inline BSONIndexKey(name::AbstractString, parent_offset::Integer) = BSONIndexKey(
pointer(name),
sizeof(name) % Int32,
parent_offset % Int32
)
@inline BSONIndexKey(name::Symbol, parent_offset::Integer) = BSONIndexKey(
Base.unsafe_convert(Ptr{UInt8}, name),
ccall(:strlen, Csize_t, (Cstring,), Base.unsafe_convert(Ptr{UInt8}, name)) % Int32,
parent_offset % Int32
)
@inline function Base.isequal(x::BSONIndexKey, y::BSONIndexKey)
x.name_len == y.name_len &&
x.parent_offset == y.parent_offset &&
ccall(:memcmp, Cint, (Ptr{UInt8}, Ptr{UInt8}, Csize_t), x.name_p, y.name_p, x.name_len % Csize_t) == 0
end
struct BSONIndexValue
offset::Int32
type::UInt8
end
mutable struct BSONIndex
entries::Vector{Tuple{BSONIndexKey, Int32, BSONIndexValue}}
version::Int32
size_mask::Int32
include_arrays::Bool
function BSONIndex(size::Integer; include_arrays::Bool = false)
pow2size = nextpow(2, size)
new(
fill((BSONIndexKey(Ptr{UInt8}(0), 0, 0), 0, BSONIndexValue(0, 0)), pow2size),
0,
pow2size - 1,
include_arrays
)
end
end
function build_index_(index::BSONIndex, reader::BSONReader, ::Val{include_arrays}) where include_arrays
let parent_offset = reader.offset % Int32
f = @inline x -> begin
name = x.first
field_reader = x.second
key = BSONIndexKey(name.ptr, name.len % Int32, parent_offset)
value = BSONIndexValue(field_reader.offset % Int32, field_reader.type)
index[key] = value
if field_reader.type == BSON_TYPE_DOCUMENT || (include_arrays && field_reader.type == BSON_TYPE_ARRAY)
build_index_(index, field_reader, Val{include_arrays}())
end
nothing
end
foreach(f, Map(identity), reader)
end
nothing
end
@inline function index_(index::BSONIndex, key::BSONIndexKey)
nh = fnv1a(UInt32, key.name_p, key.name_len)
oh = reinterpret(UInt32, key.parent_offset) * 0x9e3779b1
h = nh ⊻ (oh + 0x9e3779b9 + (nh << 6) + (nh >> 2))
(h & index.size_mask) % Int + 1
end
@inline function Base.setindex!(index::BSONIndex, reader::BSONReader)
index.version += Int32(1)
if index.include_arrays
build_index_(index, reader, Val{true}())
else
build_index_(index, reader, Val{false}())
end
nothing
end
@inline function Base.setindex!(index::BSONIndex, value::BSONIndexValue, key::BSONIndexKey)
@inbounds index.entries[index_(index, key)] = (key, index.version, value)
nothing
end
@inline function Base.getindex(index::BSONIndex, key::BSONIndexKey)
@inbounds e_key, e_version, e_value = index.entries[index_(index, key)]
(e_version == index.version && isequal(e_key, key)) ? e_value : nothing
end
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 1662 | struct IndexedBSONReader{R <: BSONReader} <: AbstractBSONReader
index::BSONIndex
reader::R
@inline function IndexedBSONReader(index::BSONIndex, reader::R) where R
index[] = reader
new{R}(index, reader)
end
@inline function IndexedBSONReader(index::BSONIndex, reader::R, ::Val{:internal}) where R
new{R}(index, reader)
end
end
@inline Base.sizeof(reader::IndexedBSONReader) = sizeof(reader.reader)
@inline Base.foreach(f, reader::IndexedBSONReader) = foreach(f, reader.reader)
@inline function Base.getproperty(reader::IndexedBSONReader, f::Symbol)
f == :type && return reader.reader.type
f == :conversions && return reader.reader.conversions
getfield(reader, f)
end
@inline function Base.getindex(reader::IndexedBSONReader, name::Union{AbstractString, Symbol})
src = reader.reader.src
GC.@preserve src name begin
key = BSONIndexKey(name, reader.reader.offset)
value = reader.index[key]
field_reader = if value !== nothing
BSONReader(src, Int(value.offset), value.type, reader.reader.validator, reader.reader.conversions)
else
reader.reader[name]
end
IndexedBSONReader(reader.index, field_reader, Val{:internal}())
end
end
function Base.getindex(reader::IndexedBSONReader, i::Integer)
el = getindex(reader.reader, i)
IndexedBSONReader(reader.index, el, Val{:internal}())
end
@inline Transducers.__foldl__(rf, val, reader::IndexedBSONReader) = Transducers.__foldl__(rf, val, reader.reader)
@inline read_field_(reader::IndexedBSONReader, ::Type{T}) where T <: ValueField = read_field_(reader.reader, T)
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 3260 | struct BSONObjectId
data::NTuple{12, UInt8}
end
Base.isless(x::BSONObjectId, y::BSONObjectId) = x.data < y.data
function BSONObjectId(x::AbstractVector{UInt8})
length(x) == 12 || throw(ArgumentError("ObjectId bytes must be 12 long"))
BSONObjectId(NTuple{12, UInt8}(x))
end
function BSONObjectId(s::AbstractString)
length(s) == 24 || throw(ArgumentError("ObjectId hex string must be 24 characters"))
BSONObjectId(hex2bytes(s))
end
function Base.show(io::IO, x::BSONObjectId)
print(io, bytes2hex(collect(x.data)))
nothing
end
time_part_(x::BSONObjectId) = (Int(x.data[1]) << 24) | (Int(x.data[2]) << 16) | (Int(x.data[3]) << 8) | Int(x.data[4])
Dates.DateTime(x::BSONObjectId) = DateTime(Dates.UTM(Dates.UNIXEPOCH + time_part_(x) * 1000))
Base.time(x::BSONObjectId) = Float64(time_part_(x))
mutable struct BSONObjectIdGenerator
cache_pad1::NTuple{4, UInt128}
seq::Threads.Atomic{UInt32}
rnd::NTuple{5, UInt8}
cache_pad2::NTuple{4, UInt128}
function BSONObjectIdGenerator()
seq = Threads.Atomic{UInt32}(rand(UInt32))
rnd = rand(UInt64)
new(
(UInt128(0), UInt128(0), UInt128(0), UInt128(0)),
seq,
(
(rnd >> 32) % UInt8,
(rnd >> 24) % UInt8,
(rnd >> 16) % UInt8,
(rnd >> 8) % UInt8,
rnd % UInt8,
),
(UInt128(0), UInt128(0), UInt128(0), UInt128(0)),
)
end
end
function Base.show(io::IO, x::BSONObjectIdGenerator)
print(io, "BSONObjectIdGenerator($(x.seq), $(x.rnd))")
end
if Sys.islinux()
struct LinuxTimespec
seconds::Clong
nanoseconds::Cuint
end
@inline function seconds_from_epoch_()
ts = Ref{LinuxTimespec}()
ccall(:clock_gettime, Cint, (Cint, Ref{LinuxTimespec}), 0, ts)
x = ts[]
x.seconds % UInt32
end
else
@inline function seconds_from_epoch_()
tv = Libc.TimeVal()
tv.sec % UInt32
end
end
@inline id_from_parts_(t, r, s) = BSONObjectId((
(t >> 24) % UInt8,
(t >> 16) % UInt8,
(t >> 8) % UInt8,
t % UInt8,
r[1],
r[2],
r[3],
r[4],
r[5],
(s >> 16) % UInt8,
(s >> 8) % UInt8,
s % UInt8,
))
@inline Base.getindex(x::BSONObjectIdGenerator) = id_from_parts_(
seconds_from_epoch_(),
x.rnd,
Threads.atomic_add!(x.seq, UInt32(1))
)
struct BSONObjectIdIterator
t::UInt32
r::NTuple{5, UInt8}
first::UInt32
past_last::UInt32
end
Base.eltype(::BSONObjectIdIterator) = BSONObjectId
@inline Base.length(x::BSONObjectIdIterator) = (x.past_last - x.first) % Int
@inline function Base.iterate(x::BSONObjectIdIterator, cur::UInt32 = x.first)
if cur == x.past_last
nothing
else
id_from_parts_(x.t, x.r, cur), cur + UInt32(1)
end
end
@inline function Base.getindex(x::BSONObjectIdGenerator, range)
n = length(range) % UInt32
first = Threads.atomic_add!(x.seq, n)
BSONObjectIdIterator(seconds_from_epoch_(), x.rnd, first, first + n)
end
const default_object_id_generator = BSONObjectIdGenerator()
@inline BSONObjectId() = default_object_id_generator[]
@inline bson_object_id_range(n::Integer) = default_object_id_generator[1:n]
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 18971 | abstract type AbstractBSONReader end
struct BSONReader{S <: DenseVector{UInt8}, V <: BSONValidator, C <: BSONConversionRules} <: AbstractBSONReader
src::S
offset::Int
type::UInt8
validator::V
conversions::C
end
@inline function BSONReader(
src::DenseVector{UInt8};
validator::BSONValidator = LightBSONValidator(),
conversions::BSONConversionRules = DefaultBSONConversions(),
)
validate_root(validator, src)
BSONReader(src, 0, BSON_TYPE_DOCUMENT, validator, conversions)
end
# For back compat
@inline BSONReader(
src::DenseVector{UInt8},
validator::BSONValidator,
conversions::BSONConversionRules
) = BSONReader(src; validator, conversions)
# For back compat
@inline BSONReader(src::DenseVector{UInt8}, validator::BSONValidator) = BSONReader(
src; validator
)
# For back compat
@inline BSONReader(src::DenseVector{UInt8}, conversions::BSONConversionRules) = BSONReader(
src; conversions
)
@inline Base.pointer(reader::BSONReader) = pointer(reader.src) + reader.offset
const TYPE_SIZE_TABLE = fill(-1, 256)
TYPE_SIZE_TABLE[BSON_TYPE_DOUBLE] = 8
TYPE_SIZE_TABLE[BSON_TYPE_DATETIME] = 8
TYPE_SIZE_TABLE[BSON_TYPE_INT64] = 8
TYPE_SIZE_TABLE[BSON_TYPE_TIMESTAMP] = 8
TYPE_SIZE_TABLE[BSON_TYPE_INT32] = 4
TYPE_SIZE_TABLE[BSON_TYPE_BOOL] = 1
TYPE_SIZE_TABLE[BSON_TYPE_NULL] = 0
TYPE_SIZE_TABLE[BSON_TYPE_UNDEFINED] = 0
TYPE_SIZE_TABLE[BSON_TYPE_DECIMAL128] = 16
TYPE_SIZE_TABLE[BSON_TYPE_OBJECTID] = 12
TYPE_SIZE_TABLE[BSON_TYPE_MIN_KEY] = 0
TYPE_SIZE_TABLE[BSON_TYPE_MAX_KEY] = 0
function element_size_variable_(t::UInt8, p::Ptr{UInt8})
if t == BSON_TYPE_DOCUMENT || t == BSON_TYPE_ARRAY || t == BSON_TYPE_CODE_WITH_SCOPE
Int(ltoh(unsafe_load(Ptr{Int32}(p))))
elseif t == BSON_TYPE_STRING || t == BSON_TYPE_CODE || t == BSON_TYPE_SYMBOL
Int(ltoh(unsafe_load(Ptr{Int32}(p)))) + 4
elseif t == BSON_TYPE_BINARY
Int(ltoh(unsafe_load(Ptr{Int32}(p)))) + 5
elseif t == BSON_TYPE_REGEX
len1 = unsafe_trunc(Int, ccall(:strlen, Csize_t, (Cstring,), p)) + 1
len2 = unsafe_trunc(Int, ccall(:strlen, Csize_t, (Cstring,), p + len1)) + 1
len1 + len2
elseif t == BSON_TYPE_DB_POINTER
Int(ltoh(unsafe_load(Ptr{Int32}(p)))) + 16
else
error("Unsupported BSON type $t")
end
end
@inline function element_size_(t::UInt8, p::Ptr{UInt8})
@inbounds s = TYPE_SIZE_TABLE[t]
s >= 0 ? s : element_size_variable_(t, p)
end
Base.sizeof(reader::BSONReader) = GC.@preserve reader element_size_(reader.type, pointer(reader))
"""
name_len_and_match_(field, target)
Compare field name and target name, and calculate length of field name (including null terminator)
Returns (length(field)), field == target)
Performs byte wise comparison, optimized for short length field names
"""
@inline function name_len_and_match_(field::Ptr{UInt8}, target::Ptr{UInt8})
len = 1
cmp_acc = 0x0
while true
c = unsafe_load(field, len)
c2 = unsafe_load(target, len)
cmp_acc |= xor(c, c2)
c == 0x0 && return (len, cmp_acc == 0)
len += 1
c2 == 0x0 && break
end
while true
c = unsafe_load(field, len)
c == 0x0 && break
len += 1
end
(len, false)
end
@inline function name_len_(field::Ptr{UInt8})
len = 1
while true
unsafe_load(field, len) == 0x0 && break
len += 1
end
len
end
@inline function Transducers.__foldl__(rf, val, reader::BSONReader)
reader.type == BSON_TYPE_DOCUMENT || reader.type == BSON_TYPE_ARRAY || throw(
ArgumentError("Field access only available on documents and arrays")
)
src = reader.src
GC.@preserve src begin
p = pointer(reader.src)
offset = reader.offset
doc_len = Int(ltoh(unsafe_load(Ptr{Int32}(p + offset))))
doc_end = offset + doc_len - 1
offset += 4
while offset < doc_end
el_type = unsafe_load(p, offset + 1)
name_p = p + offset + 1
name_len = name_len_(name_p)
field_p = name_p + name_len
value_len = element_size_(el_type, field_p)
field_start = offset + 1 + name_len
field_end = field_start + value_len
validate_field(reader.validator, el_type, field_p, value_len, doc_end - field_start)
field_reader = BSONReader(src, field_start, el_type, reader.validator, reader.conversions)
val = Transducers.@next(rf, val, UnsafeBSONString(name_p, name_len - 1) => field_reader)
offset = field_end
end
Transducers.complete(rf, val)
end
end
@inline function Base.foreach(f, reader::BSONReader)
foreach(f, Map(identity), reader)
end
@noinline Base.@constprop :none function find_field_(reader::BSONReader, target::String)
reader.type == BSON_TYPE_DOCUMENT || reader.type == BSON_TYPE_ARRAY || throw(
ArgumentError("Field access only available on documents and arrays")
)
src = reader.src
GC.@preserve src target begin
target_p = Base.unsafe_convert(Ptr{UInt8}, target)
p = pointer(reader.src)
offset = reader.offset
doc_len = Int(ltoh(unsafe_load(Ptr{Int32}(p + offset))))
doc_end = offset + doc_len - 1
offset += 4
while offset < doc_end
el_type = unsafe_load(p, offset + 1)
name_p = p + offset + 1
name_len, name_match = name_len_and_match_(name_p, target_p)
field_p = name_p + name_len
value_len = element_size_(el_type, field_p)
field_start = offset + 1 + name_len
field_end = field_start + value_len
validate_field(reader.validator, el_type, field_p, value_len, doc_end - field_start)
name_match && return BSONReader(reader.src, field_start, el_type, reader.validator, reader.conversions)
offset = field_end
end
end
BSONReader(reader.src, 0, BSON_TYPE_NULL, reader.validator, reader.conversions)
end
# @noinline Base.@constprop :none function Base.getindex(reader::BSONReader, target::Union{AbstractString, Symbol})
Base.getindex(reader::BSONReader, target::String) = find_field_(reader, target)
function Base.getindex(reader::BSONReader, i::Integer)
i < 1 && throw(BoundsError(reader, i))
el = foldl((_, x) -> reduced(x.second), Drop(i - 1), reader; init = nothing)
el === nothing && throw(BoundsError(reader, i))
el
end
@inline load_bits_(::Type{T}, p::Ptr{UInt8}) where T = ltoh(unsafe_load(Ptr{T}(p)))
@inline load_bits_(::Type{BSONTimestamp}, p::Ptr{UInt8}) = BSONTimestamp(load_bits_(UInt64, p))
@inline load_bits_(::Type{BSONObjectId}, p::Ptr{UInt8}) = unsafe_load(Ptr{BSONObjectId}(p))
@inline load_bits_(::Type{DateTime}, p::Ptr{UInt8}) = DateTime(
Dates.UTM(Dates.UNIXEPOCH + load_bits_(Int64, p))
)
@inline function read_field_(reader::BSONReader, ::Type{T}) where T <: Union{
Int64,
Int32,
Float64,
Dec128,
DateTime,
BSONTimestamp,
BSONObjectId
}
reader.type == bson_type_(T) || throw(BSONConversionError(reader.type, T))
GC.@preserve reader load_bits_(T, pointer(reader))
end
@inline function read_field_(reader::BSONReader, ::Type{Bool})
reader.type == BSON_TYPE_BOOL || throw(BSONConversionError(reader.type, Bool))
x = GC.@preserve reader unsafe_load(pointer(reader))
validate_bool(reader.validator, x)
x != 0x0
end
@inline function read_binary_(reader::BSONReader)
GC.@preserve reader begin
p = pointer(reader)
len = load_bits_(Int32, p)
subtype = unsafe_load(p + 4)
validate_binary_subtype(reader.validator, p, len, subtype)
UnsafeBSONBinary(
UnsafeArray(p + 5, (Int(len),)),
subtype
)
end
end
@inline function read_field_(reader::BSONReader, ::Type{UnsafeBSONBinary})
reader.type == BSON_TYPE_BINARY || throw(BSONConversionError(reader.type, UnsafeBSONBinary))
read_binary_(reader)
end
function read_field_(reader::BSONReader, ::Type{BSONBinary})
reader.type == BSON_TYPE_BINARY || throw(BSONConversionError(reader.type, BSONBinary))
x = read_binary_(reader)
GC.@preserve reader BSONBinary(copy(x.data), x.subtype)
end
@inline function read_field_(reader::BSONReader, ::Type{UUID})
reader.type == BSON_TYPE_BINARY || throw(BSONConversionError(reader.type, UUID))
GC.@preserve reader begin
p = pointer(reader)
subtype = unsafe_load(p + 4)
subtype == BSON_SUBTYPE_UUID || subtype == BSON_SUBTYPE_UUID_OLD || throw(
BSONConversionError(reader.type, subtype, UUID)
)
len = load_bits_(Int32, p)
len != 16 && error("Unexpected UUID length $len")
return unsafe_load(Ptr{UUID}(p + 5))
end
end
@inline function read_field_(reader::BSONReader, ::Type{BSONUUIDOld})
reader.type == BSON_TYPE_BINARY || throw(BSONConversionError(reader.type, BSONUUIDOld))
GC.@preserve reader begin
p = pointer(reader)
subtype = unsafe_load(p + 4)
subtype == BSON_SUBTYPE_UUID_OLD || throw(BSONConversionError(reader.type, subtype, BSONUUIDOld))
len = load_bits_(Int32, p)
len != 16 && error("Unexpected UUID length $len")
return BSONUUIDOld(unsafe_load(Ptr{UUID}(p + 5)))
end
end
@inline function read_string_(reader::BSONReader)
GC.@preserve reader begin
p = pointer(reader)
len = Int(load_bits_(Int32, p))
validate_string(reader.validator, p + 4, len - 1)
UnsafeBSONString(p + 4, len - 1)
end
end
@inline function read_field_(reader::BSONReader, ::Type{UnsafeBSONString})
reader.type == BSON_TYPE_STRING || reader.type == BSON_TYPE_CODE || reader.type == BSON_TYPE_SYMBOL || throw(
BSONConversionError(reader.type, UnsafeBSONString)
)
read_string_(reader)
end
function read_field_(reader::BSONReader, ::Type{String})
reader.type == BSON_TYPE_STRING || reader.type == BSON_TYPE_CODE || reader.type == BSON_TYPE_SYMBOL || throw(
BSONConversionError(reader.type, String)
)
GC.@preserve reader String(read_string_(reader))
end
function read_field_(reader::BSONReader, ::Type{BSONCode})
reader.type == BSON_TYPE_CODE || throw(BSONConversionError(reader.type, BSONCode))
GC.@preserve reader begin
p = pointer(reader)
len = Int(load_bits_(Int32, p))
validate_string(reader.validator, p + 4, len - 1)
BSONCode(unsafe_string(p + 4, len - 1))
end
end
function read_field_(reader::BSONReader, ::Type{BSONSymbol})
reader.type == BSON_TYPE_SYMBOL || throw(BSONConversionError(reader.type, BSONSymbol))
BSONSymbol(reader[String])
end
function read_field_(reader::BSONReader, ::Type{BSONRegex})
reader.type == BSON_TYPE_REGEX || throw(BSONConversionError(reader.type, BSONRegex))
GC.@preserve reader begin
p = pointer(reader)
len1 = unsafe_trunc(Int, ccall(:strlen, Csize_t, (Cstring,), p))
BSONRegex(
unsafe_string(p, len1),
unsafe_string(p + len1 + 1)
)
end
end
function read_field_(reader::BSONReader, ::Type{BSONDBPointer})
reader.type == BSON_TYPE_DB_POINTER || throw(BSONConversionError(reader.type, BSONDBPointer))
GC.@preserve reader begin
p = pointer(reader)
len = Int(load_bits_(Int32, p))
validate_string(reader.validator, p + 4, len - 1)
collection = unsafe_string(p + 4, len - 1)
ref = unsafe_load(Ptr{BSONObjectId}(p + 4 + len))
BSONDBPointer(collection, ref)
end
end
@inline function read_field_(reader::BSONReader, ::Type{BSONMinKey})
reader.type == BSON_TYPE_MIN_KEY || throw(BSONConversionError(reader.type, BSONMinKey))
BSONMinKey()
end
@inline function read_field_(reader::BSONReader, ::Type{BSONMaxKey})
reader.type == BSON_TYPE_MAX_KEY || throw(BSONConversionError(reader.type, BSONMaxKey))
BSONMaxKey()
end
@inline function read_field_(reader::BSONReader, ::Type{BSONUndefined})
reader.type == BSON_TYPE_UNDEFINED || throw(BSONConversionError(reader.type, BSONUndefined))
BSONUndefined()
end
@inline function read_field_(reader::BSONReader, ::Type{Nothing})
reader.type == BSON_TYPE_NULL || throw(BSONConversionError(reader.type, Nothing))
nothing
end
function read_field_(reader::AbstractBSONReader, ::Type{Number})
t = reader.type
if t == BSON_TYPE_DOUBLE
reader[Float64]
elseif t == BSON_TYPE_INT64
reader[Int64]
elseif t == BSON_TYPE_INT32
reader[Int32]
elseif t == BSON_TYPE_DECIMAL128
reader[Dec128]
else
throw(BSONConversionError(t, Number))
end
end
function read_field_(reader::AbstractBSONReader, ::Type{Integer})
t = reader.type
if t == BSON_TYPE_INT64
reader[Int64]
elseif t == BSON_TYPE_INT32
reader[Int32]
else
throw(BSONConversionError(t, Number))
end
end
function read_field_(reader::AbstractBSONReader, ::Type{AbstractFloat})
t = reader.type
if t == BSON_TYPE_DOUBLE
reader[Float64]
elseif t == BSON_TYPE_DECIMAL128
reader[Dec128]
else
throw(BSONConversionError(t, Number))
end
end
@inline function read_field_(reader::AbstractBSONReader, ::Type{Union{Nothing, T}}) where T
reader.type == BSON_TYPE_NULL ? nothing : reader[T]
end
function read_field_(reader::BSONReader, ::Type{BSONCodeWithScope})
reader.type == BSON_TYPE_CODE_WITH_SCOPE || throw(BSONConversionError(reader.type, BSONCodeWithScope))
src = reader.src
GC.@preserve src begin
offset = reader.offset
p = pointer(reader.src) + offset
code_len = Int(load_bits_(Int32, p + 4))
doc_offset = offset + code_len + 8
validate_field(reader.validator, BSON_TYPE_CODE, p + 8, code_len, Int(load_bits_(Int32, p)) - 11)
validate_string(reader.validator, p + 8, code_len - 1)
BSONCodeWithScope(
unsafe_string(p + 8, code_len - 1),
BSONReader(src, doc_offset, BSON_TYPE_DOCUMENT, reader.validator, reader.conversions)[Dict{String, Any}]
)
end
end
function read_field_(reader::AbstractBSONReader, ::Type{T}) where {X, T <: AbstractDict{String, X}}
foldxl(reader; init = T()) do state, x
state[String(x.first)] = x.second[X]
state
end
end
function read_field_(reader::AbstractBSONReader, ::Type{T}) where {X, T <: AbstractDict{Symbol, X}}
foldxl(reader; init = T()) do state, x
state[Symbol(x.first)] = x.second[X]
state
end
end
function read_field_(reader::AbstractBSONReader, ::Type{Vector{T}}) where T
dst = T[]
copy!(dst, reader)
end
function read_field_(reader::T, ::Type{<:Union{T, AbstractBSONReader}}) where {T <: AbstractBSONReader}
reader
end
function Base.copy!(dst::AbstractArray{T}, reader::AbstractBSONReader) where T
copy!(Map(x -> x.second[T]), dst, reader)
end
function read_field_(reader::AbstractBSONReader, ::Type{Any})
if reader.type == BSON_TYPE_DOUBLE
reader[Float64]
elseif reader.type == BSON_TYPE_STRING
reader[String]
elseif reader.type == BSON_TYPE_DOCUMENT
reader[LittleDict{String, Any}]
elseif reader.type == BSON_TYPE_ARRAY
reader[Vector{Any}]
elseif reader.type == BSON_TYPE_BINARY
x = reader[BSONBinary]
data = x.data
if x.subtype == BSON_SUBTYPE_UUID && length(data) == 16
GC.@preserve data unsafe_load(Ptr{UUID}(pointer(data)))
elseif x.subtype == BSON_SUBTYPE_UUID_OLD && length(data) == 16
GC.@preserve data BSONUUIDOld(unsafe_load(Ptr{UUID}(pointer(data))))
else
x
end
elseif reader.type == BSON_TYPE_OBJECTID
reader[BSONObjectId]
elseif reader.type == BSON_TYPE_BOOL
reader[Bool]
elseif reader.type == BSON_TYPE_DATETIME
reader[DateTime]
elseif reader.type == BSON_TYPE_NULL
nothing
elseif reader.type == BSON_TYPE_REGEX
reader[BSONRegex]
elseif reader.type == BSON_TYPE_CODE
reader[BSONCode]
elseif reader.type == BSON_TYPE_SYMBOL
reader[BSONSymbol]
elseif reader.type == BSON_TYPE_INT32
reader[Int32]
elseif reader.type == BSON_TYPE_TIMESTAMP
reader[BSONTimestamp]
elseif reader.type == BSON_TYPE_INT64
reader[Int64]
elseif reader.type == BSON_TYPE_DECIMAL128
reader[Dec128]
elseif reader.type == BSON_TYPE_MIN_KEY
reader[BSONMinKey]
elseif reader.type == BSON_TYPE_MAX_KEY
reader[BSONMaxKey]
elseif reader.type == BSON_TYPE_UNDEFINED
reader[BSONUndefined]
elseif reader.type == BSON_TYPE_CODE_WITH_SCOPE
reader[BSONCodeWithScope]
elseif reader.type == BSON_TYPE_DB_POINTER
reader[BSONDBPointer]
else
error("Unsupported BSON type $(reader.type)")
end
end
@inline @generated function bson_read_simple(::Type{T}, reader::AbstractBSONReader) where T
field_readers = map(zip(fieldnames(T), fieldtypes(T))) do (fn, ft)
fns = string(fn)
:(reader[$fns][$ft])
end
:($T($(field_readers...)))
end
@inline function bson_read_structtype(::Type{T}, reader::AbstractBSONReader) where T
StructTypes.construct((i, name, FT) -> reader[name][FT], T)
end
@inline function bson_read_unversioned(::Type{T}, reader::AbstractBSONReader) where T
if bson_simple(T)
bson_read_simple(T, reader)
else
bson_read_structtype(T, reader)
end
end
@inline function bson_read_versioned(::Type{T}, v::V, reader::AbstractBSONReader) where {T, V}
target = bson_schema_version(T)
v != target && error("Mismatched schema version, read: $v, target: $target")
bson_read_unversioned(T, reader)
end
@inline function bson_read(::Type{T}, reader::AbstractBSONReader) where T
target_v = bson_schema_version(T)
if target_v !== nothing
v = reader[bson_schema_version_field(T)][typeof(target_v)]
bson_read_versioned(T, v, reader)
else
bson_read_unversioned(T, reader)
end
end
@inline function read_field_(reader::AbstractBSONReader, ::Type{T}) where T
# If T is a struct or not concrete (abstract or union), assume it has an implementation to read as object
if isstructtype(T) || !isconcretetype(T)
bson_read(T, reader)
else
throw(ArgumentError("Unsupported type $T"))
end
end
@inline function Base.getindex(reader::AbstractBSONReader, ::Type{T}) where T
RT = bson_representation_type(reader.conversions, T)
if RT != T
bson_representation_convert(reader.conversions, T, read_field_(reader, RT))
else
read_field_(reader, T)
end
end
@inline @generated function Base.getindex(reader::AbstractBSONReader, ::Type{T}) where T <: NamedTuple
field_readers = map(zip(fieldnames(T), fieldtypes(T))) do (fn, ft)
fns = string(fn)
:(reader[$fns][$ft])
end
:($T(($(field_readers...),)))
end
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 4525 | abstract type BSONConversionRules end
struct DefaultBSONConversions <: BSONConversionRules end
@inline bson_representation_type(::DefaultBSONConversions, ::Type{T}) where T = bson_representation_type(T)
@inline bson_representation_convert(::DefaultBSONConversions, ::Type{T}, x) where T = bson_representation_convert(T, x)
@inline bson_representation_type(::Type{T}) where T = T
@inline bson_representation_type(::Type{Symbol}) = String
@inline bson_representation_type(::Type{<:Enum}) = String
@inline bson_representation_type(::Type{<:Tuple}) = Vector{Any}
@inline bson_representation_convert(::Type{Vector{Any}}, x::Tuple) = collect(x)
@inline bson_representation_convert(::Type{T}, x::Vector{Any}) where T <: Tuple = T(x)
@inline bson_representation_convert(::Type{T}, x) where T = StructTypes.construct(T, x)
@inline bson_representation_convert(::Type{String}, x) = string(x)
@inline bson_representation_type(::Type{Vector{UInt8}}) = BSONBinary
@inline bson_representation_convert(::Type{Vector{UInt8}}, x::BSONBinary) = x.data
@inline bson_representation_convert(::Type{BSONBinary}, x::Vector{UInt8}) = BSONBinary(x)
# NOTE: no public API for this, hopefully this doesn't break too often
function regex_opts_str_(x::Regex)
o1 = Base.regex_opts_str(x.compile_options & ~Base.DEFAULT_COMPILER_OPTS)
o2 = Base.regex_opts_str(x.match_options & ~Base.DEFAULT_MATCH_OPTS)
o1 * o2
end
# Alternative implementation should the former start breaking
# function regex_opts_str_(r::Regex)
# s = string(r)
# s[findlast(x -> x == '"', s)+1:end]
# end
@inline bson_representation_type(::Type{Regex}) = BSONRegex
@inline bson_representation_convert(::Type{Regex}, x::BSONRegex) = Regex(x.pattern, x.options)
@inline bson_representation_convert(::Type{BSONRegex}, x::Regex) = BSONRegex(
x.pattern,
regex_opts_str_(x)
)
@inline bson_representation_type(::Type{<:IPAddr}) = String
@inline bson_representation_type(::Type{<:Sockets.InetAddr}) = String
bson_representation_convert(::Type{String}, x::Sockets.InetAddr{IPv4}) = "$(x.host):$(x.port)"
function bson_representation_convert(::Type{Sockets.InetAddr{IPv4}}, x::String)
m = match(r"^(.*):(\d+)$", x)
m === nothing && throw(ArgumentError("Invalid IPv4 inet address: $x"))
Sockets.InetAddr(IPv4(m.captures[1]), parse(Int, m.captures[2]))
end
bson_representation_convert(::Type{String}, x::Sockets.InetAddr{IPv6}) = "[$(x.host)]:$(x.port)"
function bson_representation_convert(::Type{Sockets.InetAddr{IPv6}}, x::String)
m = match(r"^\[(.*)\]:(\d+)$", x)
m === nothing && throw(ArgumentError("Invalid IPv6 inet address: $x"))
Sockets.InetAddr(IPv6(m.captures[1]), parse(Int, m.captures[2]))
end
@inline bson_representation_type(::Type{Date}) = DateTime
bson_representation_convert(::Type{Date}, x::DateTime) = Date(x)
bson_representation_convert(::Type{DateTime}, x::Date) = DateTime(x)
struct NumericBSONConversions <: BSONConversionRules end
@inline function bson_representation_type(::NumericBSONConversions, ::Type{T}) where T
bson_representation_type(DefaultBSONConversions(), T)
end
@inline function bson_representation_convert(::NumericBSONConversions, ::Type{T}, x) where T
bson_representation_convert(DefaultBSONConversions(), T, x)
end
const SmallInt = Union{Int8, UInt8, Int16, UInt16}
@inline bson_representation_type(::NumericBSONConversions, ::Type{<:SmallInt}) = Int32
@inline bson_representation_type(::NumericBSONConversions, ::Type{UInt32}) = Int32
@inline bson_representation_type(::NumericBSONConversions, ::Type{UInt64}) = Int64
@inline bson_representation_type(::NumericBSONConversions, ::Type{Float32}) = Float64
@inline bson_representation_convert(::NumericBSONConversions, ::Type{Float64}, x::Float32) = Float64(x)
@inline bson_representation_convert(::NumericBSONConversions, ::Type{Float32}, x::Float64) = Float32(x)
@inline bson_representation_convert(::NumericBSONConversions, ::Type{Int32}, x::SmallInt) = Int32(x)
@inline bson_representation_convert(::NumericBSONConversions, ::Type{T}, x::Int32) where T <: SmallInt = T(x)
@inline bson_representation_convert(::NumericBSONConversions, ::Type{Int32}, x::UInt32) = reinterpret(Int32, x)
@inline bson_representation_convert(::NumericBSONConversions, ::Type{UInt32}, x::Int32) = reinterpret(UInt32, x)
@inline bson_representation_convert(::NumericBSONConversions, ::Type{Int64}, x::UInt64) = reinterpret(Int64, x)
@inline bson_representation_convert(::NumericBSONConversions, ::Type{UInt64}, x::Int64) = reinterpret(UInt64, x)
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 3268 | const BSON_TYPE_DOUBLE = 0x01
const BSON_TYPE_STRING = 0x02
const BSON_TYPE_DOCUMENT = 0x03
const BSON_TYPE_ARRAY = 0x04
const BSON_TYPE_BINARY = 0x05
const BSON_TYPE_UNDEFINED = 0x06
const BSON_TYPE_OBJECTID = 0x07
const BSON_TYPE_BOOL = 0x08
const BSON_TYPE_DATETIME = 0x09
const BSON_TYPE_NULL = 0x0A
const BSON_TYPE_REGEX = 0x0B
const BSON_TYPE_DB_POINTER = 0x0C
const BSON_TYPE_CODE = 0x0D
const BSON_TYPE_SYMBOL = 0x0E
const BSON_TYPE_CODE_WITH_SCOPE = 0x0F
const BSON_TYPE_INT32 = 0x10
const BSON_TYPE_TIMESTAMP = 0x11
const BSON_TYPE_INT64 = 0x12
const BSON_TYPE_DECIMAL128 = 0x13
const BSON_TYPE_MIN_KEY = 0xFF
const BSON_TYPE_MAX_KEY = 0x7F
const BSON_SUBTYPE_GENERIC_BINARY = 0x00
const BSON_SUBTYPE_FUNCTION = 0x01
const BSON_SUBTYPE_BINARY_OLD = 0x02
const BSON_SUBTYPE_UUID_OLD = 0x03
const BSON_SUBTYPE_UUID = 0x04
const BSON_SUBTYPE_MD5 = 0x05
const BSON_SUBTYPE_ENCRYPTED = 0x06
const UnsafeBSONString = WeakRefString{UInt8}
struct BSONTimestamp
counter::UInt32
time::UInt32
end
BSONTimestamp(x::UInt64) = BSONTimestamp(x % UInt32, (x >> 32) % UInt32)
struct BSONCode
code::String
end
struct BSONCodeWithScope
code::String
mappings::Dict{String, Any}
end
struct BSONBinary
data::Vector{UInt8}
subtype::UInt8
end
BSONBinary(data::Vector{UInt8}) = BSONBinary(data, BSON_SUBTYPE_GENERIC_BINARY)
struct UnsafeBSONBinary
data::UnsafeArray{UInt8, 1}
subtype::UInt8
end
UnsafeBSONBinary(data::UnsafeArray{UInt8, 1}) = UnsafeBSONBinary(data, BSON_SUBTYPE_GENERIC_BINARY)
struct BSONRegex
pattern::String
options::String
end
struct BSONSymbol
value::String
end
struct BSONDBPointer
collection::String
ref::BSONObjectId
end
struct BSONUUIDOld
value::UUID
end
struct BSONMinKey end
struct BSONMaxKey end
struct BSONUndefined end
const ValueField = Union{
Float64,
Int64,
Int32,
Bool,
DateTime,
Dec128,
UUID,
String,
UnsafeBSONString,
Nothing,
BSONTimestamp,
BSONObjectId,
BSONBinary,
UnsafeBSONBinary,
BSONRegex,
BSONCode,
BSONSymbol,
BSONMinKey,
BSONMaxKey,
BSONUndefined,
BSONDBPointer,
BSONUUIDOld
}
bson_type_(::Type{Float64}) = BSON_TYPE_DOUBLE
bson_type_(::Type{Int64}) = BSON_TYPE_INT64
bson_type_(::Type{Int32}) = BSON_TYPE_INT32
bson_type_(::Type{Bool}) = BSON_TYPE_BOOL
bson_type_(::Type{Dec128}) = BSON_TYPE_DECIMAL128
bson_type_(::Type{UUID}) = BSON_TYPE_BINARY
bson_type_(::Type{BSONUUIDOld}) = BSON_TYPE_BINARY
bson_type_(::Type{DateTime}) = BSON_TYPE_DATETIME
bson_type_(::Type{Nothing}) = BSON_TYPE_NULL
bson_type_(::Type{String}) = BSON_TYPE_STRING
bson_type_(::Type{UnsafeBSONString}) = BSON_TYPE_STRING
bson_type_(::Type{BSONTimestamp}) = BSON_TYPE_TIMESTAMP
bson_type_(::Type{BSONBinary}) = BSON_TYPE_BINARY
bson_type_(::Type{UnsafeBSONBinary}) = BSON_TYPE_BINARY
bson_type_(::Type{BSONRegex}) = BSON_TYPE_REGEX
bson_type_(::Type{BSONCode}) = BSON_TYPE_CODE
bson_type_(::Type{BSONSymbol}) = BSON_TYPE_SYMBOL
bson_type_(::Type{BSONObjectId}) = BSON_TYPE_OBJECTID
bson_type_(::Type{BSONMinKey}) = BSON_TYPE_MIN_KEY
bson_type_(::Type{BSONMaxKey}) = BSON_TYPE_MAX_KEY
bson_type_(::Type{BSONUndefined}) = BSON_TYPE_UNDEFINED
bson_type_(::Type{BSONDBPointer}) = BSON_TYPE_DB_POINTER
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 3185 | abstract type BSONValidator end
struct UncheckedBSONValidator <: BSONValidator end
struct LightBSONValidator <: BSONValidator end
struct StrictBSONValidator <: BSONValidator end
@inline validate_field(
::BSONValidator,
type::UInt8,
p::Ptr{UInt8},
field_length::Integer,
available_length::Integer
) = nothing
@inline function validate_field(
::LightBSONValidator,
type::UInt8,
p::Ptr{UInt8},
field_length::Integer,
available::Integer
)
field_length > available && throw(BSONValidationError("Field length too long, $field_length > $available"))
nothing
end
@inline function validate_field(
::StrictBSONValidator,
type::UInt8,
p::Ptr{UInt8},
field_length::Integer,
available::Integer
)
field_length > available && throw(BSONValidationError("Field length too long, $field_length > $available"))
if type == BSON_TYPE_DOCUMENT || type == BSON_TYPE_ARRAY
field_length < 5 && throw(BSONValidationError("Document or array under 5 bytes ($field_length)"))
unsafe_load(p + field_length - 1) != 0 && throw(BSONValidationError("Document or array missing null terminator"))
end
nothing
end
@inline validate_root(::BSONValidator, src::DenseVector{UInt8}) = nothing
@inline function validate_root(validator::LightBSONValidator, src::DenseVector{UInt8})
GC.@preserve src begin
p = pointer(src)
len = ltoh(unsafe_load(Ptr{Int32}(p)))
validate_field(validator, BSON_TYPE_DOCUMENT, p, len, length(src))
end
end
@inline function validate_root(validator::StrictBSONValidator, src::DenseVector{UInt8})
GC.@preserve src begin
p = pointer(src)
len = ltoh(unsafe_load(Ptr{Int32}(p)))
validate_field(validator, BSON_TYPE_DOCUMENT, p, len, length(src))
len < length(src) && throw(BSONValidationError("Garbage after end of document"))
end
end
@inline validate_bool(::BSONValidator, x::UInt8) = nothing
@inline function validate_bool(::StrictBSONValidator, x::UInt8)
x == 0x0 || x == 0x1 || throw(BSONValidationError("Invalid bool value $x"))
nothing
end
@inline validate_string(::BSONValidator, p::Ptr{UInt8}, len::Integer) = nothing
@inline function validate_string(::StrictBSONValidator, p::Ptr{UInt8}, len::Integer)
unsafe_load(p + len) != 0 && throw(BSONValidationError("Code string missing null terminator"))
s = unsafe_string(p, len)
isvalid(s) || throw(BSONValidationError("Invalid UTF-8 string"))
nothing
end
@inline validate_binary_subtype(::BSONValidator, p::Ptr{UInt8}, len::Integer, subtype::UInt8) = nothing
@inline function validate_binary_subtype(::StrictBSONValidator, p::Ptr{UInt8}, len::Integer, subtype::UInt8)
if subtype == BSON_SUBTYPE_UUID || subtype == BSON_SUBTYPE_UUID_OLD || subtype == BSON_SUBTYPE_MD5
len != 16 && throw(BSONValidationError("Subtype $subtype must be 16 bytes long"))
elseif subtype == BSON_SUBTYPE_BINARY_OLD
nested_len = ltoh(unsafe_load(Ptr{Int32}(p + 5)))
nested_len != len - 4 && throw(
BSONValidationError("Binary (Old) subtype invalid length $nested_len, expected $(len - 4)")
)
end
nothing
end
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 1254 | mutable struct BSONWriteBuffer <: DenseVector{UInt8}
data::Vector{UInt8}
len::Int
BSONWriteBuffer() = new(UInt8[], 0)
end
function Base.sizehint!(buffer::BSONWriteBuffer, capacity::Integer)
resize!(buffer.data, max(capacity, buffer.len))
buffer
end
@inline function Base.empty!(buffer::BSONWriteBuffer)
buffer.len = 0
buffer
end
@inline Base.length(buffer::BSONWriteBuffer) = buffer.len
@inline Base.size(buffer::BSONWriteBuffer) = (buffer.len,)
@inline Base.sizeof(buffer::BSONWriteBuffer) = buffer.len
@inline Base.elsize(BSONWriteBuffer) = 1
@inline function Base.getindex(buffer::BSONWriteBuffer, i::Integer)
@boundscheck (i > 0 && i <= buffer.len) || throw(BoundsError(buffer, i))
@inbounds buffer.data[i]
end
@inline function Base.resize!(buffer::BSONWriteBuffer, len::Int)
if length(buffer.data) < len
resize!(buffer.data, len * 2)
end
buffer.len = len
buffer
end
@inline Base.pointer(buffer::BSONWriteBuffer) = pointer(buffer.data)
@inline function Base.push!(buffer::BSONWriteBuffer, x::UInt8)
if length(buffer.data) == buffer.len
resize!(buffer.data, max(buffer.len * 2, 10))
end
buffer.len += 1
@inbounds buffer.data[buffer.len] = x
buffer
end
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 9492 | struct BSONWriter{D <: DenseVector{UInt8}, C <: BSONConversionRules}
dst::D
offset::Int
conversions::C
function BSONWriter(
dst::D;
conversions::C = DefaultBSONConversions()
) where {D <: DenseVector{UInt8}, C <: BSONConversionRules}
offset = length(dst)
resize!(dst, offset + 4)
new{D, C}(dst, offset, conversions)
end
end
# For back compat
@inline BSONWriter(dst::DenseVector{UInt8}, conversions::BSONConversionRules) = BSONWriter(
dst; conversions
)
function Base.close(writer::BSONWriter)
dst = writer.dst
push!(dst, 0x0)
p = pointer(dst) + writer.offset
GC.@preserve dst unsafe_store!(Ptr{Int32}(p), length(dst) - writer.offset)
nothing
end
@inline wire_size_(::Type{T}) where T = missing
@inline wire_size_(::Type{T}) where T <: Union{
Int32, Int64, Float64, Dec128, DateTime, BSONTimestamp, BSONObjectId
} = sizeof(T)
@inline wire_size_(::Type{T}) where T <: Union{Nothing, BSONMinKey, BSONMaxKey} = 0
@inline wire_size_(::Type{Bool}) = 1
@inline wire_size_(::Type{UUID}) = 21
@inline wire_size_(x) = sizeof(x)
@inline wire_size_(x::Nothing) = 0
@inline wire_size_(x::Union{String, UnsafeBSONString}) = sizeof(x) + 5
@inline wire_size_(x::BSONCode) = sizeof(x.code) + 5
@inline wire_size_(x::BSONSymbol) = sizeof(x.value) + 5
@inline wire_size_(x::UUID) = 21
@inline wire_size_(x::BSONUUIDOld) = 21
@inline wire_size_(x::Union{BSONBinary, UnsafeBSONBinary}) = 5 + length(x.data)
@inline wire_size_(x::BSONRegex) = 2 + sizeof(x.pattern) + sizeof(x.options)
@inline wire_size_(x::BSONMinKey) = 0
@inline wire_size_(x::BSONMaxKey) = 0
@inline wire_size_(x::BSONUndefined) = 0
@inline wire_size_(x::BSONDBPointer) = 17 + sizeof(x.collection)
@inline wire_store_(p::Ptr{UInt8}, x::T) where T = unsafe_store!(Ptr{T}(p), htol(x))
@inline wire_store_(::Ptr{UInt8}, ::Nothing) = nothing
@inline wire_store_(p::Ptr{UInt8}, x::Bool) = unsafe_store!(p, UInt8(x))
@inline wire_store_(p::Ptr{UInt8}, x::DateTime) = wire_store_(p, Dates.value(x) - Dates.UNIXEPOCH)
@inline wire_store_(p::Ptr{UInt8}, x::BSONTimestamp) = wire_store_(p, (x.counter % Int64) | ((x.time % Int64) << 32))
@inline wire_store_(p::Ptr{UInt8}, x::BSONObjectId) = unsafe_store!(Ptr{BSONObjectId}(p), x)
@inline wire_store_(::Ptr{UInt8}, ::BSONMinKey) = nothing
@inline wire_store_(::Ptr{UInt8}, ::BSONMaxKey) = nothing
@inline wire_store_(::Ptr{UInt8}, ::BSONUndefined) = nothing
@inline function wire_store_(p::Ptr{UInt8}, x::Union{String, UnsafeBSONString})
unsafe_store!(Ptr{Int32}(p), (sizeof(x) + 1) % Int32)
GC.@preserve x unsafe_copyto!(p + 4, pointer(x), sizeof(x))
unsafe_store!(p + 4 + sizeof(x), 0x0)
end
@inline wire_store_(p::Ptr{UInt8}, x::BSONCode) = wire_store_(p, x.code)
@inline wire_store_(p::Ptr{UInt8}, x::BSONSymbol) = wire_store_(p, x.value)
@inline function wire_store_(p::Ptr{UInt8}, x::UUID)
unsafe_store!(Ptr{Int32}(p), Int32(16))
unsafe_store!(p + 4, BSON_SUBTYPE_UUID)
unsafe_store!(Ptr{UUID}(p + 5), x)
end
@inline function wire_store_(p::Ptr{UInt8}, x::BSONUUIDOld)
unsafe_store!(Ptr{Int32}(p), Int32(16))
unsafe_store!(p + 4, BSON_SUBTYPE_UUID_OLD)
unsafe_store!(Ptr{UUID}(p + 5), x.value)
end
@inline function wire_store_(p::Ptr{UInt8}, x::Union{BSONBinary, UnsafeBSONBinary})
unsafe_store!(Ptr{Int32}(p), length(x.data) % Int32)
unsafe_store!(p + 4, x.subtype)
GC.@preserve x unsafe_copyto!(p + 5, pointer(x.data), length(x.data))
end
@inline function wire_store_(p::Ptr{UInt8}, x::BSONRegex)
GC.@preserve x unsafe_copyto!(p, pointer(x.pattern), sizeof(x.pattern))
unsafe_store!(p + sizeof(x.pattern), 0x0)
GC.@preserve x unsafe_copyto!(p + sizeof(x.pattern) + 1, pointer(x.options), sizeof(x.options))
unsafe_store!(p + sizeof(x.pattern) + sizeof(x.options) + 1 , 0x0)
end
@inline function wire_store_(p::Ptr{UInt8}, x::BSONDBPointer)
wire_store_(p, x.collection)
unsafe_store!(Ptr{BSONObjectId}(p + 5 + sizeof(x.collection)), x.ref)
end
@inline len_(x::AbstractString) = sizeof(x)
@inline len_(x::Symbol) = ccall(:strlen, Csize_t, (Cstring,), Base.unsafe_convert(Ptr{UInt8}, x)) % Int
@inline function write_header_(dst::DenseVector{UInt8}, t::UInt8, name::Union{String, Symbol}, value_size::Integer)
name_len = len_(name)
offset = length(dst)
resize!(dst, offset + name_len + value_size + 2)
GC.@preserve name dst begin
p = pointer(dst) + offset
unsafe_store!(p, t)
ccall(
:memcpy,
Cvoid,
(Ptr{UInt8}, Ptr{UInt8}, Csize_t),
p + 1, Base.unsafe_convert(Ptr{UInt8}, name), name_len % Csize_t
)
unsafe_store!(p + name_len + 1, 0x0)
end
offset + name_len + 2
end
function write_field_(writer::BSONWriter, value::T, name::Union{String, Symbol}) where T <: ValueField
dst = writer.dst
offset = write_header_(dst, bson_type_(T), name, wire_size_(value))
p = pointer(dst) + offset
GC.@preserve dst wire_store_(p, value)
nothing
end
function write_field_(writer::BSONWriter, value::BSONCodeWithScope, name::Union{String, Symbol})
dst = writer.dst
offset = write_header_(dst, BSON_TYPE_CODE_WITH_SCOPE, name, wire_size_(value.code) + 4)
GC.@preserve dst begin
p = pointer(dst) + offset
wire_store_(p + 4, value.code)
mappings_writer = BSONWriter(dst, writer.conversions)
mappings_writer[] = value.mappings
close(mappings_writer)
p = pointer(dst) + offset
unsafe_store!(Ptr{Int32}(p), length(dst) - offset)
end
nothing
end
function write_field_(writer::BSONWriter, generator::Function, name::Union{String, Symbol})
dst = writer.dst
write_header_(dst, BSON_TYPE_DOCUMENT, name, 0)
element_writer = BSONWriter(dst, writer.conversions)
generator(element_writer)
close(element_writer)
end
const SMALL_INDEX_STRINGS = [string(i) for i in 0:99]
function write_field_(writer::BSONWriter, values::Union{AbstractVector, Base.Generator}, name::Union{String, Symbol})
dst = writer.dst
write_header_(dst, BSON_TYPE_ARRAY, name, 0)
element_writer = BSONWriter(dst, writer.conversions)
element_writer[] = values
close(element_writer)
end
function Base.setindex!(writer::BSONWriter, values::Union{AbstractVector, Base.Generator})
for (i, x) in enumerate(values)
is = i <= length(SMALL_INDEX_STRINGS) ? SMALL_INDEX_STRINGS[i] : string(i - 1)
writer[is] = x
end
nothing
end
@inline function write_field_(writer::BSONWriter, value::T, name::Union{String, Symbol}) where T
if isstructtype(T)
write_field_(writer, field_writer -> field_writer[] = value, name)
else
throw(ArgumentError("Unsupported type $T"))
end
end
@inline function Base.setindex!(writer::BSONWriter, value::T, name::Union{String, Symbol}) where T
RT = bson_representation_type(writer.conversions, T)
if RT != T
write_field_(writer, bson_representation_convert(writer.conversions, RT, value), name)
else
write_field_(writer, value, name)
end
end
function Base.setindex!(writer::BSONWriter, fields::AbstractDict{<:Union{String, Symbol}})
for (key, value) in fields
writer[key] = value
end
nothing
end
@inline function Base.setindex!(writer::BSONWriter, field::Pair{String})
writer[field.first] = field.second
nothing
end
function Base.setindex!(writer::BSONWriter, fields::Tuple{Vararg{Pair{String, T} where T}})
for (key, value) in fields
writer[key] = value
end
nothing
end
@inline @generated function bson_write_simple(writer::BSONWriter, value::T) where T
fieldcount(T) == 0 && return nothing
totalsize = sum(wire_size_, fieldtypes(T)) + sum(sizeof, fieldnames(T)) + fieldcount(T) * 2
if ismissing(totalsize)
e = Expr(:block)
for fn in fieldnames(T)
fns = string(fn)
push!(e.args, :(writer[$fns] = value.$fn))
end
e
else
e = Expr(:block)
curoffset = 0
for (ft, fn) in zip(fieldtypes(T), fieldnames(T))
push!(e.args, :(unsafe_store!(p + $curoffset, $(bson_type_(ft)))))
curoffset += 1
fns = string(fn)
fnl = sizeof(fns)
push!(e.args, :(ccall(:memcpy, Cvoid, (Ptr{UInt8}, Ptr{UInt8}, Csize_t), p + $curoffset, pointer($fns), $fnl)))
curoffset += fnl
push!(e.args, :(unsafe_store!(p + $curoffset, 0x0)))
curoffset += 1
push!(e.args, :(wire_store_(p + $curoffset, value.$fn)))
curoffset += wire_size_(ft)
end
quote
dst = writer.dst
offset = length(dst)
resize!(dst, offset + $totalsize)
GC.@preserve dst begin
p = pointer(dst) + offset
$e
end
end
end
end
@inline function bson_write_structtype(writer::BSONWriter, value)
StructTypes.foreachfield(value) do i, name, FT, value
writer[name] = value
end
end
@inline function bson_write(writer::BSONWriter, value::T) where T
v = bson_schema_version(T)
if v !== nothing
writer[bson_schema_version_field(T)] = v
end
if bson_simple(T)
bson_write_simple(writer, value)
else
bson_write_structtype(writer, value)
end
end
@inline function Base.setindex!(writer::BSONWriter, value::T) where T
bson_write(writer::BSONWriter, value)
end
| LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
|
[
"MIT"
] | 0.2.21 | ce253ad53efeed8201656971874d8cd9dad0227e | code | 315 | @testset "convenience" begin
x = LittleDict{String, Any}("x" => 1, "y" => 2)
buf = bson_write(UInt8[], x)
@test bson_read(buf) == x
io = IOBuffer()
bson_write(io, x)
seekstart(io)
@test bson_read(io) == x
path, io = mktemp()
bson_write(path, x)
@test bson_read(path) == x
end | LightBSON | https://github.com/ancapdev/LightBSON.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.