Forum Discussion

FICO's avatar
FICO
Community Manager
3 years ago

How to use chgmcoef or similar functions to change constraints coefficients with indexed dictionary

Hello Xpress experts! I would appreciate if you could help me figure out the following question. Thanks in advance!

I have a dummy problem with both variables and constraints defined in dictionary style:

mdl = xp.problem("test")
 
# Creating a dictionary of variables
 
y = {(m,t): xp.var(vartype = xp.binary, lb = 0, ub = 1, name = f'y_{m}_{t}') for m in range(10) for t in range(5)}
 
# Parameters
 
p = {(m,t): m*2+t for m in range(10) for t in range(5)}
b = {(m,t): m*3+t*3 for m in range(10) for t in range(5)}
 
c1 = {
  (m,t): xp.constraint(
    body=(
      p[m,t] * y[m,t] - b[m,t]
    ),
    sense = xp.leq,
    rhs = 0,
  )
  for m in range(10)
  for t in range(5)
}
 
mdl.addVariable(x,y)
mdl.addConstraint(c1)
mdl.solve()

Now I want to change the coefficient of p[m,t] to p2[m,t] and resolve the model without rebuilding it. I have the following code:

p2 = {(m,t): m*3+t*3 for m in range(10) for t in range(5)}
 
mdl.chgmcoef(c1, y, p2)

And it gave me an error of "Invalid sequence of objects" on chgmcoef function.

I could not find more details in the documentation as chgmcoef therein only has an example of using lists to update the coefficient. I'm wondering if there is a good way of updating the coefficients with indices?

To be clear, I know we could use a bunch of for loops and chgcoef to first extract individual constraint out of the dictionary and change the coefficient one by one in the for loop:

for m in range(10):
    for t in range(5):
        mdl.chgcoef(c1[m,t], y[m,t], p2[m,t])

but I think that is less efficient and wonder if we have more elegant liners to achieve this without using for loops. I guess the essence of chgmcoef is to efficiently do things other than multiple chgcoef. Thanks!

Any suggestion is highly appreciated! Thanks.

1 Reply

  • FICO's avatar
    FICO
    Community Manager

    As you can see in the documentation, function chgmcoef()required arguments to be arrays, so dictionaries won't work. I can see two ways to write your code with a single call to chgmcoef():

    mdl.chgmcoef([c1[m,t] for m,t in c1],
                 [y[m,t] for m,t in c1],
                 [p2[m,t] for m,t in c1])

    or

    zipped = [(c1[m,t], y[m,t], p2[m,t]) for m,t in c1]
    rowind, colind, rowcoef = zip(*zipped)
    mdl.chgmcoef(rowind, colind, rowcoef)