Tutorial

import sparsegrad

Testing installation

sparsegrad.test()
Running unit tests for sparsegrad
NumPy version 1.13.3
NumPy relaxed strides checking option: True
NumPy is installed in /usr/lib/python3.6/site-packages/numpy
Python version 3.6.4 (default, Dec 23 2017, 19:07:07) [GCC 7.2.1 20171128]
nose version 1.3.7
....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
----------------------------------------------------------------------
Ran 676 tests in 1.340s

OK
<nose.result.TextTestResult run=676 errors=0 failures=0>

Calculation of Jacobian

import numpy as np
import sparsegrad as ad
def function(x):
    return np.exp(-x**2)
x0=np.linspace(-1,1,5)

Calculate value and function gradient by forward mode automatic differentiation:

y=function(ad.forward.seed_sparse_gradient(x0))

Access function value:

y.value
array([ 0.36787944,  0.77880078,  1.        ,  0.77880078,  0.36787944])

Access gradient as sparse matrix:

y.dvalue.tocsr()
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>
print(y.dvalue.toarray())
[[ 0.73575888  0.          0.          0.          0.        ]
 [ 0.          0.77880078  0.          0.          0.        ]
 [ 0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.         -0.77880078  0.        ]
 [ 0.          0.          0.          0.         -0.73575888]]

Calculation of sparsity pattern

y=function(ad.forward.seed_sparsity(np.zeros_like(x0)))

Access positions of possible nonzeros in AIJ format:

y.sparsity.indices
array([0, 1, 2, 3, 4], dtype=int32)
y.sparsity.indptr
array([0, 1, 2, 3, 4, 5], dtype=int32)

Access positions of possible nonzeros as scipy CSR matrix:

y.sparsity.tocsr()
<5x5 sparse matrix of type '<class 'numpy.int64'>'
    with 5 stored elements in Compressed Sparse Row format>
print(y.sparsity.tocsr().toarray())
[[1 0 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]