TMB Documentation  v1.9.11
distributions.hpp
1 namespace robust_utils {
2 
3  using namespace atomic::tiny_ad;
4 
5  // logspace_add
6  // template<class T>
7  // T fmax2(T x, T y) {return (x < y) ? y : x;}
8  template<class T>
9  T logspace_add (const T &logx, const T &logy) {
10  // Was:
11  // fmax2 (logx, logy) + log1p (exp (-fabs (logx - logy)));
12  return ( logx < logy ?
13  logy + log1p (exp (logx - logy)) :
14  logx + log1p (exp (logy - logx)) );
15  }
16  // logspace_sub
17  template<class T>
18  T R_Log1_Exp (const T &x) {
19  return ((x) > -M_LN2 ? log(-expm1(x)) : log1p(-exp(x))) ;
20  }
21  template<class T>
22  T logspace_sub (const T &logx, const T &logy) {
23  return logx + R_Log1_Exp(logy - logx);
24  }
25 
46  template <class Float>
47  inline Float dnbinom_robust(const Float &x,
48  const Float &log_mu,
49  const Float &log_var_minus_mu,
50  int give_log = 0) {
51  // Float p = mu / var;
52  // Float n = mu * p / (1. - p);
53  Float log_var = logspace_add( log_mu, log_var_minus_mu );
54  Float log_p = log_mu - log_var;
55  Float log_n = 2 * log_mu - log_var_minus_mu;
56  Float n = exp(log_n); // NB: exp(log_n) could over/underflow
57  Float logres = n * log_p;
58  if (x != 0) {
59  Float log_1mp = log_var_minus_mu - log_var;
60  logres += lgamma(x + n) - lgamma(n) - lgamma(x + 1.) + x * log_1mp;
61  }
62  return ( give_log ? logres : exp(logres) );
63  }
64 
80  template<class Float>
81  Float dbinom_robust(Float k, Float size, Float logit_p, int give_log=0)
82  {
83  Float zero = 0;
84  Float log_p = -logspace_add( zero , Float(-logit_p) );
85  Float log_1mp = -logspace_add( zero , logit_p );
86  Float logres = k * log_p + (size-k) * log_1mp;
87  return ( give_log ? logres : exp(logres) );
88  }
89 
90 }
Type lgamma(Type x)
Logarithm of gamma function (following R argument convention).
Definition: lgamma.hpp:12
Type dbinom_robust(Type k, Type size, Type logit_p, int give_log=0)
Density of binomial distribution parameterized via logit(prob)
Type dnbinom_robust(const Type &x, const Type &log_mu, const Type &log_var_minus_mu, int give_log=0)
Negative binomial probability function.
Definition: lgamma.hpp:103
Type logspace_add(Type logx, Type logy)
Addition in log-space.
Type logspace_sub(Type logx, Type logy)
Subtraction in log-space.
License: GPL v2