Julia NLopt force stops before the first iteration

Viewed 216

I'm using NLopt for a constrained maximization problem. Regardless of the algorithm or start values, the optimization program is force stopped even before the first iteration (or so I assume because it gives me the initial value). I've attached my code here. I'm trying to find probabilities attached to a grid such that a function is maximized under some constraints. Any help is appreciated.

uk = x -> x^0.5

function objective(u,p,grd)
    -p'*u.(grd)
end

function c3(grd,p)
    c =[]
    d =[]
    for i=1:length(grd)
        push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
        push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
    end
    return append!(d-c,-p)
end

function c4(grd,p)
    return (grd .* p)-quadgk(x,0,1)
end

grd = n -> collect(0:1/n:1)

opt = Opt(:LD_SLSQP,11)

inequality_constraint!(opt, p -> c3(grd(10),p))
inequality_constraint!(opt, p -> -p)
equality_constraint!(opt, p -> sum(p)-1)
equality_constraint!(opt, p -> c4(grd(10),p))


opt.min_objective =  p -> objective(-uk, p, grd(10))

k = push!(ones(11)*(1/11))
(minf,minx,ret) = optimize(opt, k)
1 Answers

I'm not a julia developer, but I only know this, if you need exit before complete the loop for is not your best choice, you need do a while with a sentinel variable.

here you have an article that explain you how while with sentinels works and here you have a julia example changing your for to a while with a sentinel that exit after the third loop

i = 1
third = 0

while i < length(grd) && third != 1
    # of course you need change this, it is only an example that will exit in the 3 loop 
    if i == 3
        third = 1
    end
    push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
    push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
    i += 1
end
Related