Skip to content
Closed
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
76 changes: 76 additions & 0 deletions src/sage/numerical/backends/cvxpy_backend.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,9 @@ cdef class CVXPYBackend:
sage: p.row_name(1)
'constraint_1'
"""
if not isinstance(coefficients, (list, tuple)):
# may be generator
coefficients = list(coefficients)
last = len(self.Matrix)
self.Matrix.append([])
for i in range(len(self.objective_coefficients)):
Expand Down Expand Up @@ -932,3 +935,76 @@ cdef class CVXPYBackend:
self.col_lower_bound[index] = value
else:
return self.col_lower_bound[index]

cpdef remove_constraint(self, int index):
"""
Remove a linear constraint by index.

INPUT:

- ``index`` -- integer. The index of the constraint to remove.

EXAMPLES::

sage: from sage.numerical.backends.generic_backend import get_solver
sage: p = get_solver(solver="CVXPY")
sage: p.add_variables(5)
4
sage: row_index = p.nrows(); row_index
5
sage: p.add_linear_constraint(zip(range(5), range(5)), 2, 2)
sage: p.nrows() - row_index
1
sage: p.add_linear_constraint(zip(range(5), range(5)), 1, 1, name='foo')
sage: p.nrows() - row_index
2
sage: p.remove_constraint(row_index)
sage: p.nrows() - row_index
1
sage: p.row_name(row_index)
'foo'
sage: p.row_bounds(row_index)
(1, 1)
sage: p.cvxpy_problem().constraints[row_index:]
[Equality(Expression(AFFINE, UNKNOWN, ()), Constant(CONSTANT, NONNEGATIVE, ()))]
"""
self.remove_constraints([index])

cpdef remove_constraints(self, indices):
r"""
Remove several constraints.

INPUT:

- ``indices`` -- iterable of integers. The indices of the constraints to remove,
in arbitrary order.

EXAMPLES::

sage: from sage.numerical.backends.generic_backend import get_solver
sage: p = get_solver(solver="CVXPY")
sage: p.add_variables(5)
4
sage: row_index = p.nrows(); row_index
5
sage: for i in range(3):
....: p.add_linear_constraint(zip(range(5), range(5)), None, 5)
sage: p.add_linear_constraint(zip(range(5), range(5)), 1, 1, name='foo')
sage: p.cvxpy_problem().constraints[row_index:]
[Inequality(Expression(AFFINE, UNKNOWN, ())),
Inequality(Expression(AFFINE, UNKNOWN, ())),
Inequality(Expression(AFFINE, UNKNOWN, ())),
Equality(Expression(AFFINE, UNKNOWN, ()), Constant(CONSTANT, NONNEGATIVE, ()))]
sage: p.remove_constraints(range(row_index, row_index + 3))
sage: p.cvxpy_problem().constraints[row_index:]
[Equality(Expression(AFFINE, UNKNOWN, ()), Constant(CONSTANT, NONNEGATIVE, ()))]
"""
indices = sorted(indices)
constraints = list(self.problem.constraints)
for index in reversed(indices):
del self.Matrix[index]
del self.row_lower_bound[index]
del self.row_upper_bound[index]
del self.constraint_names[index]
del constraints[index]
self.problem = cvxpy.Problem(self.problem.objective, constraints)