It's not totally clear from your description which of the parameters of f
you are optimizing over. For the purposes of this example I'm going to use x
to refer to the vector of parameters you are optimizing over, and a
to refer to another parameter vector of the same length which is held constant.
Now let's suppose you wanted to enforce the following inequality constraint:
10 <= x[0] * a[0] + x[1] * a[1] + ... + x[n] * a[n]
First you must define a function that accepts x
and a
and returns a value that is non-negative when the constraint is met. In this case we could use:
lambda x, a: (x * a).sum() - 10
or equivalently:
lambda x, a: x.dot(a) - 10
Constraints are passed to minimize in a dict (or a sequence of dicts if you have multiple constraints to apply):
con = {'type': 'ineq',
'fun': lambda x, a: a.dot(x) - 10,
'jac': lambda x, a: a,
'args': (a,)}
For greater efficiency I've also defined a function that returns the Jacobian (the sequence of partial derivatives of the constraint function w.r.t. each parameter in x
), although this is not essential - if unspecified it will be estimated via first-order finite differences.
Your call to minimize
would then look something like:
res = minimize(f, x0, args=(a,), method='SLSQP', constraints=con)
You can find another complete example of constrained optimization using SLSQP in the official documentation here.
maximize
from? There's no maximize function inscipy.optimize
(usually you would just minimize-f(a, b, c, d)
).scipy.optimize.minimize
with the SLSQP solverx0
(x0
is the internally passed set of variables) values and checks if sum allx0 * a0
values satisfies some conditions. Please tell me if posting some code would help gettign a clearer picture of what I am asking.