CPMpy / cpmpy

Constraint Programming and Modeling library in Python, based on numpy, with direct solver access.
Apache License 2.0
218 stars 21 forks source link

AssertionError when using a value of 0.0 with type numpy.float32 as weight in a weighted sum objective #166

Closed senneberden closed 1 year ago

senneberden commented 1 year ago

Using CPMpy v0.9.9 Python 3.8.10 gurobipy 9.5.1

When using CPMpy to model a problem with a weighted sum as objective, and using the Gurobi solver, an AssertionError is thrown when one of the weights is 0.0 with type numpy.float64. This problem does not occur when the weights are of type numpy.int64 (even when a value of 0 is included), or when the weights are non-zero values of type numpy.float64.

import numpy as np
from cpmpy import *

x = boolvar(shape=3, name="x")
solver = SolverLookup.get("gurobi")

# Integer values work, also when one of the weights is 0
solver.maximize(sum(x * np.array([3, 2, 0])))

# Non-zero numpy.fLoat64 weights work as well
solver.maximize(sum(x * np.array([3.0, 2.0, 1.0])))

# A zero numpy.float64 weight does not work
# Gives error: "AssertionError: IntVar lowerbound must be integer <class 'numpy.float64'> 0.0"
solver.maximize(sum(x * np.array([3.0, 2.0, 0.0])))

Traceback

Traceback (most recent call last):
  File ~, line 15, in <module>
    solver.maximize(sum(x * np.array([3.0, 2.0, 0.0])))
  File "~/python3.8/site-packages/cpmpy/solvers/solver_interface.py", line 107, in maximize
    return self.objective(expr, minimize=False)
  File "~/python3.8/site-packages/cpmpy/solvers/gurobi.py", line 206, in objective
    (flat_obj, flat_cons) = (flatten_objective(expr))
  File "~/python3.8/site-packages/cpmpy/transformations/flatten_model.py", line 241, in flatten_objective
    return normalized_numexpr(expr)
  File "~/python3.8/site-packages/cpmpy/transformations/flatten_model.py", line 538, in normalized_numexpr
    flatvars, flatcons = zip(*[get_or_make_var(arg) for arg in expr.args])
  File "~/python3.8/site-packages/cpmpy/transformations/flatten_model.py", line 538, in <listcomp>
    flatvars, flatcons = zip(*[get_or_make_var(arg) for arg in expr.args])
  File "~/python3.8/site-packages/cpmpy/transformations/flatten_model.py", line 308, in get_or_make_var
    ivar = _IntVarImpl(min(bnds),max(bnds))
  File "~/python3.8/site-packages/cpmpy/expressions/variables.py", line 259, in __init__
    assert is_int(lb), "IntVar lowerbound must be integer {} {}".format(type(lb),lb)
AssertionError: IntVar lowerbound must be integer <class 'numpy.float64'> 0.0
Wout4 commented 1 year ago

Closing as fixed with pull request #182