jacobian_sparsity(f, x, sd) is the pattern of the Jacobian of f at
inputs like x, and hessian_sparsity(f, x, sd) the pattern of the
Hessian of the scalar function f, as logical sparse matrices. With the
default sd = NULL the pattern is found by tracing f, as
SparseConnectivityTracer's TracerSparsityDetector(): f is called with
a vector whose entries record which inputs they depend on, through the
arithmetic, math and summary functions of R. The pattern is global (it
does not depend on the values in x), and code whose control flow depends
on the values cannot be traced. sd = "none" gives a dense pattern
(NoSparsityDetector()), and a matrix gives that known pattern
(KnownJacobianSparsityDetector(), KnownHessianSparsityDetector()).
Usage
jacobian_sparsity(f, x, sd = NULL)
hessian_sparsity(f, x, sd = NULL)
column_coloring(M, ca = NULL)
row_coloring(M, ca = NULL)
symmetric_coloring(M, ca = NULL)Value
A logical sparse matrix (jacobian_sparsity(),
hessian_sparsity()) or an integer vector of colors.
Details
column_coloring(M) partitions the columns of M into structurally
orthogonal groups (no two columns of a group have a nonzero in the same
row), row_coloring(M) the rows, and symmetric_coloring(M) the columns
of a symmetric matrix by a star coloring, so that a Jacobian or Hessian
can be computed from one directional derivative per color. They are the
greedy algorithms of SparseMatrixColorings with the natural vertex order
(GreedyColoringAlgorithm()); ca = "none" gives every column its own
color (NoColoringAlgorithm()).
Examples
f <- function(x) c(x[1] * x[2], sin(x[3]), x[1] + x[4] * x[4])
S <- jacobian_sparsity(f, c(1, 2, 3, 4))
S
#> 3 x 4 sparse Matrix of class "lgCMatrix"
#>
#> [1,] | | . .
#> [2,] . . | .
#> [3,] | . . |
column_coloring(S)
#> [1] 1 2 1 2
row_coloring(S)
#> [1] 1 1 2
g <- function(x) x[1] * x[2] + exp(x[3]) + x[4] / x[1]
H <- hessian_sparsity(g, c(1, 2, 3, 4))
symmetric_coloring(H)
#> [1] 1 2 1 2