Replies: 1 comment
-
Hi @jusevitch , below is a working code that achieves what you want. You'll need:
#include <iostream>
#include <autodiff/forward/dual/dual.hpp>
#include <autodiff/forward/dual/eigen.hpp>
using namespace autodiff;
using std::cout, std::endl;
auto f(ArrayXdual2nd const& x) -> dual2nd
{
return (x * x).sum();
}
auto g(ArrayXdual1st const& z) -> ArrayXdual1st
{
ArrayXdual2nd zz = z.cast<dual2nd>();
return gradient(f, wrt(zz), at(zz));
}
int main(int argc, char const *argv[])
{
ArrayXdual1st x(5);
x << 1,2,3,4,5;
cout << "g =\n" << g(x) << endl;
cout << "dgdx =\n" << jacobian(g, wrt(x), at(x)) << endl;
return 0;
}
//---------------------------
// Output
//---------------------------
// g =
// 2
// 4
// 6
// 8
// 10
// dgdx =
// 0 0 0 0 0
// 0 0 0 0 0
// 0 0 0 0 0
// 0 0 0 0 0
// 0 0 0 0 0 What does not work at the moment (and it will require some work from my side, which unfortunately I cannot do it in the coming weeks due to more pressing issues in other projects), is the combination of outer and nested derivative calculation. As you see above, the Jacobian of g is a zero matrix, which should be instead a diagonal matrix with twos (note my |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is it possible to compute gradients for functions that themselves compute gradients?
Here's a simple example:
Can autodiff compute$\nabla g(x)$ when $g(x)$ itself depends on the gradient $\nabla f(x)$ ?
For a more complicated real-world example, there's a method used in robotics / control theory called higher-order control barrier functions (here's a paper for anyone interested). These functions help ensure your robot stays inside some safe set (e.g. doesn't crash). Without diving too deep into the theory, there's a series of functions similar to the following:
...
At the end of the day I'm looking to compute the gradient$\nabla \psi_n$ , which is itself a function of multiple nested gradients.
I tried setting up the simple example at the top of this post, but errors were thrown when I simply tried to compute$g(x)$ (without attempting to compute $\nabla g(x)$ ).
Here's a MWE (collapsable)
Error message:
For what it's worth, the authors of ForwardDiff.jl (Julia programming language) had to work out a few details to get nested differentiation operating correctly. There's an old issue describing how they solved that problem.
Beta Was this translation helpful? Give feedback.
All reactions