-
I want to compute Jacobian of a function The source code: #include <iostream> // standard input/output
#include <cppad/cppad.hpp> // the CppAD package
// main program
int main(void)
{
using CppAD::AD;
using CppAD::ADFun;
using CppAD::Independent;
size_t n = 1;
size_t m = 1;
size_t k = 1;
CPPAD_TESTVECTOR(AD<double>) ax(n), ay(m), ap(k);
ap[0] = AD<double>(4.0);
Independent(ax, ap);
ay[0] = ap[0] * ax[0] * ax[0];
ADFun<double> f(ax, ay);
ADFun<AD<double>, double> af = f.base2ad();
Independent(ax, ap);
CPPAD_TESTVECTOR(AD<double>) az(m * n);
az = af.Jacobian(ax);
ADFun<double> g;
g.Dependent(ax, az);
g.function_name_set("g");
g.optimize("no_compare_op");
std::string c_type = "double";
g.to_csrc(std::cout, c_type);
} The output: // includes
# include <stddef.h>
# include <math.h>
// typedefs
typedef double float_point_t;
// externals
// azmul
static float_point_t azmul(float_point_t x, float_point_t y)
{ if( x == 0.0 ) return 0.0;
return x * y;
}
// sign
static float_point_t sign(float_point_t x)
{ if( x > 0.0 ) return 1.0;
if( x == 0.0 ) return 0.0;
return -1.0;
}
// This JIT function
__declspec(dllexport) int __cdecl cppad_jit_g(
size_t nx ,
const float_point_t* x ,
size_t ny ,
float_point_t* y ,
size_t* compare_change )
{ // begin function body
// declare variables
float_point_t v[7];
size_t i;
// check nx, ny
if( nx != 2) return 1;
if( ny != 1) return 2;
// initialize
v[0] = NAN; // const
// independent variables
// set v[1+i] for i = 0, ..., nx-1
for(i = 0; i < nx; ++i)
v[1+i] = x[i];
// constants
// set v[1+nx+i] for i = 0, ..., nc-1
// nc = 2
v[1+nx+0] = 4;
v[1+nx+1] = 0;
// result nodes
// set v[1+nx+nc+i] for i = 0, ..., n_result_node-1
// n_result_node = 2
v[5] = v[3] * v[2];
v[6] = v[5] + v[5];
// dependent variables
// set y[i] for i = 0, ny-1
y[0] = v[6];
return 0;
} The value of Could you give some advice? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
Could you post a fully complete working example please? |
Beta Was this translation helpful? Give feedback.
-
I think this is what you want, please check the results and see that it works for you.
|
Beta Was this translation helpful? Give feedback.
-
Does this make the code above clear to you ? |
Beta Was this translation helpful? Give feedback.
-
@metab0t @a-jp I forgot that both the dynamic parameters and the variables are in the jit function. The dynamic parameters come first. I suggest you look at the file dynamic.c (created by this example). Also, see the heading 03-06 on |
Beta Was this translation helpful? Give feedback.
I think this is what you want, please check the results and see that it works for you.