Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions mip/cbc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1591,15 +1591,6 @@ def set_mip_gap(self, allowable_ratio_gap: mip.Numeric):
cbclib.Cbc_setAllowableFractionGap(self._model, allowable_ratio_gap)

def constr_get_expr(self, constr: Constr) -> LinExpr:
numnz = cbclib.Cbc_getRowNz(self._model, constr.idx)

ridx = cbclib.Cbc_getRowIndices(self._model, constr.idx)
if ridx == ffi.NULL:
raise ParameterNotAvailable("Error getting row indices.")
rcoef = cbclib.Cbc_getRowCoeffs(self._model, constr.idx)
if rcoef == ffi.NULL:
raise ParameterNotAvailable("Error getting row coefficients.")

rhs = cbclib.Cbc_getRowRHS(self._model, constr.idx)
rsense = cbclib.Cbc_getRowSense(self._model, constr.idx).decode("utf-8").upper()
sense = ""
Expand All @@ -1613,6 +1604,17 @@ def constr_get_expr(self, constr: Constr) -> LinExpr:
raise ValueError("Unknow sense: {}".format(rsense))

expr = LinExpr(const=-rhs, sense=sense)
if not self.num_cols():
return expr

numnz = cbclib.Cbc_getRowNz(self._model, constr.idx)
ridx = cbclib.Cbc_getRowIndices(self._model, constr.idx)
if ridx == ffi.NULL:
raise ParameterNotAvailable("Error getting row indices.")
rcoef = cbclib.Cbc_getRowCoeffs(self._model, constr.idx)
if rcoef == ffi.NULL:
raise ParameterNotAvailable("Error getting row coefficients.")

for i in range(numnz):
expr.add_var(self.model.vars[ridx[i]], rcoef[i])

Expand Down
14 changes: 14 additions & 0 deletions mip/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,10 @@ def add_constr(
priority(mip.constants.ConstraintPriority): optional constraint
priority

Raises:
mip.InvalidLinExpr: if the expression has no comparison, or if it
has no variables and the model has no variables.

Examples:

The following code adds the constraint :math:`x_1 + x_2 \leq 1`
Expand Down Expand Up @@ -371,6 +375,16 @@ def add_constr(
"A boolean (true/false) cannot be used as a constraint."
)

if not lin_expr.sense:
raise mip.InvalidLinExpr(
"A linear expression without a comparison cannot be used as a constraint."
)

if not lin_expr.expr and len(self.vars) == 0:
raise mip.InvalidLinExpr(
"Cannot add an empty constraint to a model without variables."
)

return self.constrs.add(lin_expr, name, priority)

def add_lazy_constr(self: "Model", expr: "mip.LinExpr"):
Expand Down
46 changes: 46 additions & 0 deletions test/mip_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,3 +756,49 @@ def test_empty_contradictory_constraint_is_considered(solver: str):
# check that all names of constraints could be queried
assert {c.name for c in m.constrs} == {"c1", "c_contra"}
assert all(isinstance(m.constr_by_name(c_name), Constr) for c_name in ("c1", "c_contra"))


def test_constraint_without_comparison_raises_invalid_lin_expr():
m = Model(solver_name=CBC)

with pytest.raises(mip.InvalidLinExpr, match="without a comparison"):
m.add_constr(xsum([]))

x = m.add_var()
with pytest.raises(mip.InvalidLinExpr, match="without a comparison"):
m.add_constr(x + 1)

assert m.num_rows == 0


@pytest.mark.parametrize("sense", ["equal", "less_or_equal"])
def test_empty_constraint_without_variables_raises_invalid_lin_expr(sense):
m = Model(solver_name=CBC)
if sense == "equal":
expr = xsum([]) == 0
else:
expr = xsum([]) <= 1

with pytest.raises(mip.InvalidLinExpr, match="model without variables"):
m.add_constr(expr)

assert m.num_rows == 0


@pytest.mark.parametrize("rhs", [0, 1])
def test_empty_constraint_remains_usable_after_last_variable_removed(rhs):
m = Model(solver_name=CBC)
x = m.add_var(name="x")
constr = m.add_constr(xsum([]) == rhs, name="empty")

assert constr.name == "empty"
assert constr.rhs == rhs
assert str(constr)

m.remove(x)

assert constr.expr.expr == {}
assert constr.rhs == rhs
assert str(constr)
m.remove(constr)
assert m.num_rows == 0
Loading