2

I am trying to solve a problem where I need to optimize a linear function, but in practice this must be accessed through a wrapper function, I can solve this with the raw data, but due to implementation constraints I need a way to pass a function as the objective.

For example,

import numpy as np
from scipy.optimize import linprog

def objective(x):
    c = [-1, 4]
    return np.dot(c,x)
c = [-1, 4]
A = [[-3, 1], [1, 2]]
b = [6, 4]
x0_bounds = (None, None)
x1_bounds = (-3, None)
#This Works:
res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),
             options={"disp": True})
#This does not
res = linprog(objective, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),
             options={"disp": True})

I could not see any appropriate resource in cvxopt, cvxpy or scipy. Any help is much appreciated.

1
  • Linear function can be fully defined by its coefficients so it's not clear why you need to pass the whole function instead of passing its coefficients. Commented Feb 25, 2016 at 7:47

1 Answer 1

0

You noticed that linprog requires a coefficient array c, so if you have a function, you can simply deduce the c array:

import numpy as np

x = np.diag((1,1))
c = np.linalg.solve(x,objective(x))

res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),
             options={"disp": True})
Sign up to request clarification or add additional context in comments.

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.