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.21.0), RcppParallel (>= 5.0.1)
in the DESCRIPTION file of another package and put something like
CXX_STD = CXX14
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)"
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] 760
#>
#> 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 log_sum_exp(as.list(x)) :
#> 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> # 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.5401593 0.1336589
#> [2,] -0.5401593 1.0000000 0.5153359
#> [3,] 0.1336589 0.5153359 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" "F32"
#> [2,] "LDLT_factor" "Phi"
#> [3,] "Phi_approx" "StdVectorBuilder"
#> [4,] "VectorBuilder" "VectorBuilderHelper"
#> [5,] "abs" "accumulator"
#> [6,] "acos" "acosh"
#> [7,] "ad_promotable" "add"
#> [8,] "add_diag" "append_array"
#> [9,] "append_col" "append_return_type"
#> [10,] "append_row" "apply_scalar_unary"
#> [11,] "array_builder" "as_array_or_scalar"
#> [12,] "as_bool" "as_column_vector_or_scalar"
#> [13,] "as_scalar" "asin"
#> [14,] "asinh" "assign"
#> [15,] "atan" "atanh"
#> [16,] "autocorrelation" "autocovariance"
#> [17,] "bernoulli_ccdf_log" "bernoulli_cdf"
#> [18,] "bernoulli_cdf_log" "bernoulli_lccdf"
#> [19,] "bernoulli_lcdf" "bernoulli_log"
#> [20,] "bernoulli_logit_glm_log" "bernoulli_logit_glm_lpmf"
#> [21,] "bernoulli_logit_glm_rng" "bernoulli_logit_log"
#> [22,] "bernoulli_logit_lpmf" "bernoulli_logit_rng"
#> [23,] "bernoulli_lpmf" "bernoulli_rng"
#> [24,] "bessel_first_kind" "bessel_second_kind"
#> [25,] "beta" "beta_binomial_ccdf_log"
#> [26,] "beta_binomial_cdf" "beta_binomial_cdf_log"
#> [27,] "beta_binomial_lccdf" "beta_binomial_lcdf"
#> [28,] "beta_binomial_log" "beta_binomial_lpmf"
#> [29,] "beta_binomial_rng" "beta_ccdf_log"
#> [30,] "beta_cdf" "beta_cdf_log"
#> [31,] "beta_lccdf" "beta_lcdf"
#> [32,] "beta_log" "beta_lpdf"
#> [33,] "beta_proportion_ccdf_log" "beta_proportion_cdf_log"
#> [34,] "beta_proportion_lccdf" "beta_proportion_lcdf"
#> [35,] "beta_proportion_log" "beta_proportion_lpdf"
#> [36,] "beta_proportion_rng" "beta_rng"
#> [37,] "binary_log_loss" "binomial_ccdf_log"
#> [38,] "binomial_cdf" "binomial_cdf_log"
#> [39,] "binomial_coefficient_log" "binomial_lccdf"
#> [40,] "binomial_lcdf" "binomial_log"
#> [41,] "binomial_logit_log" "binomial_logit_lpmf"
#> [42,] "binomial_lpmf" "binomial_rng"
#> [43,] "block" "bool_constant"
#> [44,] "boost_policy" "broadcast_array"
#> [45,] "categorical_log" "categorical_logit_glm_lpmf"
#> [46,] "categorical_logit_log" "categorical_logit_lpmf"
#> [47,] "categorical_logit_rng" "categorical_lpmf"
#> [48,] "categorical_rng" "cauchy_ccdf_log"
#> [49,] "cauchy_cdf" "cauchy_cdf_log"
#> [50,] "cauchy_lccdf" "cauchy_lcdf"
#> [51,] "cauchy_log" "cauchy_lpdf"
#> [52,] "cauchy_rng" "cbrt"
#> [53,] "ceil" "check_2F1_converges"
#> [54,] "check_3F2_converges" "check_bounded"
#> [55,] "check_cholesky_factor" "check_cholesky_factor_corr"
#> [56,] "check_column_index" "check_consistent_size"
#> [57,] "check_consistent_size_mvt" "check_consistent_sizes"
#> [58,] "check_consistent_sizes_mvt" "check_corr_matrix"
#> [59,] "check_cov_matrix" "check_finite"
#> [60,] "check_flag_sundials" "check_greater"
#> [61,] "check_greater_or_equal" "check_ldlt_factor"
#> [62,] "check_less" "check_less_or_equal"
#> [63,] "check_lower_triangular" "check_matching_dims"
#> [64,] "check_matching_sizes" "check_multiplicable"
#> [65,] "check_nonempty" "check_nonnegative"
#> [66,] "check_nonzero_size" "check_not_nan"
#> [67,] "check_ordered" "check_pos_definite"
#> [68,] "check_pos_semidefinite" "check_positive"
#> [69,] "check_positive_finite" "check_positive_ordered"
#> [70,] "check_range" "check_row_index"
#> [71,] "check_simplex" "check_size_match"
#> [72,] "check_spsd_matrix" "check_square"
#> [73,] "check_std_vector_index" "check_symmetric"
#> [74,] "check_unit_vector" "check_vector"
#> [75,] "chi_square_ccdf_log" "chi_square_cdf"
#> [76,] "chi_square_cdf_log" "chi_square_lccdf"
#> [77,] "chi_square_lcdf" "chi_square_log"
#> [78,] "chi_square_lpdf" "chi_square_rng"
#> [79,] "child_type" "chol2inv"
#> [80,] "cholesky_corr_constrain" "cholesky_corr_free"
#> [81,] "cholesky_decompose" "cholesky_factor_constrain"
#> [82,] "cholesky_factor_free" "choose"
#> [83,] "col" "cols"
#> [84,] "columns_dot_product" "columns_dot_self"
#> [85,] "common_type" "conjunction"
#> [86,] "constants" "constraint_tolerance"
#> [87,] "contains_fvar" "contains_std_vector"
#> [88,] "contains_vector" "corr_constrain"
#> [89,] "corr_free" "corr_matrix_constrain"
#> [90,] "corr_matrix_free" "cos"
#> [91,] "cosh" "coupled_ode_observer"
#> [92,] "coupled_ode_system" "cov_exp_quad"
#> [93,] "cov_matrix_constrain" "cov_matrix_constrain_lkj"
#> [94,] "cov_matrix_free" "cov_matrix_free_lkj"
#> [95,] "crossprod" "csr_extract_u"
#> [96,] "csr_extract_v" "csr_extract_w"
#> [97,] "csr_matrix_times_vector" "csr_to_dense_matrix"
#> [98,] "csr_u_to_z" "cumulative_sum"
#> [99,] "determinant" "diag_matrix"
#> [100,] "diag_post_multiply" "diag_pre_multiply"
#> [101,] "diagonal" "digamma"
#> [102,] "dims" "dirichlet_log"
#> [103,] "dirichlet_lpmf" "dirichlet_rng"
#> [104,] "disjunction" "distance"
#> [105,] "divide" "divide_columns"
#> [106,] "domain_error" "domain_error_vec"
#> [107,] "dot" "dot_product"
#> [108,] "dot_self" "double_exponential_ccdf_log"
#> [109,] "double_exponential_cdf" "double_exponential_cdf_log"
#> [110,] "double_exponential_lccdf" "double_exponential_lcdf"
#> [111,] "double_exponential_log" "double_exponential_lpdf"
#> [112,] "double_exponential_rng" "eigenvalues_sym"
#> [113,] "eigenvectors_sym" "elt_divide"
#> [114,] "elt_multiply" "erf"
#> [115,] "erfc" "error_index"
#> [116,] "exp" "exp2"
#> [117,] "exp_mod_normal_ccdf_log" "exp_mod_normal_cdf"
#> [118,] "exp_mod_normal_cdf_log" "exp_mod_normal_lccdf"
#> [119,] "exp_mod_normal_lcdf" "exp_mod_normal_log"
#> [120,] "exp_mod_normal_lpdf" "exp_mod_normal_rng"
#> [121,] "expm1" "exponential_ccdf_log"
#> [122,] "exponential_cdf" "exponential_cdf_log"
#> [123,] "exponential_lccdf" "exponential_lcdf"
#> [124,] "exponential_log" "exponential_lpdf"
#> [125,] "exponential_rng" "fabs"
#> [126,] "factor_U" "factor_cov_matrix"
#> [127,] "falling_factorial" "fdim"
#> [128,] "fill" "finite_diff_gradient"
#> [129,] "finite_diff_gradient_auto" "finite_diff_hessian"
#> [130,] "finite_diff_hessian_auto" "finite_diff_hessian_helper"
#> [131,] "finite_diff_stepsize" "floor"
#> [132,] "fma" "fmax"
#> [133,] "fmin" "frechet_ccdf_log"
#> [134,] "frechet_cdf" "frechet_cdf_log"
#> [135,] "frechet_lccdf" "frechet_lcdf"
#> [136,] "frechet_log" "frechet_lpdf"
#> [137,] "frechet_rng" "gamma_ccdf_log"
#> [138,] "gamma_cdf" "gamma_cdf_log"
#> [139,] "gamma_lccdf" "gamma_lcdf"
#> [140,] "gamma_log" "gamma_lpdf"
#> [141,] "gamma_p" "gamma_q"
#> [142,] "gamma_rng" "gaussian_dlm_obs_log"
#> [143,] "gaussian_dlm_obs_lpdf" "gaussian_dlm_obs_rng"
#> [144,] "get" "get_base1"
#> [145,] "get_base1_lhs" "get_lp"
#> [146,] "gp_dot_prod_cov" "gp_exp_quad_cov"
#> [147,] "gp_exponential_cov" "gp_matern32_cov"
#> [148,] "gp_matern52_cov" "gp_periodic_cov"
#> [149,] "grad_2F1" "grad_F32"
#> [150,] "grad_inc_beta" "grad_reg_inc_beta"
#> [151,] "grad_reg_inc_gamma" "grad_reg_lower_inc_gamma"
#> [152,] "gumbel_ccdf_log" "gumbel_cdf"
#> [153,] "gumbel_cdf_log" "gumbel_lccdf"
#> [154,] "gumbel_lcdf" "gumbel_log"
#> [155,] "gumbel_lpdf" "gumbel_rng"
#> [156,] "head" "hypergeometric_log"
#> [157,] "hypergeometric_lpmf" "hypergeometric_rng"
#> [158,] "hypot" "ibeta"
#> [159,] "identity_constrain" "identity_free"
#> [160,] "if_else" "inc_beta"
#> [161,] "inc_beta_dda" "inc_beta_ddb"
#> [162,] "inc_beta_ddz" "include_summand"
#> [163,] "index_type" "init_threadpool_tbb"
#> [164,] "initialize" "int_step"
#> [165,] "integrate_1d" "integrate_ode_rk45"
#> [166,] "inv" "inv_Phi"
#> [167,] "inv_chi_square_ccdf_log" "inv_chi_square_cdf"
#> [168,] "inv_chi_square_cdf_log" "inv_chi_square_lccdf"
#> [169,] "inv_chi_square_lcdf" "inv_chi_square_log"
#> [170,] "inv_chi_square_lpdf" "inv_chi_square_rng"
#> [171,] "inv_cloglog" "inv_gamma_ccdf_log"
#> [172,] "inv_gamma_cdf" "inv_gamma_cdf_log"
#> [173,] "inv_gamma_lccdf" "inv_gamma_lcdf"
#> [174,] "inv_gamma_log" "inv_gamma_lpdf"
#> [175,] "inv_gamma_rng" "inv_logit"
#> [176,] "inv_sqrt" "inv_square"
#> [177,] "inv_wishart_log" "inv_wishart_lpdf"
#> [178,] "inv_wishart_rng" "invalid_argument"
#> [179,] "invalid_argument_vec" "inverse"
#> [180,] "inverse_softmax" "inverse_spd"
#> [181,] "is_any_nan" "is_cholesky_factor"
#> [182,] "is_cholesky_factor_corr" "is_column_index"
#> [183,] "is_constant" "is_corr_matrix"
#> [184,] "is_eigen" "is_fvar"
#> [185,] "is_inf" "is_integer"
#> [186,] "is_ldlt_factor" "is_less_or_equal"
#> [187,] "is_lower_triangular" "is_mat_finite"
#> [188,] "is_matching_dims" "is_matching_size"
#> [189,] "is_nan" "is_nonpositive_integer"
#> [190,] "is_nonzero_size" "is_not_nan"
#> [191,] "is_ordered" "is_pos_definite"
#> [192,] "is_positive" "is_scal_finite"
#> [193,] "is_size_match" "is_square"
#> [194,] "is_symmetric" "is_uninitialized"
#> [195,] "is_unit_vector" "is_var"
#> [196,] "is_var_or_arithmetic" "is_vector"
#> [197,] "is_vector_like" "lb_constrain"
#> [198,] "lb_free" "lbeta"
#> [199,] "ldexp" "length"
#> [200,] "length_mvt" "lgamma"
#> [201,] "likely" "lkj_corr_cholesky_log"
#> [202,] "lkj_corr_cholesky_lpdf" "lkj_corr_cholesky_rng"
#> [203,] "lkj_corr_log" "lkj_corr_lpdf"
#> [204,] "lkj_corr_rng" "lkj_cov_log"
#> [205,] "lkj_cov_lpdf" "lmgamma"
#> [206,] "locscale_constrain" "locscale_free"
#> [207,] "log" "log10"
#> [208,] "log1m" "log1m_exp"
#> [209,] "log1m_inv_logit" "log1p"
#> [210,] "log1p_exp" "log2"
#> [211,] "log_determinant" "log_determinant_ldlt"
#> [212,] "log_determinant_spd" "log_diff_exp"
#> [213,] "log_falling_factorial" "log_inv_logit"
#> [214,] "log_inv_logit_diff" "log_mix"
#> [215,] "log_modified_bessel_first_kind" "log_rising_factorial"
#> [216,] "log_softmax" "log_sum_exp"
#> [217,] "logical_and" "logical_eq"
#> [218,] "logical_gt" "logical_gte"
#> [219,] "logical_lt" "logical_lte"
#> [220,] "logical_negation" "logical_neq"
#> [221,] "logical_or" "logistic_ccdf_log"
#> [222,] "logistic_cdf" "logistic_cdf_log"
#> [223,] "logistic_lccdf" "logistic_lcdf"
#> [224,] "logistic_log" "logistic_lpdf"
#> [225,] "logistic_rng" "logit"
#> [226,] "lognormal_ccdf_log" "lognormal_cdf"
#> [227,] "lognormal_cdf_log" "lognormal_lccdf"
#> [228,] "lognormal_lcdf" "lognormal_log"
#> [229,] "lognormal_lpdf" "lognormal_rng"
#> [230,] "lub_constrain" "lub_free"
#> [231,] "make_nu" "map_rect"
#> [232,] "map_rect_combine" "map_rect_concurrent"
#> [233,] "map_rect_mpi" "map_rect_reduce"
#> [234,] "matrix_exp" "matrix_exp_2x2"
#> [235,] "matrix_exp_action_handler" "matrix_exp_multiply"
#> [236,] "matrix_exp_pade" "matrix_normal_prec_log"
#> [237,] "matrix_normal_prec_lpdf" "matrix_normal_prec_rng"
#> [238,] "max" "max_size"
#> [239,] "max_size_mvt" "mdivide_left"
#> [240,] "mdivide_left_ldlt" "mdivide_left_spd"
#> [241,] "mdivide_left_tri" "mdivide_left_tri_low"
#> [242,] "mdivide_right" "mdivide_right_ldlt"
#> [243,] "mdivide_right_spd" "mdivide_right_tri"
#> [244,] "mdivide_right_tri_low" "mean"
#> [245,] "min" "minus"
#> [246,] "modified_bessel_first_kind" "modified_bessel_second_kind"
#> [247,] "modulus" "mpi_cluster"
#> [248,] "mpi_command" "mpi_distributed_apply"
#> [249,] "mpi_parallel_call" "multi_gp_cholesky_log"
#> [250,] "multi_gp_cholesky_lpdf" "multi_gp_log"
#> [251,] "multi_gp_lpdf" "multi_normal_cholesky_log"
#> [252,] "multi_normal_cholesky_lpdf" "multi_normal_cholesky_rng"
#> [253,] "multi_normal_log" "multi_normal_lpdf"
#> [254,] "multi_normal_prec_log" "multi_normal_prec_lpdf"
#> [255,] "multi_normal_prec_rng" "multi_normal_rng"
#> [256,] "multi_student_t_log" "multi_student_t_lpdf"
#> [257,] "multi_student_t_rng" "multinomial_log"
#> [258,] "multinomial_lpmf" "multinomial_rng"
#> [259,] "multiply" "multiply_log"
#> [260,] "multiply_lower_tri_self_transpose" "neg_binomial_2_ccdf_log"
#> [261,] "neg_binomial_2_cdf" "neg_binomial_2_cdf_log"
#> [262,] "neg_binomial_2_lccdf" "neg_binomial_2_lcdf"
#> [263,] "neg_binomial_2_log" "neg_binomial_2_log_glm_log"
#> [264,] "neg_binomial_2_log_glm_lpmf" "neg_binomial_2_log_log"
#> [265,] "neg_binomial_2_log_lpmf" "neg_binomial_2_log_rng"
#> [266,] "neg_binomial_2_lpmf" "neg_binomial_2_rng"
#> [267,] "neg_binomial_ccdf_log" "neg_binomial_cdf"
#> [268,] "neg_binomial_cdf_log" "neg_binomial_lccdf"
#> [269,] "neg_binomial_lcdf" "neg_binomial_log"
#> [270,] "neg_binomial_lpmf" "neg_binomial_rng"
#> [271,] "normal_ccdf_log" "normal_cdf"
#> [272,] "normal_cdf_log" "normal_id_glm_log"
#> [273,] "normal_id_glm_lpdf" "normal_lccdf"
#> [274,] "normal_lcdf" "normal_log"
#> [275,] "normal_lpdf" "normal_rng"
#> [276,] "normal_sufficient_log" "normal_sufficient_lpdf"
#> [277,] "num_elements" "offset_multiplier_constrain"
#> [278,] "offset_multiplier_free" "operands_and_partials"
#> [279,] "ordered_constrain" "ordered_free"
#> [280,] "ordered_logistic_glm_lpmf" "ordered_logistic_log"
#> [281,] "ordered_logistic_lpmf" "ordered_logistic_rng"
#> [282,] "ordered_probit_log" "ordered_probit_lpmf"
#> [283,] "ordered_probit_rng" "out_of_range"
#> [284,] "owens_t" "pareto_ccdf_log"
#> [285,] "pareto_cdf" "pareto_cdf_log"
#> [286,] "pareto_lccdf" "pareto_lcdf"
#> [287,] "pareto_log" "pareto_lpdf"
#> [288,] "pareto_rng" "pareto_type_2_ccdf_log"
#> [289,] "pareto_type_2_cdf" "pareto_type_2_cdf_log"
#> [290,] "pareto_type_2_lccdf" "pareto_type_2_lcdf"
#> [291,] "pareto_type_2_log" "pareto_type_2_lpdf"
#> [292,] "pareto_type_2_rng" "partials_return_type"
#> [293,] "partials_type" "poisson_ccdf_log"
#> [294,] "poisson_cdf" "poisson_cdf_log"
#> [295,] "poisson_lccdf" "poisson_lcdf"
#> [296,] "poisson_log" "poisson_log_glm_log"
#> [297,] "poisson_log_glm_lpmf" "poisson_log_log"
#> [298,] "poisson_log_lpmf" "poisson_log_rng"
#> [299,] "poisson_lpmf" "poisson_rng"
#> [300,] "positive_constrain" "positive_free"
#> [301,] "positive_ordered_constrain" "positive_ordered_free"
#> [302,] "primitive_value" "prob_constrain"
#> [303,] "prob_free" "prod"
#> [304,] "promote_args" "promote_common"
#> [305,] "promote_elements" "promote_scalar"
#> [306,] "promote_scalar_type" "qr_Q"
#> [307,] "qr_R" "qr_thin_Q"
#> [308,] "qr_thin_R" "quad_form"
#> [309,] "quad_form_diag" "quad_form_sym"
#> [310,] "rank" "rayleigh_ccdf_log"
#> [311,] "rayleigh_cdf" "rayleigh_cdf_log"
#> [312,] "rayleigh_lccdf" "rayleigh_lcdf"
#> [313,] "rayleigh_log" "rayleigh_lpdf"
#> [314,] "rayleigh_rng" "read_corr_L"
#> [315,] "read_corr_matrix" "read_cov_L"
#> [316,] "read_cov_matrix" "rep_array"
#> [317,] "rep_matrix" "rep_row_vector"
#> [318,] "rep_vector" "require_generics"
#> [319,] "resize" "return_type"
#> [320,] "rising_factorial" "round"
#> [321,] "row" "rows"
#> [322,] "rows_dot_product" "rows_dot_self"
#> [323,] "scalar_seq_view" "scalar_type"
#> [324,] "scalar_type_pre" "scale_matrix_exp_multiply"
#> [325,] "scaled_add" "scaled_inv_chi_square_ccdf_log"
#> [326,] "scaled_inv_chi_square_cdf" "scaled_inv_chi_square_cdf_log"
#> [327,] "scaled_inv_chi_square_lccdf" "scaled_inv_chi_square_lcdf"
#> [328,] "scaled_inv_chi_square_log" "scaled_inv_chi_square_lpdf"
#> [329,] "scaled_inv_chi_square_rng" "sd"
#> [330,] "segment" "seq_view"
#> [331,] "sign" "simplex_constrain"
#> [332,] "simplex_free" "sin"
#> [333,] "singular_values" "sinh"
#> [334,] "size" "size_of"
#> [335,] "size_zero" "skew_normal_ccdf_log"
#> [336,] "skew_normal_cdf" "skew_normal_cdf_log"
#> [337,] "skew_normal_lccdf" "skew_normal_lcdf"
#> [338,] "skew_normal_log" "skew_normal_lpdf"
#> [339,] "skew_normal_rng" "softmax"
#> [340,] "sort_asc" "sort_desc"
#> [341,] "sort_indices" "sort_indices_asc"
#> [342,] "sort_indices_desc" "sqrt"
#> [343,] "square" "squared_distance"
#> [344,] "stan_print" "std_normal_log"
#> [345,] "std_normal_lpdf" "step"
#> [346,] "student_t_ccdf_log" "student_t_cdf"
#> [347,] "student_t_cdf_log" "student_t_lccdf"
#> [348,] "student_t_lcdf" "student_t_log"
#> [349,] "student_t_lpdf" "student_t_rng"
#> [350,] "sub" "sub_col"
#> [351,] "sub_row" "subtract"
#> [352,] "sum" "system_error"
#> [353,] "tail" "tan"
#> [354,] "tanh" "tcrossprod"
#> [355,] "tgamma" "to_array_1d"
#> [356,] "to_array_2d" "to_matrix"
#> [357,] "to_row_vector" "to_vector"
#> [358,] "trace" "trace_gen_inv_quad_form_ldlt"
#> [359,] "trace_gen_quad_form" "trace_inv_quad_form_ldlt"
#> [360,] "trace_quad_form" "transpose"
#> [361,] "trigamma" "trunc"
#> [362,] "typedefs" "ub_constrain"
#> [363,] "ub_free" "uniform_ccdf_log"
#> [364,] "uniform_cdf" "uniform_cdf_log"
#> [365,] "uniform_lccdf" "uniform_lcdf"
#> [366,] "uniform_log" "uniform_lpdf"
#> [367,] "uniform_rng" "unit_vector_constrain"
#> [368,] "unit_vector_free" "validate_non_negative_index"
#> [369,] "value_of" "value_of_rec"
#> [370,] "value_type" "variance"
#> [371,] "vec_concat" "vector_seq_view"
#> [372,] "von_mises_log" "von_mises_lpdf"
#> [373,] "von_mises_rng" "weibull_ccdf_log"
#> [374,] "weibull_cdf" "weibull_cdf_log"
#> [375,] "weibull_lccdf" "weibull_lcdf"
#> [376,] "weibull_log" "weibull_lpdf"
#> [377,] "weibull_rng" "welford_covar_estimator"
#> [378,] "welford_var_estimator" "wiener_log"
#> [379,] "wiener_lpdf" "wishart_log"
#> [380,] "wishart_lpdf" "wishart_rng"
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++.
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/fwd/mat/fun/dot_self.hpp> // stuff from fwd/ must come first
#include <stan/math/mix/mat/functor/hessian.hpp> // then stuff from mix/ must come next
#include <stan/math.hpp> // finally pull in everything from rev/ & prim/
#include <Rcpp.h>
#include <RcppEigen.h> // do this AFTER including stan/math
// [[Rcpp::plugins(cpp14)]]
/* 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).eval() ); // .eval() yields a Eigen::VectorXd
}
/* 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).eval() ); },
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;
using stan::math::subtract; // necessary to get the type promotion correct
stan::math::hessian([&a](auto x) { return dot_self(subtract(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)).eval();
}, 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)).eval();
}
};
// [[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
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(cpp14)]]
/* 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}, {}, Rcpp::Rcout, 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\).
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.
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
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(cpp14)]]
// 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 = 0) 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.
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::reader<T__> in__(params_r__, params_i__);
auto beta = in__.vector_constrain(X.cols());
T__ sigma;
if (jacobian__) sigma = in__.scalar_lb_constrain(0, lp__);
else sigma = in__.scalar_lb_constrain(0);
// 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(cpp14)]]",
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' <0x560ac5e8f6a0>
#> 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.