---
title: "Solving sparse linear systems with rmumps"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Solving sparse linear systems with rmumps}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

rmumps is an R interface to [MUMPS](https://mumps-solver.org/), a
multifrontal direct solver for sparse linear systems `A x = b`. The package
bundles MUMPS, built sequential and in double precision, with the orderings
AMD, AMF, QAMD, PORD and METIS.

## A first solve

The examples use a 50 x 50 grid: `L` is the 2-D Laplacian, which is
symmetric positive definite, and `a` adds a convection term, which makes it
nonsymmetric. Its symmetric part is `L`, so `a` is nonsingular.

```{r}
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()
```

`Rmumps$new()` keeps a copy of the matrix. `solve()` runs the three phases
of MUMPS: the analysis (an ordering and a symbolic factorization, which
depend only on where the nonzeros are), the numerical factorization (LU,
or LDL^T for a symmetric matrix) and the solve. The object keeps the
analysis and the factorization.

## Reusing the factorization

Later calls on the same object only run the solve phase:

```{r}
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)
```

The right-hand sides may also be a sparse matrix; the solution is then a
dense matrix. `solve(am)` returns the inverse, as a dense matrix: use it on
small matrices only.

When the values change but not the pattern, `set_mat_data()` replaces
them. They must be in the order of the matrix first given (for a
`dgCMatrix`, the order of its `x` slot). The next solve repeats the
factorization but not the analysis:

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

## Symmetric matrices

A symmetric matrix is factored as LDL^T, which needs about half the work
and memory of LU. Give one triangle only, with `sym = 1` for a positive
definite matrix or `sym = 2` for any symmetric matrix:

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

After the factorization of a symmetric matrix, INFOG(12) is the number of
negative pivots, which is also the number of negative eigenvalues
(Sylvester's law of inertia). `L - I` is indefinite, and the eigenvalues of
`L` are known, so the count can be checked:

```{r}
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)
```

## Other ways to give the matrix

Besides a sparse matrix from Matrix, `Rmumps$new()` accepts a
`slam::simple_triplet_matrix`, or the triplets themselves: 0-based row
indices, 0-based column indices, values, and the dimension.

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

## Orderings and parameters

The ordering decides how much the factors fill in, and so the memory and
the time. By default MUMPS chooses (`RMUMPS_PERM_AUTO`); `RMUMPS_PERM` lists
the choices. Set the ordering before the first solve; setting it later
discards the analysis and the factorization. No ordering is best for every
matrix: here, the entries in the factors (INFOG(29)) and the flops of the
elimination (RINFOG(3)):

```{r}
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])
})
```

SCOTCH is not bundled: `RMUMPS_PERM_SCOTCH` falls back to
`RMUMPS_PERM_AUTO`, with a warning.

`set_icntl(values, positions)` and `set_cntl(values, positions)` set
MUMPS' integer and real control parameters, with positions numbered as in
the MUMPS user guide; `get_icntl()` and `get_cntl()` return them. For
example, ICNTL(14) is the extra working space, in percent:

```{r}
am$set_icntl(100L, 14L)
am$get_icntl()[14]
```

`get_infos()` returns MUMPS' INFO, RINFO, INFOG and RINFOG arrays.

## Errors

MUMPS itself prints nothing. A MUMPS error becomes an R error that gives
the MUMPS error code, and a MUMPS warning an R warning; the MUMPS user
guide explains the codes.

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

## Calling MUMPS from another package

Other packages can call the bundled MUMPS from their own C or C++ code. In
the client package's `DESCRIPTION`:

```
Imports: rmumps
LinkingTo: rmumps
```

In its `NAMESPACE`, import something from rmumps, for example
`importFrom(rmumps, Rmumps)`, so that rmumps is loaded first. Then:

```c
#include <rmumps/rmumps_api.h>

static rmumps_api mumps;

void R_init_mypkg(DllInfo *dll) {
  rmumps_api_load(&mumps);    /* an R error if rmumps is too old */
}

/* later, with a DMUMPS_STRUC_C id set up as in the MUMPS user guide */
char msg[256];
if (RMUMPS_DMUMPS_C(&mumps, &id, msg, sizeof msg) != RMUMPS_OK) {
  /* msg says what happened */
}
```

- `RMUMPS_DMUMPS_C` never returns by `longjmp`: an R error or a user
  interrupt raised while MUMPS runs comes back as a return code, so it can
  be called from C++.
- Call MUMPS from R's main thread only, one call at a time.
- Each entry point is registered under a name that carries the layout of
  `DMUMPS_STRUC_C` it was compiled against. A client binary built against
  an older rmumps therefore keeps working after rmumps is updated.

The header `rmumps/rmumps_api.h` documents the whole contract. C++ code
that uses Rcpp can instead work with `Rmumps` objects through the
`Rmumps__*` functions (`?Rmumps__pointer_api`).

## Version numbers

An rmumps version is the version of the bundled MUMPS followed by an R
revision: 5.9.2-1 is the first rmumps release with MUMPS 5.9.2.

## Citation

`citation("rmumps")` gives the two MUMPS papers to cite.
