PySCIPOpt icon indicating copy to clipboard operation
PySCIPOpt copied to clipboard

Support for np v1.x floats as LHS values

Open Opt-Mucca opened this issue 1 year ago • 3 comments

Describe the bug For older (still standard) versions of numpy, we fail to create the below constraints. This issue no longer exists for numpy 2.x, but I predict it will be a few years until 1.x becomes non widely used. The general reason for the error after looking into for a few hours: At some point when we create the ExprCons object the __nonzero__ function will be called (probably should change this to __bool__ at some point). It is called after the ExprCons object has been initialised and after the richcmp function has finished. My best guess is that it is being called because np is somehow forcing a comparison between the two objects at some point. This problem is avoided when np is on the RHS and we are then comparing our ExprCons object to the np object (therefore using our comparison function, which doesn't exist I guess?). Somehow when it is on the LHS np is returning some actual value instead of something that hides the comparison.

To Reproduce

from pyscipopt import Model
import numpy as np

m = Model()
a = np.array([1, 2, 3], dtype=np.float32)
x = m.addVar()
y = m.addVar()
m.addCons(a[1] <= 2 * x + 3 * y)

Expected behavior A constraint should be added

Opt-Mucca avatar Dec 11 '24 16:12 Opt-Mucca

I tried numpy 2.1.0, 2.0.2, 1.26.4. numpy 2.0.2 will raise this error too. a[1] <= x it calls np.float64.__le__ method. I thought this is a upstream problem, we can't fix it in pyscipopt.

Zeroto521 avatar Nov 05 '25 05:11 Zeroto521

For a[1] <= x, numpy 2.0.2 wouldn't change it into x >= a[0] in np.float64.__le__.

  • numpy 2.0.2: https://github.com/numpy/numpy/blob/854252ded83e6b9c21c4ee80558d354d8a72484c/numpy/_typing/_callable.pyi#L326-L336
  • numpy 2.1.0: https://github.com/numpy/numpy/blob/2f7fe64b8b6d7591dd208942f1cc74473d5db4cb/numpy/_typing/_callable.pyi#L361-L381

Zeroto521 avatar Nov 05 '25 05:11 Zeroto521

This is an upstream problem, but I believe it can be fixed by reworking how we handle our comparisons. This is a low priority issue though, and doubly so given the amount of work it requires to fix. Thanks for confirming that we can't simply wait for numpy upgrades though! (I could have sworn the error didn't happen when I upgraded major versions......)

Opt-Mucca avatar Nov 17 '25 11:11 Opt-Mucca