Python bindings for SparseDiffEngine algorithmic differentiation
Actively maintained. Last release 3 days ago, commits in 10 of the last 26 weeks. A safe choice.
pip install sparsediffpySparseDiffPy
Sparse Jacobians and Hessians of nonlinear expressions, computed by
SparseDiffEngine,
a C library that works out the sparsity pattern once and then only computes
the structural nonzeros. Results are scipy.sparse.csr_matrix.
Installation
pip install sparsediffpy
From source: git clone --recursive https://github.com/SparseDifferentiation/SparseDiffPy && pip install -e SparseDiffPy.
Quick start
import numpy as np
import sparsediffpy as sp
scope = sp.Scope() # owns the flat variable vector
x = scope.Variable(3, 1) # shapes are always 2-D: (rows, cols)
f = sp.exp(x) + 2.0 * x # build an expression with operators and sp.* atoms
fn = sp.compile(f) # analyze sparsity once
x.value = [1.0, 2.0, 3.0]
print(fn.forward()) # [[4.718] [11.389] [26.086]], shaped like f
print(fn.jacobian().toarray()) # diag(exp(x) + 2), a 3x3 csr_matrix
print(fn.hessian(np.ones(3))) # Hessian of w' f(x) for weights w
forward() has the shape of f, jacobian() has shape (f.size, n_vars)
and hessian(w) has shape (n_vars, n_vars), where n_vars is the total
size of all variables in the scope, in declaration order. Values must have
the exact shape of what they set: x.value takes an array shaped like x,
hessian(w) takes w shaped like f (for vectors a 1-D array also works),
and flat vectors such as scope.set_values(u) must be 1-D. Flat vectors (the
rows of the Jacobian, the scope values) are column-major. Reading x.value
gives a read-only copy, so assign to x.value to change it.
Parameters are data you can change without recompiling:
import numpy as np
import sparsediffpy as sp
scope = sp.Scope()
x = scope.Variable(3, 1)
A = scope.Parameter(2, 3, value=np.ones((2, 3)))
fn = sp.compile(sp.sin(A @ x))
x.value = [0.1, 0.2, 0.3]
J1 = fn.jacobian().copy() # keep this Jacobian (see below)
A.value = np.arange(6.0).reshape(2, 3) # no recompile needed
J2 = fn.jacobian()
jacobian() and hessian(w) each return the same csr_matrix on every call. Its
sparsity pattern is fixed and its values are refreshed in place, so an evaluation
builds and copies nothing. The next evaluation overwrites the values: call
on a result you want to keep, as for above.