Search code examples
drake

Autodiff wrt time in Drake


In the example given in the Drake documentation https://drake.mit.edu/doxygen_cxx/group__system__scalar__conversion.html, we are able to take Autodiff derivatives with respect to states (specifically theta in this case). Is there an easy way to take derivatives with respect to time? My current thought is to append time to the state vector from get_mutable_continuous_state_vector(), but that seems a bit hacky?


Solution

  • You would set the time variable to have a one in the derivative. E.g.

    auto autodiff_plant = System<double>::ToAutoDiffXd(*plant);
    auto autodiff_context = autodiff_plant->CreateDefaultContext();
    autodiff_context->SetTimeStateAndParametersFrom(*context);
    autodiff_plant->FixInputPortsFrom(*plant, *context, autodiff_context.get());
    // Differentiate with respect to theta by setting dtheta/dtheta = 1.0.
    constexpr int kNumDerivatives = 1;
    autodiff_context->SetTime(initializeAutoDiffXd(initial_time));
    

    then, the output of computations using that context will have the derivative taking with respect to time.