Skip to content
João Rui Leal edited this page May 20, 2014 · 25 revisions

Welcome to the CppADCodeGen wiki!

CppADCodeGen aims to extend the CppAD library in order to perform hybrid automatic differentiation, that is, to use operator overloading and produce source code.

Some of the key features of this library include:

  • source code generation for any CppAD method;
  • production of human readable source code;
  • source code generation for multiple languages;
  • elimination of any unneeded operation/variable.

Currently, only support for the C language has been developed, however new languages can be easily added in the future. A graph like representation of operations is generated independently from the source code generation methods which allows to produce source code for different languages.

There are some additional classes that help generate and compile source code for Linux. Please see the Linux page for an example.

A generic program used to generate source code can be written as:

#include <iosfwd>
#include <vector>
#include <cppadcg/cg.hpp>

using namespace CppAD;

int main(void) {
    // use a special object for source code generation
    typedef CG<double> CGD;
    typedef AD<CGD> ADCG;

    // independent variable vector
    CppAD::vector<ADCG> U(2);
    U[0] = 2.;
    U[1] = 3.;
    Independent(U);

    // dependent variable vector 
    CppAD::vector<ADCG> Z(1);

    // the model
    ADCG a = U[0] / 1. + U[1] * U[1];
    Z[0] = a / 2;

    ADFun<CGD> fun(U, Z); // the model tape

    /**
     * start the special steps for source code generation
     * for a Jacobian
     */
    CodeHandler<double> handler;

    CppAD::vector<CGD> indVars(2);
    handler.makeVariables(indVars);

    CppAD::vector<CGD> jac = fun.SparseJacobian(indVars);

    CLanguage<double> langC("double");
    CLangDefaultVariableNameGenerator<double> nameGen;

    std::ostringstream code;
    handler.generateCode(code, langC, jac, nameGen);
    std::cout << code.str();
}

The output of this function is:

   dep[1] = 0.5 * ind[1] + 0.5 * ind[1];
   // dependent variables without operations
   dep[0] = 0.5;
Clone this wiki locally