Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix gradient for multidimensional quad form #1854

Merged
merged 2 commits into from
Aug 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions cvxpy/atoms/quad_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ def name(self) -> str:
def _grad(self, values):
x = np.array(values[0])
P = np.array(values[1])
D = (P + np.conj(P.T)) @ x.T
return [sp.csc_matrix(D.ravel(order='F')).T]
D = (P + np.conj(P.T)) @ x
return [sp.csc_matrix(D.ravel(order="F")).T]

def shape_from_args(self) -> Tuple[int, ...]:
return tuple() if self.args[0].ndim == 0 else (1, 1)
Expand Down
15 changes: 15 additions & 0 deletions cvxpy/tests/test_grad.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,21 @@ def test_quad_form(self) -> None:
# access quad_form.expr.grad without error
prob.constraints[1].expr.grad

# define the optimization problem with a two-dimensional decision variable
x = cp.Variable((n, 1))
prob = cp.Problem(
cp.Maximize(q.T @ x - (1 / 2) * cp.quad_form(x, P)),
[
cp.norm(x, 1) <= 1.0,
cp.quad_form(x, P) <= 10, # quad form constraint
cp.abs(x) <= 0.01,
],
)
prob.solve(solver=cp.SCS)

# access quad_form.expr.grad without error
prob.constraints[1].expr.grad

def test_max(self) -> None:
"""Test gradient for max
"""
Expand Down