0

I'm trying to write the derivative of a two-argument function double response(double x, double y) using the boost autodiff API. This function returns the value of a matrix cell indexed by its arguments, therefore it cannot be made auto-differentiable in the usual ways.

As explained in section 5.3 of the manual, the solution in this case is to provide a manually-written implementation of the derivative. I can compute a second matrix with the derivative values, so this would work just fine for me; the problem is that I don't know how to write the differentiated function in terms of the autodiff API. The manual does include an example of a custom derivative function on a single variable (copied below for convenience):

template <typename RealType, size_t Order>
fvar<RealType, Order> cos(fvar<RealType, Order> const& cr) {
  using std::cos;
  using std::sin;
  using root_type = typename fvar<RealType, Order>::root_type;
  constexpr size_t order = fvar<RealType, Order>::order_sum;
  root_type const d0 = cos(static_cast<root_type>(cr));
  if constexpr (order == 0)
    return fvar<RealType, Order>(d0);
  else {
    root_type const d1 = -sin(static_cast<root_type>(cr));
    root_type const derivatives[4]{d0, d1, -d0, -d1};
    return cr.apply_derivatives(order, [&derivatives](size_t i) { return derivatives[i & 3]; });
  }
}

But it's unclear to me how this could be generalized for my double response(double x, double y) function, considering it could potentially be differentiated on either x, y or both of them.

xperroni
  • 2,606
  • 1
  • 23
  • 29
  • See [Example 2](https://www.boost.org/doc/libs/1_83_0/libs/math/doc/html/math_toolkit/autodiff.html#math_toolkit.autodiff.example-multiprecision). – Matt Aug 29 '23 at 14:39
  • Thanks, but that doesn't answer my question. Example 2 shows how to write a multi-argument differentiable function using autodiff primitives. What I need to know is how to write the derivative of a function that cannot be auto-differentiated using autodiff primitives. See section 5.3 of the manual. – xperroni Aug 29 '23 at 19:12
  • 1
    The [implementation for `atan2(y,x)`](https://github.com/boostorg/math/blob/develop/include/boost/math/differentiation/autodiff.hpp#L1652-L1677) gives an example for a function of two independent variables. If that doesn't help, can you provide an explicit simple example of `response(x,y)` along with the derivative values? Also, do you know what the maximum Order is? I.e. do you only need first order derivatives? – Matt Aug 30 '23 at 14:39

0 Answers0