[modernize] Modernize internal autodiff and numeric_diff logic

Refactor the core automatic and numeric differentiation internal helpers
to utilize C++17 features for improved readability and maintainability:

- Added IntegerSequenceTraits to provide a uniform compile-time interface
  for accessing head and tail of std::integer_sequence.
- Eliminated recursive template meta-programming in autodiff.h, replacing
  it with fold expressions and std::index_sequence.
- Simplified core helper functions like Make1stOrderPerturbation into
  unrolled loops.
- Refactored EvaluateJacobianForParameterBlocks from a recursive struct
  to a recursive function template using if constexpr.
- Updated NumericDiffCostFunction and NumericDiffFirstOrderFunction
  to use the modernized internal helper API.

Change-Id: I934034f7434fc05a8855565b2b534d325f920584
This commit is contained in:
Sameer Agarwal
2026-03-17 14:48:19 -07:00
parent 3d1b494dce
commit 2f946a582a
4 changed files with 145 additions and 178 deletions
@@ -148,9 +148,10 @@ class NumericDiffFirstOrderFunction final : public FirstOrderFunction {
explicit NumericDiffFirstOrderFunction(FirstOrderFunctor* functor,
Ownership ownership = TAKE_OWNERSHIP)
: NumericDiffFirstOrderFunction(std::unique_ptr<FirstOrderFunctor>(functor),
kNumParameters,
ownership) {
: NumericDiffFirstOrderFunction(
std::unique_ptr<FirstOrderFunctor>(functor),
kNumParameters,
ownership) {
static_assert(kNumParameters != DYNAMIC,
"When kNumParameters is DYNAMIC, the number of parameters "
"must be provided as a constructor argument.");
@@ -209,14 +210,16 @@ class NumericDiffFirstOrderFunction final : public FirstOrderFunction {
&parameters_ptr,
gradient);
} else {
return internal::EvaluateJacobianForParameterBlocks<
internal::StaticParameterDims<kNumParameters>>::
template Apply<kMethod, 1>(functor_.get(),
cost,
options_,
kNumResiduals,
&parameters_ptr,
&gradient);
using ParameterDims = internal::StaticParameterDims<kNumParameters>;
return internal::EvaluateJacobianForParameterBlocks<kMethod,
kNumResiduals,
ParameterDims>(
functor_.get(),
cost,
options_,
kNumResiduals,
&parameters_ptr,
&gradient);
}
}
@@ -225,10 +228,11 @@ class NumericDiffFirstOrderFunction final : public FirstOrderFunction {
const FirstOrderFunctor& functor() const { return *functor_; }
private:
explicit NumericDiffFirstOrderFunction(std::unique_ptr<FirstOrderFunctor> functor,
Ownership ownership,
int num_parameters,
const NumericDiffOptions& options)
explicit NumericDiffFirstOrderFunction(
std::unique_ptr<FirstOrderFunctor> functor,
Ownership ownership,
int num_parameters,
const NumericDiffOptions& options)
: functor_(std::move(functor)),
num_parameters_(num_parameters),
ownership_(ownership),