|
Prev | Next | sparse_jac_pattern_xam.py | Headings |
def sparse_jac_pattern_xam() :
#
# load the Cppad Swig library
import py_cppad
#
# initialize return variable
ok = True
# ---------------------------------------------------------------------
# number of dependent and independent variables
n = 3
#
# create the independent variables ax
x = py_cppad.vec_double(n)
for i in range( n ) :
x[i] = i + 2.0
#
ax = py_cppad.independent(x)
#
# create dependent variables ay with ay[i] = ax[j]
# where i = mod(j + 1, n)
ay = py_cppad.vec_a_double(n)
for j in range( n ) :
i = j+1
if i >= n :
i = i - n
#
ay_i = ax[j]
ay[i] = ay_i
#
#
# define af corresponding to f(x)
af = py_cppad.a_fun(ax, ay)
#
# sparsity pattern for identity matrix
pat_in = py_cppad.sparse_rc()
pat_in.resize(n, n, n)
for k in range( n ) :
pat_in.put(k, k, k)
#
#
# loop over forward and reverse mode
for mode in range( 2 ) :
pat_out = py_cppad.sparse_rc()
if mode == 0 :
af.for_jac_sparsity(pat_in, pat_out)
#
if mode == 1 :
af.rev_jac_sparsity(pat_in, pat_out)
#
#
# check that result is sparsity pattern for Jacobian
ok = ok and n == pat_out.nnz()
col_major = pat_out.col_major()
row = pat_out.row()
col = pat_out.col()
for k in range( n ) :
ell = col_major[k]
r = row[ell]
c = col[ell]
i = c+1
if i >= n :
i = i - n
#
ok = ok and c == k
ok = ok and r == i
#
#
#
return( ok )
#