Automatic Differentiation
 
Loading...
Searching...
No Matches
check_sum_to_zero.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_ERR_CHECK_SUM_TO_ZERO_HPP
2#define STAN_MATH_PRIM_ERR_CHECK_SUM_TO_ZERO_HPP
3
11#include <sstream>
12#include <string>
13
14namespace stan {
15namespace math {
16
30template <typename T, require_matrix_t<T>* = nullptr>
31inline void check_sum_to_zero(const char* function, const char* name,
32 const T& theta) {
33 using std::fabs;
34 // the size-zero case is technically a valid sum-to-zero vector,
35 // but it cannot be unconstrained to anything
36 check_nonzero_size(function, name, theta);
37 auto&& theta_ref = to_ref(value_of_rec(theta));
38 if (unlikely(!(fabs(theta_ref.sum()) <= CONSTRAINT_TOLERANCE))) {
39 [&]() STAN_COLD_PATH {
40 std::stringstream msg;
41 scalar_type_t<T> sum = theta_ref.sum();
42 msg << "does not sum to zero.";
43 msg.precision(10);
44 msg << " sum(" << name << ") = " << sum << ", but should be ";
45 std::string msg_str(msg.str());
46 throw_domain_error(function, name, 0.0, msg_str.c_str());
47 }();
48 }
49}
50
63template <typename T, require_std_vector_t<T>* = nullptr>
64inline void check_sum_to_zero(const char* function, const char* name,
65 const T& theta) {
66 for (size_t i = 0; i < theta.size(); ++i) {
67 check_sum_to_zero(function, internal::make_iter_name(name, i).c_str(),
68 theta[i]);
69 }
70}
71
72} // namespace math
73} // namespace stan
74#endif
#define STAN_COLD_PATH
#define unlikely(x)
auto make_iter_name(const char *name)
double value_of_rec(const fvar< T > &v)
Return the value of the specified variable.
void check_sum_to_zero(const char *function, const char *name, const T &theta)
Throw an exception if the specified vector does not sum to 0.
void throw_domain_error(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw a domain error with a consistently formatted message.
auto sum(const std::vector< T > &m)
Return the sum of the entries of the specified standard vector.
Definition sum.hpp:23
void check_nonzero_size(const char *function, const char *name, const T_y &y)
Check if the specified matrix/vector is of non-zero size.
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:18
const double CONSTRAINT_TOLERANCE
The tolerance for checking arithmetic bounds in rank and in simplexes.
fvar< T > fabs(const fvar< T > &x)
Definition fabs.hpp:16
typename scalar_type< T >::type scalar_type_t
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...