# Using the Stan Math C++ Library

#### Stan Development Team

#### 2026-09-01

# Using the StanHeaders Package from Other R Packages

The StanHeaders package contains no R functions. To use the Stan Math Library in other packages, it is often sufficient to specify

    LinkingTo: StanHeaders (>= 2.26.0), RcppParallel (>= 5.0.1)

in the DESCRIPTION file of another package and put something like

    CXX_STD = CXX17
    PKG_CXXFLAGS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::CxxFlags()") \
                   $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::CxxFlags()")
    PKG_LIBS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::RcppParallelLibs()") \
               $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::LdFlags()")

in the src/Makevars and src/Makevars.win files and put `GNU make` in the `SystemRequirements:` field of the package’s DESCRIPTION file. If, in addition, the other package needs to utilize the MCMC, optimization, variational inference, or parsing facilities of the Stan Library, then it is also necessary to include the `src` directory of StanHeaders in the other package’s `PKG_CXXFLAGS` in the src/Makevars and src/Makevars.win files with something like

    STANHEADERS_SRC = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "message()" \
      -e "cat(system.file('include', 'src', package = 'StanHeaders', mustWork = TRUE))" \
      -e "message()" | grep "StanHeaders")
    PKG_CXXFLAGS += -I"$(STANHEADERS_SRC)"

# Calling functions in the StanHeaders Package from R

The only exposed R function in the in the StanHeaders package is `stanFunction`, which can be used to call most functions in the Stan Math Library.

    example(stanFunction, package = "StanHeaders", run.dontrun = TRUE)
    #>
    #> stnFnc>   files <- dir(system.file("include", "stan", "math", "prim",
    #> stnFnc+                            package = "StanHeaders"),
    #> stnFnc+                pattern = "hpp$", recursive = TRUE)
    #>
    #> stnFnc>   functions <- sub("\\.hpp$", "",
    #> stnFnc+                    sort(unique(basename(files[dirname(files) != "."]))))
    #>
    #> stnFnc>   length(functions) # you could call most of these Stan functions
    #> [1] 932
    #>
    #> stnFnc>     log(sum(exp(exp(1)), exp(pi))) # true value
    #> [1] 3.645318
    #>
    #> stnFnc>     stanFunction("log_sum_exp", x = exp(1), y = pi)
    #> [1] 3.645318
    #>
    #> stnFnc>     args(log_sum_exp) # now exists in .GlobalEnv
    #> function (x, y)
    #> NULL
    #>
    #> stnFnc>     log_sum_exp(x = pi, y = exp(1))
    #> [1] 3.645318
    #>
    #> stnFnc>     # but log_sum_exp() was not defined for a vector or matrix
    #> stnFnc>     x <- c(exp(1), pi)
    #>
    #> stnFnc>     try(log_sum_exp(x))
    #> Error in log_sum_exp(x) : argument "y" is missing, with no default
    #>
    #> stnFnc>     stanFunction("log_sum_exp", x = x) # now it is
    #> [1] 3.645318
    #>
    #> stnFnc>     # log_sum_exp() is now also defined for a matrix
    #> stnFnc>     log_sum_exp(as.matrix(x))
    #> [1] 3.645318
    #>
    #> stnFnc>     log_sum_exp(t(as.matrix(x)))
    #> [1] 3.645318
    #>
    #> stnFnc>     log_sum_exp(rbind(x, x))
    #> [1] 4.338465
    #>
    #> stnFnc>     # but log_sum_exp() was not defined for a list
    #> stnFnc>     try(log_sum_exp(as.list(x)))
    #> Error in eval(ei, envir) :
    #>   Not compatible with requested type: [type=list; target=double].
    #>
    #> stnFnc>     stanFunction("log_sum_exp", x = as.list(x)) # now it is
    #> [1] 3.645318
    #>
    #> stnFnc>     # in rare cases, passing a nested list is needed
    #> stnFnc>     stanFunction("dims", x = list(list(1:3)))
    #> [1] 1 1 3
    #>
    #> stnFnc>     # functions of complex arguments work
    #> stnFnc>     stanFunction("eigenvalues", # different ordering than base:eigen()
    #> stnFnc+                  x = matrix(complex(real = 1:9, imaginary = pi),
    #> stnFnc+                             nrow = 3, ncol = 3))
    #> [1] -8.179880e-17+1.622085e-18i -8.612657e-01+4.854073e-01i  1.586127e+01+8.939371e+00i
    #>
    #> stnFnc>     # nullary functions work but are not that interesting
    #> stnFnc>     stanFunction("negative_infinity")
    #> [1] -Inf
    #>
    #> stnFnc>     # PRNG functions work by adding a seed argument
    #> stnFnc>     stanFunction("lkj_corr_rng", K = 3L, eta = 1)
    #>            [,1]       [,2]       [,3]
    #> [1,]  1.0000000 -0.1191310  0.3659245
    #> [2,] -0.1191310  1.0000000 -0.8277807
    #> [3,]  0.3659245 -0.8277807  1.0000000
    #>
    #> stnFnc>     args(lkj_corr_rng) # has a seed argument
    #> function (K, eta, random_seed = sample.int(.Machine$integer.max,
    #>     size = 1L))
    #> NULL

The `functions` object defined in this example lists the many Stan functions that could be called (if all their arguments are numeric, see `help(stanFunction, package = "StanHeaders")` for details)

    #>        [,1]                               [,2]
    #>   [1,] "Eigen"                            "LDLT_factor"
    #>   [2,] "Phi"                              "Phi_approx"
    #>   [3,] "StdVectorBuilder"                 "VectorBuilder"
    #>   [4,] "VectorBuilderHelper"              "abs"
    #>   [5,] "accumulator"                      "acos"
    #>   [6,] "acosh"                            "ad_promotable"
    #>   [7,] "add"                              "add_diag"
    #>   [8,] "algebra_solver_adapter"           "all"
    #>   [9,] "any"                              "append_array"
    #>  [10,] "append_col"                       "append_return_type"
    #>  [11,] "append_row"                       "apply"
    #>  [12,] "apply_scalar_binary"              "apply_scalar_ternary"
    #>  [13,] "apply_scalar_unary"               "apply_vector_unary"
    #>  [14,] "arg"                              "array_builder"
    #>  [15,] "as_array_or_scalar"               "as_bool"
    #>  [16,] "as_column_vector_or_scalar"       "as_value_array_or_scalar"
    #>  [17,] "as_value_column_array_or_scalar"  "as_value_column_vector_or_scalar"
    #>  [18,] "asin"                             "asinh"
    #>  [19,] "assign"                           "atan"
    #>  [20,] "atan2"                            "atanh"
    #>  [21,] "autocorrelation"                  "autocovariance"
    #>  [22,] "base_type"                        "bernoulli_ccdf_log"
    #>  [23,] "bernoulli_cdf"                    "bernoulli_cdf_log"
    #>  [24,] "bernoulli_lccdf"                  "bernoulli_lcdf"
    #>  [25,] "bernoulli_logit_glm_lpmf"         "bernoulli_logit_glm_rng"
    #>  [26,] "bernoulli_logit_lpmf"             "bernoulli_logit_rng"
    #>  [27,] "bernoulli_lpmf"                   "bernoulli_rng"
    #>  [28,] "bessel_first_kind"                "bessel_second_kind"
    #>  [29,] "beta"                             "beta_binomial_ccdf_log"
    #>  [30,] "beta_binomial_cdf"                "beta_binomial_cdf_log"
    #>  [31,] "beta_binomial_lccdf"              "beta_binomial_lcdf"
    #>  [32,] "beta_binomial_lpmf"               "beta_binomial_rng"
    #>  [33,] "beta_ccdf_log"                    "beta_cdf"
    #>  [34,] "beta_cdf_log"                     "beta_lccdf"
    #>  [35,] "beta_lcdf"                        "beta_lpdf"
    #>  [36,] "beta_neg_binomial_cdf"            "beta_neg_binomial_lccdf"
    #>  [37,] "beta_neg_binomial_lcdf"           "beta_neg_binomial_lpmf"
    #>  [38,] "beta_neg_binomial_rng"            "beta_proportion_ccdf_log"
    #>  [39,] "beta_proportion_cdf_log"          "beta_proportion_lccdf"
    #>  [40,] "beta_proportion_lcdf"             "beta_proportion_lpdf"
    #>  [41,] "beta_proportion_rng"              "beta_rng"
    #>  [42,] "binary_log_loss"                  "binomial_ccdf_log"
    #>  [43,] "binomial_cdf"                     "binomial_cdf_log"
    #>  [44,] "binomial_coefficient_log"         "binomial_lccdf"
    #>  [45,] "binomial_lcdf"                    "binomial_logit_glm_lpmf"
    #>  [46,] "binomial_logit_lpmf"              "binomial_lpmf"
    #>  [47,] "binomial_rng"                     "block"
    #>  [48,] "bool_constant"                    "boost_policy"
    #>  [49,] "broadcast_array"                  "categorical_logit_glm_lpmf"
    #>  [50,] "categorical_logit_lpmf"           "categorical_logit_rng"
    #>  [51,] "categorical_lpmf"                 "categorical_rng"
    #>  [52,] "cauchy_ccdf_log"                  "cauchy_cdf"
    #>  [53,] "cauchy_cdf_log"                   "cauchy_lccdf"
    #>  [54,] "cauchy_lcdf"                      "cauchy_lpdf"
    #>  [55,] "cauchy_rng"                       "cbrt"
    #>  [56,] "ceil"                             "check_2F1_converges"
    #>  [57,] "check_3F2_converges"              "check_bounded"
    #>  [58,] "check_cholesky_factor"            "check_cholesky_factor_corr"
    #>  [59,] "check_column_index"               "check_consistent_size"
    #>  [60,] "check_consistent_sizes"           "check_consistent_sizes_mvt"
    #>  [61,] "check_corr_matrix"                "check_cov_matrix"
    #>  [62,] "check_finite"                     "check_flag_sundials"
    #>  [63,] "check_greater"                    "check_greater_or_equal"
    #>  [64,] "check_ldlt_factor"                "check_less"
    #>  [65,] "check_less_or_equal"              "check_lower_triangular"
    #>  [66,] "check_matching_dims"              "check_matching_sizes"
    #>  [67,] "check_multiplicable"              "check_nonnegative"
    #>  [68,] "check_nonzero_size"               "check_not_nan"
    #>  [69,] "check_ordered"                    "check_pos_definite"
    #>  [70,] "check_pos_semidefinite"           "check_positive"
    #>  [71,] "check_positive_finite"            "check_positive_ordered"
    #>  [72,] "check_range"                      "check_row_index"
    #>  [73,] "check_simplex"                    "check_size_match"
    #>  [74,] "check_sorted"                     "check_square"
    #>  [75,] "check_std_vector_index"           "check_stochastic_column"
    #>  [76,] "check_stochastic_row"             "check_sum_to_zero"
    #>  [77,] "check_symmetric"                  "check_unit_vector"
    #>  [78,] "check_vector"                     "check_vector_index"
    #>  [79,] "chi_square_ccdf_log"              "chi_square_cdf"
    #>  [80,] "chi_square_cdf_log"               "chi_square_lccdf"
    #>  [81,] "chi_square_lcdf"                  "chi_square_lpdf"
    #>  [82,] "chi_square_rng"                   "chol2inv"
    #>  [83,] "cholesky_corr_constrain"          "cholesky_corr_free"
    #>  [84,] "cholesky_decompose"               "cholesky_factor_constrain"
    #>  [85,] "cholesky_factor_free"             "choose"
    #>  [86,] "col"                              "cols"
    #>  [87,] "columns_dot_product"              "columns_dot_self"
    #>  [88,] "common_container_type"            "compiler_attributes"
    #>  [89,] "complex_base"                     "complex_schur_decompose"
    #>  [90,] "conj"                             "conjunction"
    #>  [91,] "constants"                        "constraint_tolerance"
    #>  [92,] "contains_std_vector"              "contains_tuple"
    #>  [93,] "copysign"                         "corr_constrain"
    #>  [94,] "corr_free"                        "corr_matrix_constrain"
    #>  [95,] "corr_matrix_free"                 "cos"
    #>  [96,] "cosh"                             "coupled_ode_system"
    #>  [97,] "cov_exp_quad"                     "cov_matrix_constrain"
    #>  [98,] "cov_matrix_constrain_lkj"         "cov_matrix_free"
    #>  [99,] "cov_matrix_free_lkj"              "crossprod"
    #> [100,] "csr_extract"                      "csr_extract_u"
    #> [101,] "csr_extract_v"                    "csr_extract_w"
    #> [102,] "csr_matrix_times_vector"          "csr_to_dense_matrix"
    #> [103,] "csr_u_to_z"                       "cumulative_sum"
    #> [104,] "determinant"                      "diag_matrix"
    #> [105,] "diag_post_multiply"               "diag_pre_multiply"
    #> [106,] "diagonal"                         "digamma"
    #> [107,] "dims"                             "dirichlet_lpdf"
    #> [108,] "dirichlet_multinomial_lpmf"       "dirichlet_multinomial_rng"
    #> [109,] "dirichlet_rng"                    "discrete_range_ccdf_log"
    #> [110,] "discrete_range_cdf"               "discrete_range_cdf_log"
    #> [111,] "discrete_range_lccdf"             "discrete_range_lcdf"
    #> [112,] "discrete_range_lpmf"              "discrete_range_rng"
    #> [113,] "disjunction"                      "distance"
    #> [114,] "divide"                           "divide_columns"
    #> [115,] "domain_error"                     "domain_error_vec"
    #> [116,] "dot"                              "dot_product"
    #> [117,] "dot_self"                         "double_exponential_ccdf_log"
    #> [118,] "double_exponential_cdf"           "double_exponential_cdf_log"
    #> [119,] "double_exponential_lccdf"         "double_exponential_lcdf"
    #> [120,] "double_exponential_lpdf"          "double_exponential_rng"
    #> [121,] "eigen_comparisons"                "eigendecompose"
    #> [122,] "eigendecompose_sym"               "eigenvalues"
    #> [123,] "eigenvalues_sym"                  "eigenvectors"
    #> [124,] "eigenvectors_sym"                 "elementwise_check"
    #> [125,] "elt_divide"                       "elt_multiply"
    #> [126,] "erf"                              "erfc"
    #> [127,] "error_index"                      "eval"
    #> [128,] "exp"                              "exp2"
    #> [129,] "exp_mod_normal_ccdf_log"          "exp_mod_normal_cdf"
    #> [130,] "exp_mod_normal_cdf_log"           "exp_mod_normal_lccdf"
    #> [131,] "exp_mod_normal_lcdf"              "exp_mod_normal_lpdf"
    #> [132,] "exp_mod_normal_rng"               "expm1"
    #> [133,] "exponential_ccdf_log"             "exponential_cdf"
    #> [134,] "exponential_cdf_log"              "exponential_lccdf"
    #> [135,] "exponential_lcdf"                 "exponential_lpdf"
    #> [136,] "exponential_rng"                  "fabs"
    #> [137,] "factor_U"                         "factor_cov_matrix"
    #> [138,] "falling_factorial"                "fdim"
    #> [139,] "fft"                              "fill"
    #> [140,] "filter_map"                       "finite_diff_gradient"
    #> [141,] "finite_diff_gradient_auto"        "finite_diff_stepsize"
    #> [142,] "floor"                            "fma"
    #> [143,] "fmax"                             "fmin"
    #> [144,] "fmod"                             "for_each"
    #> [145,] "forward_as"                       "frechet_ccdf_log"
    #> [146,] "frechet_cdf"                      "frechet_cdf_log"
    #> [147,] "frechet_lccdf"                    "frechet_lcdf"
    #> [148,] "frechet_lpdf"                     "frechet_rng"
    #> [149,] "gamma_ccdf_log"                   "gamma_cdf"
    #> [150,] "gamma_cdf_log"                    "gamma_lccdf"
    #> [151,] "gamma_lcdf"                       "gamma_lpdf"
    #> [152,] "gamma_p"                          "gamma_q"
    #> [153,] "gamma_rng"                        "gaussian_dlm_obs_lpdf"
    #> [154,] "gaussian_dlm_obs_rng"             "generalized_inverse"
    #> [155,] "generate_laplace_options"         "get"
    #> [156,] "get_base1"                        "get_base1_lhs"
    #> [157,] "get_imag"                         "get_lp"
    #> [158,] "get_real"                         "gp_dot_prod_cov"
    #> [159,] "gp_exp_quad_cov"                  "gp_exponential_cov"
    #> [160,] "gp_matern32_cov"                  "gp_matern52_cov"
    #> [161,] "gp_periodic_cov"                  "grad_2F1"
    #> [162,] "grad_F32"                         "grad_pFq"
    #> [163,] "grad_reg_inc_beta"                "grad_reg_inc_gamma"
    #> [164,] "grad_reg_lower_inc_gamma"         "gumbel_ccdf_log"
    #> [165,] "gumbel_cdf"                       "gumbel_cdf_log"
    #> [166,] "gumbel_lccdf"                     "gumbel_lcdf"
    #> [167,] "gumbel_lpdf"                      "gumbel_rng"
    #> [168,] "hcubature"                        "head"
    #> [169,] "hmm_check"                        "hmm_hidden_state_prob"
    #> [170,] "hmm_latent_rng"                   "hmm_marginal"
    #> [171,] "holder"                           "hypergeometric_1F0"
    #> [172,] "hypergeometric_2F1"               "hypergeometric_2F2"
    #> [173,] "hypergeometric_3F2"               "hypergeometric_lpmf"
    #> [174,] "hypergeometric_pFq"               "hypergeometric_rng"
    #> [175,] "hypot"                            "i_times"
    #> [176,] "identity_constrain"               "identity_free"
    #> [177,] "identity_matrix"                  "if_else"
    #> [178,] "imag"                             "inc_beta"
    #> [179,] "inc_beta_dda"                     "inc_beta_ddb"
    #> [180,] "inc_beta_ddz"                     "include_summand"
    #> [181,] "index_apply"                      "index_type"
    #> [182,] "init_threadpool_tbb"              "initialize"
    #> [183,] "initialize_fill"                  "int_step"
    #> [184,] "integrate_1d"                     "integrate_1d_adapter"
    #> [185,] "integrate_ode_rk45"               "integrate_ode_std_vector_interface_adapter"
    #> [186,] "inv"                              "inv_Phi"
    #> [187,] "inv_chi_square_ccdf_log"          "inv_chi_square_cdf"
    #> [188,] "inv_chi_square_cdf_log"           "inv_chi_square_lccdf"
    #> [189,] "inv_chi_square_lcdf"              "inv_chi_square_lpdf"
    #> [190,] "inv_chi_square_rng"               "inv_cloglog"
    #> [191,] "inv_erfc"                         "inv_gamma_ccdf_log"
    #> [192,] "inv_gamma_cdf"                    "inv_gamma_cdf_log"
    #> [193,] "inv_gamma_lccdf"                  "inv_gamma_lcdf"
    #> [194,] "inv_gamma_lpdf"                   "inv_gamma_rng"
    #> [195,] "inv_inc_beta"                     "inv_logit"
    #> [196,] "inv_sqrt"                         "inv_square"
    #> [197,] "inv_wishart_cholesky_lpdf"        "inv_wishart_cholesky_rng"
    #> [198,] "inv_wishart_lpdf"                 "inv_wishart_rng"
    #> [199,] "invalid_argument"                 "invalid_argument_vec"
    #> [200,] "inverse"                          "inverse_softmax"
    #> [201,] "inverse_spd"                      "is_all_arithmetic"
    #> [202,] "is_any_nan"                       "is_arena_matrix"
    #> [203,] "is_autodiff"                      "is_base_pointer_convertible"
    #> [204,] "is_cholesky_factor"               "is_cholesky_factor_corr"
    #> [205,] "is_column_index"                  "is_complex"
    #> [206,] "is_constant"                      "is_container"
    #> [207,] "is_container_or_var_matrix"       "is_corr_matrix"
    #> [208,] "is_dense_dynamic"                 "is_detected"
    #> [209,] "is_double_or_int"                 "is_eigen"
    #> [210,] "is_eigen_dense_base"              "is_eigen_dense_dynamic"
    #> [211,] "is_eigen_matrix"                  "is_eigen_matrix_base"
    #> [212,] "is_eigen_sparse_base"             "is_floating_point"
    #> [213,] "is_fvar"                          "is_inf"
    #> [214,] "is_integer"                       "is_integral"
    #> [215,] "is_kernel_expression"             "is_ldlt_factor"
    #> [216,] "is_less_or_equal"                 "is_lower_triangular"
    #> [217,] "is_mat_finite"                    "is_matching_dims"
    #> [218,] "is_matching_size"                 "is_matrix"
    #> [219,] "is_matrix_cl"                     "is_nan"
    #> [220,] "is_nonpositive_integer"           "is_nonzero_size"
    #> [221,] "is_not_nan"                       "is_ordered"
    #> [222,] "is_plain_type"                    "is_pos_definite"
    #> [223,] "is_positive"                      "is_real"
    #> [224,] "is_rev_matrix"                    "is_scal_finite"
    #> [225,] "is_size_match"                    "is_square"
    #> [226,] "is_stan_scalar"                   "is_stan_scalar_or_eigen"
    #> [227,] "is_string_convertible"            "is_symmetric"
    #> [228,] "is_tuple"                         "is_uninitialized"
    #> [229,] "is_unit_vector"                   "is_var"
    #> [230,] "is_var_and_matrix_types"          "is_var_dense_dynamic"
    #> [231,] "is_var_eigen"                     "is_var_matrix"
    #> [232,] "is_var_or_arithmetic"             "is_vari"
    #> [233,] "is_vector"                        "is_vector_like"
    #> [234,] "isfinite"                         "isinf"
    #> [235,] "isnan"                            "isnormal"
    #> [236,] "iter_tuple_nested"                "lambert_w"
    #> [237,] "lb_constrain"                     "lb_free"
    #> [238,] "lbeta"                            "ldexp"
    #> [239,] "lgamma"                           "lgamma_stirling"
    #> [240,] "lgamma_stirling_diff"             "linspaced_array"
    #> [241,] "linspaced_int_array"              "linspaced_row_vector"
    #> [242,] "linspaced_vector"                 "lkj_corr_cholesky_lpdf"
    #> [243,] "lkj_corr_cholesky_rng"            "lkj_corr_lpdf"
    #> [244,] "lkj_corr_rng"                     "lkj_cov_lpdf"
    #> [245,] "lmgamma"                          "lmultiply"
    #> [246,] "log"                              "log10"
    #> [247,] "log1m"                            "log1m_exp"
    #> [248,] "log1m_inv_logit"                  "log1p"
    #> [249,] "log1p_exp"                        "log2"
    #> [250,] "log_determinant"                  "log_determinant_ldlt"
    #> [251,] "log_determinant_spd"              "log_diff_exp"
    #> [252,] "log_falling_factorial"            "log_gamma_q_dgamma"
    #> [253,] "log_inv_logit"                    "log_inv_logit_diff"
    #> [254,] "log_mix"                          "log_modified_bessel_first_kind"
    #> [255,] "log_rising_factorial"             "log_softmax"
    #> [256,] "log_sum_exp"                      "log_sum_exp_signed"
    #> [257,] "logb"                             "logical_and"
    #> [258,] "logical_eq"                       "logical_gt"
    #> [259,] "logical_gte"                      "logical_lt"
    #> [260,] "logical_lte"                      "logical_negation"
    #> [261,] "logical_neq"                      "logical_or"
    #> [262,] "logistic_ccdf_log"                "logistic_cdf"
    #> [263,] "logistic_cdf_log"                 "logistic_lccdf"
    #> [264,] "logistic_lcdf"                    "logistic_lpdf"
    #> [265,] "logistic_rng"                     "logit"
    #> [266,] "loglogistic_cdf"                  "loglogistic_lpdf"
    #> [267,] "loglogistic_rng"                  "lognormal_ccdf_log"
    #> [268,] "lognormal_cdf"                    "lognormal_cdf_log"
    #> [269,] "lognormal_lccdf"                  "lognormal_lcdf"
    #> [270,] "lognormal_lpdf"                   "lognormal_rng"
    #> [271,] "lub_constrain"                    "lub_free"
    #> [272,] "make_holder_tuple"                "make_iter_name"
    #> [273,] "make_nu"                          "map_if"
    #> [274,] "map_rect"                         "map_rect_combine"
    #> [275,] "map_rect_concurrent"              "map_rect_mpi"
    #> [276,] "map_rect_reduce"                  "matrix_exp"
    #> [277,] "matrix_exp_2x2"                   "matrix_exp_action_handler"
    #> [278,] "matrix_exp_multiply"              "matrix_exp_pade"
    #> [279,] "matrix_normal_prec_lpdf"          "matrix_normal_prec_rng"
    #> [280,] "matrix_power"                     "max"
    #> [281,] "max_size"                         "max_size_mvt"
    #> [282,] "mdivide_left"                     "mdivide_left_ldlt"
    #> [283,] "mdivide_left_spd"                 "mdivide_left_tri"
    #> [284,] "mdivide_left_tri_low"             "mdivide_right"
    #> [285,] "mdivide_right_ldlt"               "mdivide_right_spd"
    #> [286,] "mdivide_right_tri"                "mdivide_right_tri_low"
    #> [287,] "mean"                             "min"
    #> [288,] "minus"                            "modified_bessel_first_kind"
    #> [289,] "modified_bessel_second_kind"      "modify_eigen_options"
    #> [290,] "modulus"                          "mpi_cluster"
    #> [291,] "mpi_command"                      "mpi_distributed_apply"
    #> [292,] "mpi_parallel_call"                "multi_gp_cholesky_lpdf"
    #> [293,] "multi_gp_lpdf"                    "multi_normal_cholesky_lpdf"
    #> [294,] "multi_normal_cholesky_rng"        "multi_normal_lpdf"
    #> [295,] "multi_normal_prec_lpdf"           "multi_normal_prec_rng"
    #> [296,] "multi_normal_rng"                 "multi_student_t_cholesky_lpdf"
    #> [297,] "multi_student_t_cholesky_rng"     "multi_student_t_lpdf"
    #> [298,] "multi_student_t_rng"              "multinomial_logit_lpmf"
    #> [299,] "multinomial_logit_rng"            "multinomial_lpmf"
    #> [300,] "multinomial_rng"                  "multiply"
    #> [301,] "multiply_log"                     "multiply_lower_tri_self_transpose"
    #> [302,] "neg_binomial_2_ccdf_log"          "neg_binomial_2_cdf"
    #> [303,] "neg_binomial_2_cdf_log"           "neg_binomial_2_lccdf"
    #> [304,] "neg_binomial_2_lcdf"              "neg_binomial_2_log_glm_lpmf"
    #> [305,] "neg_binomial_2_log_lpmf"          "neg_binomial_2_log_rng"
    #> [306,] "neg_binomial_2_lpmf"              "neg_binomial_2_rng"
    #> [307,] "neg_binomial_ccdf_log"            "neg_binomial_cdf"
    #> [308,] "neg_binomial_cdf_log"             "neg_binomial_lccdf"
    #> [309,] "neg_binomial_lcdf"                "neg_binomial_lpmf"
    #> [310,] "neg_binomial_rng"                 "norm"
    #> [311,] "norm1"                            "norm2"
    #> [312,] "normal_ccdf_log"                  "normal_cdf"
    #> [313,] "normal_cdf_log"                   "normal_id_glm_lpdf"
    #> [314,] "normal_lccdf"                     "normal_lcdf"
    #> [315,] "normal_lpdf"                      "normal_rng"
    #> [316,] "normal_sufficient_lpdf"           "num_elements"
    #> [317,] "ode_ckrk"                         "ode_rk45"
    #> [318,] "ode_store_sensitivities"          "offset_multiplier_constrain"
    #> [319,] "offset_multiplier_free"           "one_hot_array"
    #> [320,] "one_hot_int_array"                "one_hot_row_vector"
    #> [321,] "one_hot_vector"                   "ones_array"
    #> [322,] "ones_int_array"                   "ones_row_vector"
    #> [323,] "ones_vector"                      "operands_and_partials"
    #> [324,] "operator_addition"                "operator_division"
    #> [325,] "operator_equal_equal"             "operator_minus"
    #> [326,] "operator_multiplication"          "operator_not_equal"
    #> [327,] "operator_plus"                    "operator_subtraction"
    #> [328,] "ordered_constrain"                "ordered_free"
    #> [329,] "ordered_logistic_glm_lpmf"        "ordered_logistic_lpmf"
    #> [330,] "ordered_logistic_rng"             "ordered_probit_lpmf"
    #> [331,] "ordered_probit_rng"               "out_of_range"
    #> [332,] "owens_t"                          "pareto_ccdf_log"
    #> [333,] "pareto_cdf"                       "pareto_cdf_log"
    #> [334,] "pareto_lccdf"                     "pareto_lcdf"
    #> [335,] "pareto_lpdf"                      "pareto_rng"
    #> [336,] "pareto_type_2_ccdf_log"           "pareto_type_2_cdf"
    #> [337,] "pareto_type_2_cdf_log"            "pareto_type_2_lccdf"
    #> [338,] "pareto_type_2_lcdf"               "pareto_type_2_lpdf"
    #> [339,] "pareto_type_2_rng"                "partials_propagator"
    #> [340,] "partials_return_type"             "partials_type"
    #> [341,] "plain_type"                       "plus"
    #> [342,] "poisson_binomial_ccdf_log"        "poisson_binomial_cdf"
    #> [343,] "poisson_binomial_cdf_log"         "poisson_binomial_lccdf"
    #> [344,] "poisson_binomial_lcdf"            "poisson_binomial_log_probs"
    #> [345,] "poisson_binomial_lpmf"            "poisson_binomial_rng"
    #> [346,] "poisson_ccdf_log"                 "poisson_cdf"
    #> [347,] "poisson_cdf_log"                  "poisson_lccdf"
    #> [348,] "poisson_lcdf"                     "poisson_log_glm_lpmf"
    #> [349,] "poisson_log_lpmf"                 "poisson_log_rng"
    #> [350,] "poisson_lpmf"                     "poisson_rng"
    #> [351,] "polar"                            "positive_constrain"
    #> [352,] "positive_free"                    "positive_ordered_constrain"
    #> [353,] "positive_ordered_free"            "possibly_sum"
    #> [354,] "pow"                              "primitive_value"
    #> [355,] "prob_constrain"                   "prob_free"
    #> [356,] "prod"                             "proj"
    #> [357,] "promote_args"                     "promote_elements"
    #> [358,] "promote_scalar"                   "promote_scalar_type"
    #> [359,] "pseudo_eigenvalues"               "pseudo_eigenvectors"
    #> [360,] "qr"                               "qr_Q"
    #> [361,] "qr_R"                             "qr_thin"
    #> [362,] "qr_thin_Q"                        "qr_thin_R"
    #> [363,] "quad_form"                        "quad_form_diag"
    #> [364,] "quad_form_sym"                    "quantile"
    #> [365,] "rank"                             "rayleigh_ccdf_log"
    #> [366,] "rayleigh_cdf"                     "rayleigh_cdf_log"
    #> [367,] "rayleigh_lccdf"                   "rayleigh_lcdf"
    #> [368,] "rayleigh_lpdf"                    "rayleigh_rng"
    #> [369,] "read_corr_L"                      "read_corr_matrix"
    #> [370,] "read_cov_L"                       "read_cov_matrix"
    #> [371,] "real"                             "reduce_sum"
    #> [372,] "reduce_sum_static"                "ref_type"
    #> [373,] "rep_array"                        "rep_matrix"
    #> [374,] "rep_row_vector"                   "rep_vector"
    #> [375,] "require_generics"                 "require_helpers"
    #> [376,] "resize"                           "return_type"
    #> [377,] "reverse"                          "rising_factorial"
    #> [378,] "round"                            "row"
    #> [379,] "rows"                             "rows_dot_product"
    #> [380,] "rows_dot_self"                    "scalar_seq_view"
    #> [381,] "scalar_type"                      "scalbn"
    #> [382,] "scale_matrix_exp_multiply"        "scaled_add"
    #> [383,] "scaled_inv_chi_square_ccdf_log"   "scaled_inv_chi_square_cdf"
    #> [384,] "scaled_inv_chi_square_cdf_log"    "scaled_inv_chi_square_lccdf"
    #> [385,] "scaled_inv_chi_square_lcdf"       "scaled_inv_chi_square_lpdf"
    #> [386,] "scaled_inv_chi_square_rng"        "sd"
    #> [387,] "segment"                          "select"
    #> [388,] "seq_view"                         "serializer"
    #> [389,] "sign"                             "signbit"
    #> [390,] "simplex_constrain"                "simplex_free"
    #> [391,] "sin"                              "singular_values"
    #> [392,] "sinh"                             "size"
    #> [393,] "size_mvt"                         "size_zero"
    #> [394,] "skew_double_exponential_ccdf_log" "skew_double_exponential_cdf"
    #> [395,] "skew_double_exponential_cdf_log"  "skew_double_exponential_lccdf"
    #> [396,] "skew_double_exponential_lcdf"     "skew_double_exponential_lpdf"
    #> [397,] "skew_double_exponential_rng"      "skew_normal_ccdf_log"
    #> [398,] "skew_normal_cdf"                  "skew_normal_cdf_log"
    #> [399,] "skew_normal_lccdf"                "skew_normal_lcdf"
    #> [400,] "skew_normal_lpdf"                 "skew_normal_rng"
    #> [401,] "softmax"                          "sort_asc"
    #> [402,] "sort_desc"                        "sort_indices"
    #> [403,] "sort_indices_asc"                 "sort_indices_desc"
    #> [404,] "sqrt"                             "square"
    #> [405,] "squared_distance"                 "stan_print"
    #> [406,] "static_select"                    "std_normal_ccdf_log"
    #> [407,] "std_normal_cdf"                   "std_normal_cdf_log"
    #> [408,] "std_normal_lccdf"                 "std_normal_lcdf"
    #> [409,] "std_normal_log_qf"                "std_normal_lpdf"
    #> [410,] "std_normal_rng"                   "step"
    #> [411,] "stochastic_column_constrain"      "stochastic_column_free"
    #> [412,] "stochastic_row_constrain"         "stochastic_row_free"
    #> [413,] "student_t_ccdf_log"               "student_t_cdf"
    #> [414,] "student_t_cdf_log"                "student_t_lccdf"
    #> [415,] "student_t_lcdf"                   "student_t_lpdf"
    #> [416,] "student_t_qf"                     "student_t_rng"
    #> [417,] "sub_col"                          "sub_row"
    #> [418,] "subtract"                         "sum"
    #> [419,] "sum_to_zero_constrain"            "sum_to_zero_free"
    #> [420,] "svd"                              "svd_U"
    #> [421,] "svd_V"                            "symmetrize_from_lower_tri"
    #> [422,] "symmetrize_from_upper_tri"        "system_error"
    #> [423,] "tail"                             "tan"
    #> [424,] "tanh"                             "tcrossprod"
    #> [425,] "tgamma"                           "throw_domain_error"
    #> [426,] "throw_domain_error_mat"           "throw_domain_error_vec"
    #> [427,] "to_array_1d"                      "to_array_2d"
    #> [428,] "to_complex"                       "to_int"
    #> [429,] "to_matrix"                        "to_ref"
    #> [430,] "to_row_vector"                    "to_vector"
    #> [431,] "trace"                            "trace_dot"
    #> [432,] "trace_gen_inv_quad_form_ldlt"     "trace_gen_quad_form"
    #> [433,] "trace_inv_quad_form_ldlt"         "trace_quad_form"
    #> [434,] "transpose"                        "trigamma"
    #> [435,] "trunc"                            "tuple_concat"
    #> [436,] "tuple_element"                    "tuple_size"
    #> [437,] "typedefs"                         "ub_constrain"
    #> [438,] "ub_free"                          "uniform_ccdf_log"
    #> [439,] "uniform_cdf"                      "uniform_cdf_log"
    #> [440,] "uniform_lccdf"                    "uniform_lcdf"
    #> [441,] "uniform_lpdf"                     "uniform_rng"
    #> [442,] "uniform_simplex"                  "unit_vector_constrain"
    #> [443,] "unit_vector_free"                 "unitspaced_array"
    #> [444,] "validate_non_negative_index"      "validate_positive_index"
    #> [445,] "validate_unit_vector_index"       "value_of"
    #> [446,] "value_of_rec"                     "value_type"
    #> [447,] "variance"                         "vec_concat"
    #> [448,] "vector_seq_view"                  "void_t"
    #> [449,] "von_mises_ccdf_log"               "von_mises_cdf"
    #> [450,] "von_mises_cdf_log"                "von_mises_lccdf"
    #> [451,] "von_mises_lcdf"                   "von_mises_lpdf"
    #> [452,] "von_mises_rng"                    "weibull_ccdf_log"
    #> [453,] "weibull_cdf"                      "weibull_cdf_log"
    #> [454,] "weibull_lccdf"                    "weibull_lcdf"
    #> [455,] "weibull_lpdf"                     "weibull_rng"
    #> [456,] "welford_covar_estimator"          "welford_var_estimator"
    #> [457,] "wiener4_lccdf_unnorm"             "wiener4_lcdf_unnorm"
    #> [458,] "wiener5_lpdf"                     "wiener_full_lccdf_unnorm"
    #> [459,] "wiener_full_lcdf_unnorm"          "wiener_full_lpdf"
    #> [460,] "wiener_lpdf"                      "wishart_cholesky_lpdf"
    #> [461,] "wishart_cholesky_rng"             "wishart_lpdf"
    #> [462,] "wishart_rng"                      "yule_simon_cdf"
    #> [463,] "yule_simon_lccdf"                 "yule_simon_lcdf"
    #> [464,] "yule_simon_lpmf"                  "yule_simon_rng"
    #> [465,] "zeros_array"                      "zeros_int_array"
    #> [466,] "zeros_row_vector"                 "zeros_vector"

# Using Higher-Order Functions in the StanHeaders Package

This section will demonstrate how to use some of the C++ functions in the StanHeaders package whose first argument is another C++ function, in which case the `stanFunction` in the previous section will not work and you have to write your own C++.

## Derivatives and Minimization

The following is a toy example of using the Stan Math library via `Rcpp::sourceCpp`: to minimize the function \[\left(\mathbf{x} - \mathbf{a}\right)^\top \left(\mathbf{x} - \mathbf{a}\right)\] which has a global minimum when \(\mathbf{x} = \mathbf{a}\). To find this minimum with autodifferentiation, we need to define the objective function. Then, its gradient with respect to \(\mathbf{x}\), which we know is \(2\left(\mathbf{x} - \mathbf{a}\right)\) in this case, can be calculated by autodifferentiation. At the optimum (or on the way to the optimum), we might want to evaluate the Hessian matrix, which we know is \(2\mathbf{I}\), but would need an additional function to evaluate it via autodifferentiation. Finally, one could reconceptualize the problem as solving a homogeneous system of equations where the gradient is set equal to a vector of zeros. The `stan::math::algebra_solver` function can solve such a system using autodifferentiation to obtain the Jacobian, which we know to be the identity matrix in this case.

    Sys.setenv(PKG_CXXFLAGS = StanHeaders:::CxxFlags(as_character = TRUE))
    SH <- system.file(ifelse(.Platform$OS.type == "windows", "libs", "lib"), .Platform$r_arch,
                      package = "StanHeaders", mustWork = TRUE)
    Sys.setenv(PKG_LIBS = paste0(StanHeaders:::LdFlags(as_character = TRUE),
                                 " -L", shQuote(SH), " -lStanHeaders"))

Here is C++ code that does all of the above, except for the part of finding the optimum, which is done using the R function `optim` below.

    // [[Rcpp::depends(BH)]]
    // [[Rcpp::depends(RcppEigen)]]
    // [[Rcpp::depends(RcppParallel)]]
    // [[Rcpp::depends(StanHeaders)]]
    #include <stan/math/mix.hpp> // stuff from mix/ must come first
    #include <stan/math.hpp>     // finally pull in everything from rev/ and prim/
    #include <Rcpp.h>
    #include <RcppEigen.h>       // do this AFTER including stuff from stan/math

    // [[Rcpp::plugins(cpp17)]]

    /* Objective function */

    // [[Rcpp::export]]
    auto f(Eigen::VectorXd x, Eigen::VectorXd a) { // objective function in doubles
      using stan::math::dot_self;                  // dot_self() is a dot product with self
      return dot_self( (x - a) );
    }

    /* Gradient */

    // [[Rcpp::export]]
    auto g(Eigen::VectorXd x, Eigen::VectorXd a) {  // gradient by AD using Stan
      double fx;
      Eigen::VectorXd grad_fx;
      using stan::math::dot_self;
      stan::math::gradient([&a](auto x) { return dot_self( (x - a) ); },
                           x, fx, grad_fx);
      return grad_fx;
    }

    /* Hessian */

    // [[Rcpp::export]]
    auto H(Eigen::VectorXd x, Eigen::VectorXd a) { // Hessian by AD using Stan
      double fx;
      Eigen::VectorXd grad_fx;
      Eigen::MatrixXd H;
      using stan::math::dot_self;
      stan::math::hessian([&a](auto x) { return dot_self(x - a); },
                          x, fx, grad_fx, H);
      return H;
    }

    /* Jacobian */

    // [[Rcpp::export]]
    auto J(Eigen::VectorXd x, Eigen::VectorXd a) { // not actually used
      Eigen::VectorXd fx;
      Eigen::MatrixXd J;
      using stan::math::dot_self;
      stan::math::jacobian([&a](auto x) {
        return (2 * (x - a));
      }, x, fx, J);
      return J;
    }

    struct equations_functor {
      template <typename T0, typename T1>
      inline Eigen::Matrix<T0, Eigen::Dynamic, 1>
      operator()(const Eigen::Matrix<T0, Eigen::Dynamic, 1>& x,
                 const Eigen::Matrix<T1, Eigen::Dynamic, 1>& theta,
                 const std::vector<double>& x_r, const std::vector<int>& x_i,
                 std::ostream* pstream__) const {
        return 2 * (x - stan::math::to_vector(x_r));
      }
    };

    // [[Rcpp::export]]
    auto solution(Eigen::VectorXd a, Eigen::VectorXd guess) {
      Eigen::VectorXd theta;
      auto x_r = stan::math::to_array_1d(a);
      equations_functor f;
      auto x = stan::math::algebra_solver(f, guess, theta, x_r, {});
      return x;
    }

In this compiled RMarkdown document, the knitr package has exported functions `f`, `g`, `H`, `J` and `solution` (but not `equations_functor`) to R’s global environment using the `sourceCpp` function in the Rcpp package, so that they can now be called from R. Here we find the optimum starting from a random point in three dimensions:

    x <- optim(rnorm(3), fn = f, gr = g, a = 1:3, method = "BFGS", hessian = TRUE)
    x$par
    #> [1] 1 2 3
    x$hessian
    #>      [,1] [,2] [,3]
    #> [1,]    2    0    0
    #> [2,]    0    2    0
    #> [3,]    0    0    2
    H(x$par, a = 1:3)
    #>      [,1] [,2] [,3]
    #> [1,]    2    0    0
    #> [2,]    0    2    0
    #> [3,]    0    0    2
    J(x$par, a = 1:3)
    #>      [,1] [,2] [,3]
    #> [1,]    2    0    0
    #> [2,]    0    2    0
    #> [3,]    0    0    2
    solution(a = 1:3, guess = rnorm(3))
    #> [1] 1 2 3

# Integrals and Ordinary Differential Equations

The Stan Math library can do one-dimensional numerical integration and can solve stiff and non-stiff systems of differential equations, such as the harmonic oscillator example below. Solving stiff systems utilizes the CVODES library, which is included in StanHeaders.

    // [[Rcpp::depends(BH)]]
    // [[Rcpp::depends(RcppEigen)]]
    // [[Rcpp::depends(RcppParallel)]]
    // [[Rcpp::depends(StanHeaders)]]
    #include <stan/math.hpp>                         // pulls in everything from rev/ and prim/
    #include <Rcpp.h>
    #include <RcppEigen.h>                           // do this AFTER including stan/math

    // [[Rcpp::plugins(cpp17)]]

    /* Definite integrals */

    // [[Rcpp::export]]
    double Cauchy(double scale) {
      std::vector<double> theta;
      auto half = stan::math::integrate_1d([](auto x, auto xc, auto theta,
                                              auto x_r, auto x_i, auto msgs) {
        return exp(stan::math::cauchy_lpdf(x, 0, x_r[0]));
      }, -scale, scale, theta, {scale}, {}, nullptr, 1e-7);
      return half * 2; // should equal 1 for any positive scale
    }

    /* Ordinary Differential Equations */

    // [[Rcpp::export]]
    auto nonstiff(Eigen::MatrixXd A, Eigen::VectorXd y0) {
      using stan::math::integrate_ode_rk45;
      using stan::math::to_vector;
      using stan::math::to_array_1d;
      std::vector<double> theta;
      std::vector<double> times = {1, 2};
      auto y = integrate_ode_rk45([&A](auto t, auto y,
                                       auto theta, auto x_r, auto x_i, std::ostream *msgs) {
        return to_array_1d( (A * to_vector(y)).eval() );
      }, to_array_1d(y0), 0, times, theta, {}, {});
      Eigen::VectorXd truth = stan::math::matrix_exp(A) * y0;
      return (to_vector(y[0]) - truth).eval(); // should be "zero"
    }

    // [[Rcpp::export]]
    auto stiff(Eigen::MatrixXd A, Eigen::VectorXd y0) { // not actually stiff
      using stan::math::integrate_ode_bdf;              // but use the stiff solver anyways
      using stan::math::to_vector;
      using stan::math::to_array_1d;
      std::vector<double> theta;
      std::vector<double> times = {1, 2};
      auto y = integrate_ode_bdf([&A](auto t, auto y,
                                      auto theta, auto x_r, auto x_i, std::ostream *msgs) {
        return to_array_1d( (A * to_vector(y)).eval() );
      }, to_array_1d(y0), 0, times, theta, {}, {});
      Eigen::VectorXd truth = stan::math::matrix_exp(A) * y0;
      return (to_vector(y[0]) - truth).eval(); // should be "zero"
    }

Again, in this compiled RMarkdown document, the knitr package has exported the `Cauchy`, `nonstiff` and `stiff` functions to R’s global environment using the `sourceCpp` function in the Rcpp package so that they can be called from R.

First, we numerically integrate the Cauchy PDF over its interquartile range — which has an area of \(\frac{1}{2}\) — that we then double to verify that it is almost within machine precision of \(1\).

    all.equal(1, Cauchy(rexp(1)), tol = 1e-15)
    #> [1] TRUE

Next, we consider the system of differential equations \[\frac{d}{dt}\mathbf{y} = \mathbf{A}\mathbf{y}\] where \(\mathbf{A}\) is a square matrix such as that for a simple harmonic oscillator

\[\mathbf{A} = \begin{bmatrix}0 & 1 \\ -1 & -\theta\end{bmatrix}\] for \(\theta \in \left(0,1\right)\). The solution for \(\mathbf{y}_t = e^{t\mathbf{A}}\mathbf{y}_0\) can be obtained via the matrix exponential function, which is available in the Stan Math Library, but it can also be obtained numerically using a fourth-order Runge-Kutta solver, which is appropriate for non-stiff systems of ODEs, such as this one. However, it is possible, albeit less efficient in this case, to use the backward-differentiation formula solver for stiff systems of ODEs. In both cases, we calculate the difference between the analytical solution and the numerical one, and the stiff version does produce somewhat better accuracy in this case.

    A <- matrix(c(0, -1, 1, -runif(1)), nrow = 2, ncol = 2)
    y0 <- rexp(2)
    all.equal(nonstiff(A, y0), c(0, 0), tol = 1e-5)
    #> [1] TRUE
    all.equal(   stiff(A, y0), c(0, 0), tol = 1e-8)
    #> [1] TRUE

# Parellelization

## `map_rect` Function

The Stan Math Library includes the `map_rect` function, which applies a function to each element of rectangular arrays and returns a vector, making it a bit like a restricted version of R’s `sapply` function. However, `map_rect` can also be executed in parallel by defining the pre-processor directive `STAN_THREADS` and then setting the `STAN_NUM_THREADS` environmental variable to be the number of threads to use, as in

    Sys.setenv(STAN_NUM_THREADS = 2) # specify -1 to use all available cores

Below is C++ code to test whether an integer is prime, using a rather brute-force algorithm and running it in parallel via `map_rect`.

    // [[Rcpp::depends(BH)]]
    // [[Rcpp::depends(RcppEigen)]]
    // [[Rcpp::depends(RcppParallel)]]
    // [[Rcpp::depends(StanHeaders)]]
    #include <stan/math.hpp>                         // pulls in everything from rev/ and prim/
    #include <Rcpp.h>
    #include <RcppEigen.h>                           // do this AFTER including stan/math

    // [[Rcpp::plugins(cpp17)]]

    // see https://en.wikipedia.org/wiki/Primality_test#Pseudocode
    struct is_prime {
      is_prime() {}
      template <typename T1, typename T2>
      auto
      operator()(const Eigen::Matrix<T1, Eigen::Dynamic, 1>& eta,
                 const Eigen::Matrix<T2, Eigen::Dynamic, 1>& theta,
                 const std::vector<double>& x_r, const std::vector<int>& x_i,
                 std::ostream* msgs = nullptr) const {
        Eigen::VectorXd res(1); // can only return double or var vectors
        int n = x_i[0];
        if (n <= 3) {
          res.coeffRef(0) = n > 1;
          return res;
        } else if ( (n % 2 == 0) || (n % 3 == 0) ) {
          res.coeffRef(0) = false;
          return res;
        }
        int i = 5;
        while (i * i <= n) {
          if ( (n % i == 0) || (n % (i + 2) == 0) ) {
            res.coeffRef(0) = false;
            return res;
          }
          i += 6;
        }
        res.coeffRef(0) = true;
        return res;
      }
    };

    /* parallelization */
    // [[Rcpp::export]]
    auto psapply(std::vector<std::vector<int> > n) {
      std::vector<Eigen::VectorXd> eta(n.size()); // these all have to be the same size
      Eigen::VectorXd theta;
      std::vector<std::vector<double> > x_d(n.size());
      return stan::math::map_rect<0, is_prime>(theta, eta, x_d, n, &Rcpp::Rcout);
    }

Since the signature for `n` is a `std::vector<std::vector<int> >`, we have to pass it from R as a list (which is converted to the outer `std::vector<>`) of integer vectors (which is converted to the inner `std::vector<int>`) that happen to be of size one in this case.

    odd <- seq.int(from = 2^25 - 1, to = 2^26 - 1, by = 2)
    tail(psapply(n = as.list(odd))) == 1 # check your process manager while this is running
    #> [1] FALSE FALSE FALSE  TRUE FALSE FALSE

Thus, \(2^{26} - 5 = 67,108,859\) is a prime number.

## `reduce_sum` Function

The `reduce_sum` function can be used to sum a function of recursively-partitioned data in parallel. The Probability Mass Function (PMF) of the logarithmic distribution is

\[\Pr\left(x = k \mid p\right) = \frac{p^k}{-k\ln\left(1 - p\right)} \] for a positive integer \(k\) and \(0 < p < 1\). To verify that this PMF sums to \(1\) over the natural numbers, we could accumulate it for a large finite number of terms, but would like to do so in parallel. To do so, we need to define a `partial_sum` function that adds the PMF for some subset of natural numbers and pass it to the `reduce_sum` function like

    // [[Rcpp::depends(BH)]]
    // [[Rcpp::depends(RcppEigen)]]
    // [[Rcpp::depends(RcppParallel)]]
    // [[Rcpp::depends(StanHeaders)]]
    #include <stan/math.hpp>                         // pulls in everything from rev/ and prim/
    #include <Rcpp.h>
    #include <RcppEigen.h>                           // do this AFTER including stan/math

    // [[Rcpp::plugins(cpp17)]]

    template <typename T>
    struct partial_sum {
      partial_sum() {}
      T operator()(const std::vector<int>& k_slice,
                   int start, int end, // these are ignored in this example
                   std::ostream* msgs, double p) {
        double S = 0;
        for (int n = 0; n < k_slice.size(); n++) {
          int k = k_slice[n];
          S += stan::math::pow(p, k) / k;
        }
        return S;
      }
    };

    // [[Rcpp::export]]
    double check_logarithmic_PMF(const double p, const int N = 1000) {
      using stan::math::reduce_sum;
      std::vector<int> k(N);
      std::iota(k.begin(), k.end(), 1);
      return reduce_sum<partial_sum<double> >(k, 1, nullptr, p) / -std::log1p(-p);
    }

The second argument passed to `reduce_sum` is the `grainsize`, which governs the size (and number) of the recursive subsets of `k` that are passed to the `partial_sum` function. A `grainsize` of \(1\) indicates that the software will try to automatically tune the subset size for good performance, but that may be worse than choosing a `grainsize` by hand in a problem-specific fashion.

In any event, we can call the wrapper function `check_logarithmic_PMF` in R to verify that it returns \(1\) to numerical tolerance:

    stopifnot(all.equal(1, check_logarithmic_PMF(p = 1 / sqrt(2))))

# Defining a Stan Model in C++

The Stan language does not have much support for sparse matrices for a variety of reasons. Essentially the only applicable function is `csr_matrix_times_vector`, which pre-multiplies a vector by a sparse matrix in compressed row storage by taking as arguments its number of rows, columns, non-zero values, column indices of non-zero values, and locations where the non-zero values start in each row. While the `csr_matrix_times_vector` function could be used to implement the example below, we illustrate how to use the sparse data structures in the Matrix and RcppEigen packages in a Stan model written in C++, which could easily be extended to more complicated models with sparse data structures.

Our C++ file for the log-likelihood of a linear model with a sparse design matrix reads as

    #include <stan/model/model_header.hpp>
    #include <Rcpp.h>
    #include <RcppEigen.h>

    class sparselm_stan {

    public: // these would ordinarily be private in the C++ code generated by Stan
      Eigen::Map<Eigen::SparseMatrix<double> > X;
      Eigen::VectorXd y;

      sparselm_stan(Eigen::Map<Eigen::SparseMatrix<double> > X, Eigen::VectorXd y) :
        X(X), y(y) {}

      template <bool propto__ = false, bool jacobian__ = false, typename T__ = double>
      // propto__ is usually true but causes log_prob() to return 0 when called from R
      // jacobian__ is usually true for MCMC but typically is false for optimization
      T__ log_prob(std::vector<T__>& params_r__) const {
        using namespace stan::math;
        T__ lp__(0.0);
        accumulator<T__> lp_accum__;

        // set up model parameters
        std::vector<int> params_i__;
        stan::io::deserializer<T__> in__(params_r__, params_i__);
        auto beta = in__.template read<Eigen::Matrix<T__,-1,1> >(X.cols());
        auto sigma = in__.template read_constrain_lb<T__, jacobian__>(0, lp__);

        // log-likelihood (should add priors)
        lp_accum__.add(lp__);
        lp_accum__.add(normal_lpdf<propto__>(y, (X * beta).eval(), sigma));
        return lp_accum__.sum();
      }

      template <bool propto__ = false, bool jacobian__ = false>
      std::vector<double> gradient(std::vector<double>& params_r__) const {
        // Calculate gradients using reverse-mode autodiff
        // although you could do them analytically in this case

        using std::vector;
        using stan::math::var;
        double lp;
        std::vector<double> gradient;
        try {
          vector<var> ad_params_r(params_r__.size());
          for (size_t i = 0; i < params_r__.size(); ++i) {
            var var_i(params_r__[i]);
            ad_params_r[i] = var_i;
          }
          var adLogProb
            = this->log_prob<propto__, jacobian__>(ad_params_r);
          lp = adLogProb.val();
          adLogProb.grad(ad_params_r, gradient);
        } catch (const std::exception &ex) {
          stan::math::recover_memory();
          throw;
        }
        stan::math::recover_memory();
        return gradient;
      }
    };

To use it from R, we call the `exposeClass` function in the Rcpp package with the necessary arguments and then call `sourceCpp` on the file it wrote in the temporary directory:

    library(Rcpp)
    tf <- tempfile(fileext = "Module.cpp")
    exposeClass("sparselm_stan",
          constructors = list(c("Eigen::Map<Eigen::SparseMatrix<double> >",
                                "Eigen::VectorXd")),
          fields = c("X", "y"),
          methods = c("log_prob<>", "gradient<>"),
          rename = c(log_prob = "log_prob<>", gradient = "gradient<>"),
          header = c("// [[Rcpp::depends(BH)]]",
                     "// [[Rcpp::depends(RcppEigen)]]",
                     "// [[Rcpp::depends(RcppParallel)]",
                     "// [[Rcpp::depends(StanHeaders)]]",
                     "// [[Rcpp::plugins(cpp17)]]",
                     paste0("#include <", file.path(getwd(), "sparselm_stan.hpp"), ">")),
          file = tf,
          Rfile = FALSE)
    Sys.setenv(PKG_CXXFLAGS = paste0(Sys.getenv("PKG_CXXFLAGS"), " -I",
                                     system.file("include", "src",
                                                 package = "StanHeaders", mustWork = TRUE)))
    sourceCpp(tf)
    sparselm_stan
    #> C++ class 'sparselm_stan' <0x615621b653c0>
    #> Constructors:
    #>     sparselm_stan(Eigen::Map<Eigen::SparseMatrix<double, 0, int>, 0, Eigen::Stride<0, 0> >, Eigen::Matrix<double, -1, 1, 0, -1, 1>)
    #>
    #> Fields:
    #>     Eigen::Map<Eigen::SparseMatrix<double, 0, int>, 0, Eigen::Stride<0, 0> > X
    #>     Eigen::Matrix<double, -1, 1, 0, -1, 1> y
    #>
    #> Methods:
    #>      std::vector<double, std::allocator<double> > gradient(std::vector<double, std::allocator<double> >)  const
    #>
    #>      double log_prob(std::vector<double, std::allocator<double> >)  const
    #>

At this point, we need a sparse design matrix and (dense) outcome vector to pass to the constructor. The former can be created with a variety of functions in the Matrix package, such as

    dd <- data.frame(a = gl(3, 4), b = gl(4, 1, 12))
    X <- Matrix::sparse.model.matrix(~ a + b, data = dd)
    X
    #> 12 x 6 sparse Matrix of class "dgCMatrix"
    #>    (Intercept) a2 a3 b2 b3 b4
    #> 1            1  .  .  .  .  .
    #> 2            1  .  .  1  .  .
    #> 3            1  .  .  .  1  .
    #> 4            1  .  .  .  .  1
    #> 5            1  1  .  .  .  .
    #> 6            1  1  .  1  .  .
    #> 7            1  1  .  .  1  .
    #> 8            1  1  .  .  .  1
    #> 9            1  .  1  .  .  .
    #> 10           1  .  1  1  .  .
    #> 11           1  .  1  .  1  .
    #> 12           1  .  1  .  .  1

Finally, we call the `new` function in the methods package, which essentially calls our C++ constructor and provides an R interface to the instantiated object, which contains the `log_prob` and `gradient` methods we defined and can be called with arbitrary inputs.

    sm <- new(sparselm_stan, X = X, y = rnorm(nrow(X)))
    sm$log_prob(c(beta = rnorm(ncol(X)), log_sigma = log(pi)))
    #> [1] -26.01577
    round(sm$gradient(c(beta = rnorm(ncol(X)), log_sigma = log(pi))), digits = 4)
    #> [1] -2.1984 -1.0424 -0.5089 -0.4552 -0.6047 -0.8303 -6.6551