## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
                      eval = requireNamespace("Matrix", quietly = TRUE))

## -----------------------------------------------------------------------------
library(Matrix)
library(rmumps)

g <- 50
I <- Diagonal(g)
D2 <- bandSparse(g, g, -1:1, list(rep(-1, g - 1), rep(2, g), rep(-1, g - 1)))
D1 <- bandSparse(g, g, c(-1, 1), list(rep(-0.5, g - 1), rep(0.5, g - 1)))
L <- kronecker(I, D2) + kronecker(D2, I)
a <- L + kronecker(I, D1)
n <- nrow(a)
b <- as.double(a %*% (1:n))   # right-hand side for the solution 1:n

am <- Rmumps$new(a)
x <- solve(am, b)
max(abs(x - 1:n))
am
am$mumps_version()

## -----------------------------------------------------------------------------
X <- solve(am, cbind(b, 2 * b))              # several right-hand sides
y <- solvet(am, as.double(t(a) %*% (1:n)))   # the transposed system
max(abs(y - 1:n))
c(rmumps = determinant(am)$modulus,          # log |det(a)|
  Matrix = determinant(a)$modulus)

## -----------------------------------------------------------------------------
am$set_mat_data(2 * a@x)
max(abs(solve(am, b) - (1:n) / 2))

## -----------------------------------------------------------------------------
amp <- Rmumps$new(triu(L), sym = 1)
max(abs(solve(amp, as.double(L %*% (1:n))) - 1:n))

## -----------------------------------------------------------------------------
s <- L - Diagonal(n)
ams <- Rmumps$new(triu(s), sym = 2)
max(abs(solve(ams, as.double(s %*% (1:n))) - 1:n))
ams$get_infos()$infog[12]
ev <- 4 * sin(pi * (1:g) / (2 * (g + 1)))^2
sum(outer(ev, ev, "+") < 1)

## -----------------------------------------------------------------------------
A3 <- Rmumps$new(c(0L, 1L, 2L), c(0L, 1L, 2L), c(4, 5, 6), 3L)
solve(A3, c(4, 10, 18))

## -----------------------------------------------------------------------------
orderings <- c(AMD = RMUMPS_PERM_AMD, PORD = RMUMPS_PERM_PORD,
               METIS = RMUMPS_PERM_METIS)
sapply(orderings, function(p) {
  m <- Rmumps$new(a)
  m$set_permutation(p)
  m$numeric()   # analysis and factorization, without a solve
  infos <- m$get_infos()
  c(entries = infos$infog[29], flops = infos$rinfog[3])
})

## -----------------------------------------------------------------------------
am$set_icntl(100L, 14L)
am$get_icntl()[14]

## -----------------------------------------------------------------------------
sing <- Rmumps$new(c(0L, 1L), c(0L, 0L), c(1, 1), 2L)   # a zero column
tryCatch(solve(sing, c(1, 1)), error = conditionMessage)

