Automatic Differentiation
 
Loading...
Searching...
No Matches
check_simplex.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_ERR_CHECK_SIMPLEX_HPP
2#define STAN_MATH_PRIM_ERR_CHECK_SIMPLEX_HPP
3
12#include <sstream>
13#include <string>
14
15namespace stan {
16namespace math {
17
33template <typename T, require_matrix_t<T>* = nullptr>
34void check_simplex(const char* function, const char* name, const T& theta) {
35 using std::fabs;
36 check_nonzero_size(function, name, theta);
37 auto&& theta_ref = to_ref(value_of_rec(theta));
38 if (!(fabs(1.0 - theta_ref.sum()) <= CONSTRAINT_TOLERANCE)) {
39 [&]() STAN_COLD_PATH {
40 std::stringstream msg;
41 scalar_type_t<T> sum = theta_ref.sum();
42 msg << "is not a valid simplex.";
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, 1.0, msg_str.c_str());
47 }();
48 }
49 for (Eigen::Index n = 0; n < theta_ref.size(); n++) {
50 if (!(theta_ref.coeff(n) >= 0)) {
51 [&]() STAN_COLD_PATH {
52 std::ostringstream msg;
53 msg << "is not a valid simplex. " << name << "["
54 << n + stan::error_index::value << "]"
55 << " = ";
56 std::string msg_str(msg.str());
57 throw_domain_error(function, name, theta_ref.coeff(n), msg_str.c_str(),
58 ", but should be greater than or equal to 0");
59 }();
60 }
61 }
62}
63
80template <typename T, require_std_vector_t<T>* = nullptr>
81void check_simplex(const char* function, const char* name, const T& theta) {
82 for (size_t i = 0; i < theta.size(); ++i) {
83 check_simplex(function, internal::make_iter_name(name, i).c_str(),
84 theta[i]);
85 }
86}
87
88} // namespace math
89} // namespace stan
90#endif
#define STAN_COLD_PATH
auto make_iter_name(const char *name)
double value_of_rec(const fvar< T > &v)
Return the value of the specified variable.
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.
void check_simplex(const char *function, const char *name, const T &theta)
Throw an exception if the specified vector is not a simplex.
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
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.
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 ...