Skip to content

Commit

Permalink
Tests for subgradient.
Browse files Browse the repository at this point in the history
Fix an issue when the initial solution is infeasible: it could have been wrongly seen as the best iterate.
  • Loading branch information
dourouc05 committed Oct 1, 2020
1 parent 412fb09 commit b748a2b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/subgradient.jl
Expand Up @@ -20,10 +20,10 @@ function _solve_sd(p::NonSmoothProblem, params::NonSmoothSolver, x0::Vector{Floa
# Assumption for p' and params' types: either (UnconstrainedNonSmoothProblem, SubgradientMethod) or (ProjectedConstrainedNonSmoothProblem, ProjectedSubgradientMethod).
@assert length(x0) == p.dimension

x_best = copy(x0)
if p isa ProjectedConstrainedNonSmoothProblem
x0 = p.project(x0)
end
x_best = copy(x0)
f_best = p.f(x0)

dir = ((p.sense == Minimise) ? -1.0 : 1.0)::Float64
Expand Down
39 changes: 38 additions & 1 deletion test/runtests.jl
Expand Up @@ -5,7 +5,7 @@ using Test
@testset "Subgradient" begin
@testset "1D: abs(x)" begin
f = (x) -> abs(x[1])
g = x -> [(x[1] < 0) ? -1.0 : 1.0]
g = (x) -> [(x[1] < 0) ? -1.0 : 1.0]

@testset "Minimise 1D" begin
p = UnconstrainedNonSmoothProblem(f, g, 1, Minimise)
Expand Down Expand Up @@ -36,10 +36,47 @@ using Test
@test length(x1) == 1
@test x1[1] 12.0
end

@testset "Maximise 1D (2)" begin
p = UnconstrainedNonSmoothProblem(f, g, 1, Maximise)
a = SubgradientMethod(ConstantStepSize(1.0), 2)

x0 = [-10.0]
x1 = solve(p, a, x0)
@test length(x1) == 1
@test x1[1] -12.0
end

@testset "Info callback" begin
cb_called = false
cb = (k, f, x, g, f_best, x_best, δt) -> begin
cb_called = true
end
p = UnconstrainedNonSmoothProblem(f, g, 1, Maximise)
a = SubgradientMethod(ConstantStepSize(1.0), 2)
solve(p, a, [0.0], info_callback=cb)

@test cb_called
end
end
end

@testset "Projected subgradient" begin
@testset "1D: abs(x)" begin
f = (x) -> abs(x[1])
g = (x) -> [(x[1] < 0) ? -1.0 : 1.0]
proj = (x) -> [200.0]

@testset "Minimise 1D" begin
p = ProjectedConstrainedNonSmoothProblem(f, g, proj, 1, Minimise)
a = ProjectedSubgradientMethod(ConstantStepSize(1.0), 2)

x0 = [10.0] # Infeasible solution! Must be projected!
x1 = solve(p, a, x0)
@test length(x1) == 1
@test x1[1] 200.0
end
end
end

@testset "Bundle" begin
Expand Down

0 comments on commit b748a2b

Please sign in to comment.