kaskr / adcomp

AD computation with Template Model Builder (TMB)
Other
178 stars 81 forks source link

Missing numeric_limits specialization #398

Closed kaskr closed 1 month ago

kaskr commented 3 months ago

This issue was discovered on https://github.com/openpharma/mmrm/issues/462

Description

Some Eigen algorithms (e.g. LDL factorization) require std::numeric_limits<Type> to work for Type. TMB does not have such a specialization when using framework="TMBad".

Example

numlim.cpp

#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
  std::cout << std::numeric_limits<Type>::is_specialized << "\n";
  std::cout << std::numeric_limits<Type>::min() << "\n";
  return 0;
}

numlim.R

library(TMB)
compile("numlim.cpp", framework="TMBad")
dyn.load(dynlib("numlim"))
data <- list()
parameters <- list()
obj <- MakeADFun(data, parameters, DLL="numlim")

Output

## for double type
1
2.22507e-308
## for AD type there's no specialization and the value is 'random'
0
{const=6.63317e-143}

Solution

Adding the missing specialization, e.g. like this, seems to work:

#include <TMB.hpp>
namespace std {
  template<>
  struct numeric_limits<TMBad::ad_aug> : numeric_limits<double> { };
}