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.