Skip to content

Commit

Permalink
fixing issue with sparsity in projection
Browse files Browse the repository at this point in the history
  • Loading branch information
William Zijie Zhang authored and William Zijie Zhang committed Aug 9, 2024
1 parent e4b852c commit 54116b8
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
4 changes: 3 additions & 1 deletion cvxpy/expressions/leaf.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,9 @@ def project(self, val):
w[bad] = 0
return (V * w).dot(V.T)
elif self.attributes['sparsity']:
return np.where(val[self.sparse_idx], val, 0)
new_val = np.zeros(self.shape)
new_val[self.sparse_idx] = val
return new_val
else:
return val

Expand Down
4 changes: 2 additions & 2 deletions cvxpy/reductions/cvx_attr2constr.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,9 @@ def apply(self, problem):
id2new_var[var.id] = sparse_var
row_idx = np.ravel_multi_index(var.sparse_idx, var.shape)
col_idx = np.arange(n)
matrix = Constant(sp.csc_matrix((np.ones(n), (row_idx, col_idx)),
coeff_matrix = Constant(sp.csc_matrix((np.ones(n), (row_idx, col_idx)),
shape=(np.prod(var.shape, dtype=int), n)))
obj = reshape(matrix @ sparse_var, var.shape)
obj = reshape(coeff_matrix @ sparse_var, var.shape)
elif var.attributes['diag']:
diag_var = Variable(var.shape[0], var_id=var.id, **new_attr)
diag_var.set_variable_of_provenance(var)
Expand Down
14 changes: 14 additions & 0 deletions cvxpy/tests/test_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,21 @@ def test_matrix_frac(self) -> None:
class TestAttributes():
def test_sparsity_pattern(self):
X = cp.Variable((3, 3), sparsity=[(0, 0), (1, 1), (2, 2)])
target = np.eye(3)
assert X.sparse_idx == ((0, 1, 2), (0, 1, 2))
prob = cp.Problem(cp.Minimize(0), [X == target])
assert prob.solve(verbose=True) == 0
assert X.value is not None

def test_diag_sparsity(self):
X = cp.Variable((3, 3), diag=True)
prob = cp.Problem(cp.Minimize(cp.norm(X, 'fro')))
assert prob.solve(verbose=True) == 0
assert X.value is not None

def test_sparsity_pattern_similar_diag(self):
X = cp.Variable((3, 3), sparsity=[(0, 0), (1, 1), (2, 2)])
assert X.sparse_idx == ((0, 1, 2), (0, 1, 2))
prob = cp.Problem(cp.Minimize(cp.norm(X, 'fro')))
assert prob.solve(verbose=True) == 0
assert X.value is not None

0 comments on commit 54116b8

Please sign in to comment.