Prev Next sparse_hes_pattern_xam.m Headings

@(@\newcommand{\B}[1]{ {\bf #1} } \newcommand{\R}[1]{ {\rm #1} }@)@
Octave: Hessian Sparsity Patterns: Example and Test
function ok = sparse_hes_pattern_xam()
     %
     % load the Cppad Swig library
     m_cppad
     %
     % initialize return variable
     ok = true;
     % -----------------------------------------------------------------------
     % number of dependent and independent variables
     n = 3;
     %
     % create the independent variables ax
     x = m_cppad.vec_double(n);
     for i = [ 0 :(n -1) ]
          x(i) = i + 2.0;
     end
     ax = m_cppad.independent(x);
     %
     % create dependent variables ay with ay[i] = ax[j] * ax[i]
     % where i = mod(j + 1, n)
     ay = m_cppad.vec_a_double(n);
     for j = [ 0 :(n -1) ]
          i = j+1;
          if( i >= n  )
               i = i - n;
          end
          ay_i = ax(i) * ax(j);
          ay(i) = ay_i;
     end
     %
     % define af corresponding to f(x)
     af = m_cppad.a_fun(ax, ay);
     %
     % Set select_d (domain) to all true, initial select_r (range) to all false
     select_d = m_cppad.vec_bool(n);
     select_r = m_cppad.vec_bool(n);
     for i = [ 0 :(n-1) ]
          select_d(i) = true;
          select_r(i) = false;
     end
     %
     % only select component 0 of the range function
     % f_0 (x) = x_0 * x_{n-1}
     select_r(0) = true;
     %
     % loop over forward and reverse mode
     for mode = [ 0 :(2-1) ]
          pat_out = m_cppad.sparse_rc();
          if( mode == 0  )
               af.for_hes_sparsity(select_d, select_r, pat_out);
          end
          if( mode == 1  )
               af.rev_hes_sparsity(select_d, select_r, pat_out);
          end
          %
          % check that result is sparsity pattern for Hessian of f_0 (x)
          ok = ok && pat_out.nnz() == 2 ;
          row = pat_out.row();
          col = pat_out.col();
          for k = [ 0 :(2-1) ]
               r = row(k);
               c = col(k);
               if( r <= c  )
                    ok = ok && r == 0;
                    ok = ok && c == n-1;
               end
               if( r >= c  )
                    ok = ok && r == n-1;
                    ok = ok && c == 0;
               end
          end
     end
     %
     return;
end

Input File: build/lib/example/octave/sparse_hes_pattern_xam.m