Skip to content

Commit

Permalink
Simplify sparse coercion and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
bnaras committed Oct 4, 2023
1 parent 9b74318 commit e6702ea
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
18 changes: 2 additions & 16 deletions R/sparse.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,7 @@ ensure_dgc_matrix <- function(m) {
} else if (inherits(m, "matrix")) {
Matrix::.m2sparse(m, "dgCMatrix")
} else if(inherits(m, "simple_triplet_matrix")) { ## e.g. from package slam
## The matrix method assumes that indices for non-zero entries are
## in row-major order, but the simple_triplet_matrix() constructor
## currently does not canonicalize accordingly ...
ind <- order(m$j, m$i)
Matrix::sparseMatrix(p = c(0L, cumsum(tabulate(m$j[ind], m$ncol))),
i = m$i[ind] - 1L,
values = m$v[ind], dims = dim(m), index1 = FALSE)
Matrix::sparseMatrix(i = m$i, j = m$j, x = m$v, dims = dim(m))
} else {
## Resort to brute force
as(as(as(m, "CsparseMatrix"), "generalMatrix"), "dMatrix")
Expand All @@ -42,17 +36,9 @@ ensure_dtc_matrix <- function(m) {
Matrix::.m2sparse(m, "dtCMatrix")
} else if(inherits(m, "simple_triplet_matrix")) { ## e.g. from package slam
ind <- which(m$i <= m$j)
x <- list(i = m$i[ind] + 1L, j = m$j[ind] + 1L) ##make it 1-based
values <- m$v[ind]
ind <- order(x$j, x$i) ## may not be needed
Matrix::sparseMatrix(p = c(0L, cumsum(tabulate(x$j[ind], m$ncol))),
i = x$i[ind] - 1L,
values = values,
dims = dim(x), index1 = FALSE,
triangular = TRUE)
Matrix::sparseMatrix(i = m$i[ind], j = m$j[ind], x = m$v[ind], dims = dim(m), triangular = TRUE)
} else {
## Resort to brute force
Matrix::triu(as(as(as(m, "CsparseMatrix"), "generalMatrix"), "dMatrix"))
}
}

27 changes: 27 additions & 0 deletions tests/testthat/test-sparse-coercion.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

context("Sparse Coercions")

test_that("Dense P & A are properly coerced", {
P <- matrix(c(11., 2.0, 2.0, 1.0), 2, 2)
q <- c(3., 4.)
A <- matrix(c(-1., 0., -1., 2., 3., 0., -1., -3., 5., 4.) , 5, 2)
u <- c(0., 0., -15., 100., 80)
l <- rep_len(-Inf, 5)

settings <- osqpSettings(verbose = TRUE)
res <- solve_osqp(P, q, A, l, u, settings)
expect_equal(res$info$status, "solved")
})

test_that("Triplet-form P & A are properly coerced", {
P <- slam::as.simple_triplet_matrix(matrix(c(11., 2.0, 2.0, 1.0), 2, 2))
q <- c(3., 4.)
A <- slam::as.simple_triplet_matrix(matrix(c(-1., 0., -1., 2., 3., 0., -1., -3., 5., 4.) , 5, 2))
u <- c(0., 0., -15., 100., 80)
l <- rep_len(-Inf, 5)

settings <- osqpSettings(verbose = TRUE)
res <- solve_osqp(P, q, A, l, u, settings)
expect_equal(res$info$status, "solved")
})

0 comments on commit e6702ea

Please sign in to comment.