Chris
Chris

Reputation: 967

Lambda objective function for python linear optimisation

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.

Upvotes: 2

Views: 394

Answers (1)

Mathieu B
Mathieu B

Reputation: 471

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})

Upvotes: 0

Related Questions