AutomaticDifferentiation/AutomaticDifferentiation_dynamic.hpp

44 lines
2.6 KiB
C++
Executable file

#ifndef DEF_AUTOMATIC_DIFFERENTIATION_DYNAMIC
#define DEF_AUTOMATIC_DIFFERENTIATION_DYNAMIC
#undef __Dual_DualBase
#undef __Dual_VectorT
#undef __Dual_bdynamic
#define __Dual_DualBase DualD
#define __Dual_VectorT Eigen::Array<Scalar, -1, 1>
#define __Dual_bdynamic 1
#include "AutomaticDifferentiation_base.hpp"
/// Macro to create a function object that returns the gradient of the function at X.
/// Suitable for functions that take an N-dimensional vector and return a scalar.
/// This version uses dynamically allocated arrays for everything (Dual and vectors to and from the function).
/// Designed to work with functions, lambdas, etc.
#define CREATE_GRAD_FUNCTION_OBJECT_N_1_D(Func, GradFuncName, N) \
template<typename Scalar> \
struct GradFuncName { \
using ArrayOfScalar = Eigen::Array<Scalar, -1, 1>; \
using ArrayOfDual = Eigen::Array<DualD<Scalar,N>, -1, 1>; \
\
ArrayOfScalar operator()(ArrayOfScalar const& x) { \
Scalar fx; \
ArrayOfScalar gradfx; \
get_f_grad(x, fx, gradfx); \
return gradfx; \
} \
void get_f_grad(ArrayOfScalar const& x, Scalar & fx, ArrayOfScalar & gradfx) { \
ArrayOfDual X(N); \
for(int i = 0 ; i < N ; i++) \
{ \
X[i] = x[i]; \
X[i].diff(i); \
} \
auto Y = Func<DualD<Scalar,N>>(X); \
gradfx.resize(N); \
for (int i = 0; i < N; i++) \
gradfx[i] = Y.d(i); \
fx = Y.x(); \
} \
}
#endif