0

Objective:

maximize :((((alpha1*5000)+(alpha2*0.49431))-5000) + (((alpha1*5000)+(alpha2*0.49431))-0.49431)) 

constarints:

mod(alpha) <= 1

Code:

from scipy.optimize import minimize
alpha  = [0,0];v1 = 5000
v2 = 0.49431537320810676

def objective(alpha,sign = -1.0):
    alpha1 = alpha[0]
    alpha2 = alpha[1]
    return sign*((((alpha1*5000)+(alpha2*0.49431537320810676))-5000) + (((alpha1*5000)+(alpha2*0.49431537320810676))-0.49431537320810676)) 

def constraint1(alpha):

    return (1- abs (alpha[0]))

def constraint2(alpha):

    return (1- abs (alpha[1]))

con1 = {'type':'ineq','fun':constraint1}
con2 = {'type':'ineq','fun':constraint2}
cons = [con1,con2]

sol = minimize(objective,alpha,method='SLSQP',constraints = cons)

I have given the sign in the objective function to change the optimization to maximize.

Solution:

(sol.x)
 >>>>[ 1.00104909  0.99560862]

I have given the constraints for the alpha for it to be less than 1 , but getting the solutions more than 1.

1
  • 2
    You are using an NLP solver to solve an LP. That is almost always a bad idea. In addition you use non-differentiable functions abs(x), while this NLP solver assumes smooth functions. This is just a bad approach to solving your problem. Commented Jun 29, 2017 at 20:32

2 Answers 2

2

If you see examine the returned object sol, you will see that it has a property .message with the "value"

'Positive directional derivative for linesearch'

which, according to this answer, implies failure to guarantee that the returned solution is optimal. Indeed, it violates the constraints.

This behavior is probably due to the problem having a solution at the boundary of the domain of the optimization variables. Indeed, CVXPY, which is a much better option for linear programming than SLSQP, returns the optimal optimization variable equal to [1,1].

You may want to try scipy.optimize.linprog as a more suitable scipy function for linear programs, although I believe that it is not as fast as CVXPY (or other free LP packages).

Sign up to request clarification or add additional context in comments.

Comments

1

Constraints can be violated and are mainly used for relations between parameters. What you are looking for is the keyword bounds.

from scipy.optimize import minimize
alpha  = [0.,0.];v1 = 5000
v2 = 0.49431537320810676

def objective(alpha,sign = -1.0):
    alpha1 = alpha[0]
    alpha2 = alpha[1]
    return sign*(alpha1*v1+alpha2*v2-v1 + alpha1*v1+alpha2*v2-v2) 

sol = minimize(objective,alpha,method='SLSQP', bounds = ((-1,1),(-1,1)))
sol.x
>> array([ 1.,  1.])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.