coin-or / coin-or/CyLP

Issue with single-dimensional variables

Open
#96 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
JetBrains MPS
Stars
192
Forks
70
PR merge metrics
No merged PRs in 30d

Description

Hello, this may have been reported before but there is an annoying issue with size one variables when trying to multiply them by a matrix.

Here is an example. I am encoding the constraints `1 <= x <= 2` as `x <= 2` and `-x <= -1`.
```python
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPArray
import numpy as np

s = CyClpSimplex()
x = s.addVariable('x', 1)
A = np.matrix([[1, -1]])
b = np.array([2, -1])
s.addConstraint(A*x <= b)
s.objective = x.sum()
s.primal()
```

This example crashes with the following error message:
```
IndexError Traceback (most recent call last)
in
7 A = np.matrix([[1, -1]])
8 b = np.array([2, -1])
----> 9 s.addConstraint(A*x <= b)
10 s.objective = x.sum()
11 s.primal()

cylp\cy\CyClpSimplex.pyx in cylp.cy.CyClpSimplex.CyClpSimplex.addConstraint()

C:\ProgramData\Anaconda3\lib\site-packages\cylp\py\modeling\CyLPModel.py in addConstraint(self, cons, consName, addMpsNames)
1016 '''
1017
-> 1018 c = cons.evaluate(consName)
1019 if not c.isRange:
1020 self.constraints.append(c)

C:\ProgramData\Anaconda3\lib\site-packages\cylp\py\modeling\CyLPModel.py in evaluate(self, name)
291 right = operands.pop()
292 left = operands.pop()
--> 293 cons.perform(token, left, right)
294 operands.append(CyLPExpr(token, left, right))
295

C:\ProgramData\Anaconda3\lib\site-packages\cylp\py\modeling\CyLPModel.py in perform(self, opr, left, right)
402 raise Exception("Coefficient:\n%s\n has %d" \
403 " columns expected %d"
--> 404 % (left, left.shape[1], right.dim))
405 if len(left.shape) == 1: # Array
406 nr = 1

IndexError: tuple index out of range
```

I think the issue comes from `np.squeeze`ing the matrix at the beginning of `CyLPConstraint.perform` ([link](https://github.com/coin-or/CyLP/blob/master/cylp/py/modeling/CyLPModel.py#L358)) which transforms the matrix to an array when one of the dimensions is 1.
I don't know if this can be fixed easily?
I ran into this issue when solving over multiple datasets with a loop: one of the datasets only had one number and created a size 1 variable.
I managed to work around the issue by adding an extra variable and padding my matrices with zeros. A bit annoying and ugly but it did the trick.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.