/* %$$ $head Test Atomic Function$$ $srccode%cpp% */ bool set_sparsity(void) { bool ok = true; using CppAD::AD; using CppAD::NearEqual; double eps = 10. * std::numeric_limits<double>::epsilon(); /* %$$ $subhead Constructor$$ $srccode%cpp% */ // Create the atomic get_started object atomic_set_sparsity afun("atomic_set_sparsity"); /* %$$ $subhead Recording$$ $srccode%cpp% */ size_t n = 3; size_t m = 2; vector< AD<double> > ax(n), ay(m); for(size_t j = 0; j < n; j++) ax[j] = double(j + 1); // declare independent variables and start tape recording CppAD::Independent(ax); // call atomic function afun(ax, ay); // create f: x -> y and stop tape recording CppAD::ADFun<double> f; f.Dependent (ax, ay); // f(x) = x // check function value ok &= NearEqual(ay[0] , ax[2], eps, eps); ok &= NearEqual(ay[1] , ax[0] * ax[1], eps, eps); /* %$$ $subhead for_sparse_jac$$ $srccode%cpp% */ // correct Jacobian result set_vector check_s(m); check_s[0].insert(2); check_s[1].insert(0); check_s[1].insert(1); // compute and test forward mode { set_vector r(n), s(m); for(size_t i = 0; i < n; i++) r[i].insert(i); s = f.ForSparseJac(n, r); for(size_t i = 0; i < m; i++) ok &= s[i] == check_s[i]; } /* %$$ $subhead rev_sparse_jac$$ $srccode%cpp% */ // compute and test reverse mode { set_vector r(m), s(m); for(size_t i = 0; i < m; i++) r[i].insert(i); s = f.RevSparseJac(m, r); for(size_t i = 0; i < m; i++) ok &= s[i] == check_s[i]; } /* %$$ $subhead for_sparse_hes$$ $srccode%cpp% */ // correct Hessian result set_vector check_h(n); check_h[0].insert(1); check_h[1].insert(0); // compute and test forward mode { set_vector r(1), s(1), h(n); for(size_t i = 0; i < m; i++) s[0].insert(i); for(size_t j = 0; j < n; j++) r[0].insert(j); h = f.ForSparseHes(r, s); for(size_t i = 0; i < n; i++) ok &= h[i] == check_h[i]; } /* %$$ $subhead rev_sparse_hes$$ Note the previous call to $code ForSparseJac$$ above stored its results in $icode f$$. $srccode%cpp% */ // compute and test reverse mode { set_vector s(1), h(n); for(size_t i = 0; i < m; i++) s[0].insert(i); h = f.RevSparseHes(n, s); for(size_t i = 0; i < n; i++) ok &= h[i] == check_h[i]; } /* %$$ $subhead Test Result$$ $srccode%cpp% */ return ok; }