123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- #ifndef CERES_PUBLIC_AUTODIFF_FIRST_ORDER_FUNCTION_H_
- #define CERES_PUBLIC_AUTODIFF_FIRST_ORDER_FUNCTION_H_
- #include <memory>
- #include "ceres/first_order_function.h"
- #include "ceres/internal/eigen.h"
- #include "ceres/internal/fixed_array.h"
- #include "ceres/jet.h"
- #include "ceres/types.h"
- namespace ceres {
- template <typename FirstOrderFunctor, int kNumParameters>
- class AutoDiffFirstOrderFunction final : public FirstOrderFunction {
- public:
-
- explicit AutoDiffFirstOrderFunction(FirstOrderFunctor* functor)
- : functor_(functor) {
- static_assert(kNumParameters > 0, "kNumParameters must be positive");
- }
- bool Evaluate(const double* const parameters,
- double* cost,
- double* gradient) const override {
- if (gradient == nullptr) {
- return (*functor_)(parameters, cost);
- }
- using JetT = Jet<double, kNumParameters>;
- internal::FixedArray<JetT, (256 * 7) / sizeof(JetT)> x(kNumParameters);
- for (int i = 0; i < kNumParameters; ++i) {
- x[i].a = parameters[i];
- x[i].v.setZero();
- x[i].v[i] = 1.0;
- }
- JetT output;
- output.a = kImpossibleValue;
- output.v.setConstant(kImpossibleValue);
- if (!(*functor_)(x.data(), &output)) {
- return false;
- }
- *cost = output.a;
- VectorRef(gradient, kNumParameters) = output.v;
- return true;
- }
- int NumParameters() const override { return kNumParameters; }
- const FirstOrderFunctor& functor() const { return *functor_; }
- private:
- std::unique_ptr<FirstOrderFunctor> functor_;
- };
- }
- #endif
|