Gheouany Saad
Gheouany Saad

Reputation: 11

Invalid constraint using where in xpress optimizer

How can I use a nonlinear function like numpy.where in xpress solver in Python? Is it possible? If not, what other method to use?

Upvotes: 1

Views: 527

Answers (1)

Daniel Junglas
Daniel Junglas

Reputation: 5940

In order to use non-linear functions with xpress you have to wrap them as user functions by means of xpress.user(). Your code should look something like this:

for i in range(n_var):
    func = lambda y: (np.mean(np.where(y[:,1]==1)[0]) - np.mean(np.where(appliances[:,i]==1)[0]))**2
    m.addConstraint(xp.user(func, x) <= 6)

Note that things will not work as written above, though.

  1. xpress.user does not accept numpy arrays or lists at the moment. So you need to do something like *x.reshape(c*n,1).tolist() as second argument to xpress.user.
  2. The function passed as argument to xpress.user will not receive the variable objects but the values for the variable objects that were passed as arguments to xpress.user and these will be in a flat list. So your function will probably take a variable number of arguments by means of *args.

The following may work: it is completely untested but I hope you get the idea:

for i in range(n_var):
    vars_for_i = x[:,1]
    func = lambda *y: (np.mean(np.where(np.array(y).reshape(1,len(y))==1)[0]) - np.mean(np.where(appliances[:,i]==1)[0]))**2
    m.addConstraint(xp.user(func, *vars_for_i) <= 6)

You can probably do better than creating a new array in the function every time the function gets invoked.

Upvotes: 0

Related Questions