How to pre-allocate space for intermediate computation values within DynamicAutoDiffCostFunction?

73 Views Asked by At

I am using Ceres Solver for the non-linear least squares optimization of a model for which the number of parameters is not known at compile time. Because the number of parameters is not known at compile time, I implement the computation of the cost function and the corresponding automatic differentiation using the DynamicAutoDiffCostFunction class as described in http://ceres-solver.org/nnls_modeling.html#dynamicautodiffcostfunction. This cost function looks roughly like this:

class MyCostFunctor {
private:
  unsigned int num_parameters;
  const Measurement &meas;
public:
  MyCostFunctor (unsigned int num_parameters, const Measurement &meas)
    : num_parameters(num_parameters), meas(meas) {}

  template<typename T>
  bool operator()(T const* const* parameters, T* residuals) const {
    T *transformed_parameters = new [transformed_space_dim(num_parameters)];

    TransformParams<T> (parameters[0], num_parameters, transformed_parameters);
    ComputeResiduals<T> (transformed_parameters, num_parameters, meas, residuals);

    delete[] transformed_parameters;
  }
}

where the function TransformParams transforms the parameters to a different space, which is then used by ComputeResiduals to compute the residuals.

The code above sketches the idea of what I want to compute. However, it would be very inefficient to allocate and free the memory (pointed to by transformed_parameters) to represent the model in its intermediate parameter space, every time the residuals are computed. Therefor I would like to allocate this memory in the constructor of MyCostFunctor. The problem with that, is that the parameters of the intermediate results should be of type T, which is a template parameter of the operator() method.

Since I cannot come up with a solution (one, that is not dirty) how to implement a pre-allocation of the transformed_parameters array, I am wondering if someone else has a nice solution to my problem.

0

There are 0 best solutions below