joaoleal / CppADCodeGen

Source Code Generation for Automatic Differentiation using Operator Overloading
Other
167 stars 37 forks source link

Option to declare loops explicitly #10

Open jcarius opened 6 years ago

jcarius commented 6 years ago

Hi, I have a number of for loops in my algorithm. They have a fixed iteration number, hence work perfectly fine with CppAD codegen, but they produce a lot of (unnecessary?) temporary variables in the generated code and massively bloat the size of the code.

Is there a way to declare such for loops explicitly to CppADGC such that it results also in loop expressions in the generated code? I found some references to loops in CppADCodeGen/include/cppad/cg/model/patterns , but I'm not sure if it's for this purpose.

A tiny example how to use such functionality would be great :) Thank you!

joaoleal commented 6 years ago

Hi,

You can create loops with CppADCodeGen. Unfortunately, they cannot be defined explicitly. CppADCodeGen can, however, attempt to detect these loops (and reuse temporary variables) if you provide some hints to CppADCodeGen. The key method is:

ModelCSourceGen<double> compModelH(fun, "model");
compModelH.setRelatedDependents(relatedDep);

CppadCodeGen will detect and then create loops in the generated source code if each iteration is independent, that is, if the results from one iteration are not used by the next to determine dependent variable. That is, if it is possible to write something like:

for (i=0; i<n; ++i) y[i] = f(x, i)

Please see an example at: https://github.com/joaoleal/CppADCodeGen/blob/master/example/patterns.cpp Note that the model used in this example could have been writen in a for loop. There are some tests with additional (not so easy to read) examples at: https://github.com/joaoleal/CppADCodeGen/tree/master/test/cppad/cg/patterns

An alternative way of reducing the amount of source code is by creating an atomic function with the body of the for loop. There are some tests using atomic functions at: https://github.com/joaoleal/CppADCodeGen/tree/master/test/cppad/cg/models