diff --git a/optlang/cplex_interface.py b/optlang/cplex_interface.py index 5e01e112..aee6cd7e 100644 --- a/optlang/cplex_interface.py +++ b/optlang/cplex_interface.py @@ -234,7 +234,13 @@ def get_linear_coefficients(self, variables): def _get_expression(self): if self.problem is not None: cplex_problem = self.problem.problem - cplex_row = cplex_problem.linear_constraints.get_rows(self.name) + try: + cplex_row = cplex_problem.linear_constraints.get_rows(self.name) + except CplexSolverError as e: + if 'CPLEX Error 1219:' not in str(e): + raise e + else: + cplex_row = cplex_problem.indicator_constraints.get_linear_components(self.name) variables = self.problem._variables expression = add( [mul((symbolics.Real(cplex_row.val[i]), variables[ind])) for i, ind in @@ -640,7 +646,7 @@ def __init__(self, problem=None, *args, **kwargs): ) try: objective_name = self.problem.objective.get_name() - except cplex.exceptions.CplexSolverError as e: + except CplexSolverError as e: if 'CPLEX Error 1219:' not in str(e): raise e else: @@ -885,7 +891,9 @@ def _add_constraints(self, constraints, sloppy=False): def _remove_constraints(self, constraints): super(Model, self)._remove_constraints(constraints) for constraint in constraints: - if constraint.is_Linear: + if constraint.indicator_variable is not None: + self.problem.indicator_constraints.delete(constraint.name) + elif constraint.is_Linear: self.problem.linear_constraints.delete(constraint.name) elif constraint.is_Quadratic: self.problem.quadratic_constraints.delete(constraint.name) diff --git a/optlang/interface.py b/optlang/interface.py index 93bb7cdb..f06e5526 100644 --- a/optlang/interface.py +++ b/optlang/interface.py @@ -1511,8 +1511,6 @@ def _add_constraints(self, constraints, sloppy=False): constraint._problem = self def _remove_constraints(self, constraints): - for constraint in constraints: # TODO: remove this hack that fixes problems with lazy solver expressions. - constraint.expression keys = [constraint.name for constraint in constraints] if len(constraints) > 350: # Need to figure out a good threshold here self._constraints = self._constraints.fromkeys(set(self._constraints.keys()).difference(set(keys))) diff --git a/optlang/tests/abstract_test_cases.py b/optlang/tests/abstract_test_cases.py index bc76517b..9aa4567e 100644 --- a/optlang/tests/abstract_test_cases.py +++ b/optlang/tests/abstract_test_cases.py @@ -182,6 +182,12 @@ def test_indicator_constraint_support(self): model = self.interface.Model() model.add(constraint) model.update() + self.assertEqual(constraint.problem, model) + self.assertIn(constraint, model.constraints) + model.remove(constraint.name) + model.update() + self.assertEqual(constraint.problem, None) + self.assertNotIn(constraint, model.constraints) else: self.assertRaises( optlang.exceptions.IndicatorConstraintsNotSupported,