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)"
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] 908
#>
#> 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,] "compiler_attributes" "complex_base"
#> [89,] "complex_schur_decompose" "conj"
#> [90,] "conjunction" "constants"
#> [91,] "constraint_tolerance" "contains_std_vector"
#> [92,] "copysign" "corr_constrain"
#> [93,] "corr_free" "corr_matrix_constrain"
#> [94,] "corr_matrix_free" "cos"
#> [95,] "cosh" "coupled_ode_system"
#> [96,] "cov_exp_quad" "cov_matrix_constrain"
#> [97,] "cov_matrix_constrain_lkj" "cov_matrix_free"
#> [98,] "cov_matrix_free_lkj" "crossprod"
#> [99,] "csr_extract" "csr_extract_u"
#> [100,] "csr_extract_v" "csr_extract_w"
#> [101,] "csr_matrix_times_vector" "csr_to_dense_matrix"
#> [102,] "csr_u_to_z" "cumulative_sum"
#> [103,] "determinant" "diag_matrix"
#> [104,] "diag_post_multiply" "diag_pre_multiply"
#> [105,] "diagonal" "digamma"
#> [106,] "dims" "dirichlet_lpdf"
#> [107,] "dirichlet_multinomial_lpmf" "dirichlet_multinomial_rng"
#> [108,] "dirichlet_rng" "discrete_range_ccdf_log"
#> [109,] "discrete_range_cdf" "discrete_range_cdf_log"
#> [110,] "discrete_range_lccdf" "discrete_range_lcdf"
#> [111,] "discrete_range_lpmf" "discrete_range_rng"
#> [112,] "disjunction" "distance"
#> [113,] "divide" "divide_columns"
#> [114,] "domain_error" "domain_error_vec"
#> [115,] "dot" "dot_product"
#> [116,] "dot_self" "double_exponential_ccdf_log"
#> [117,] "double_exponential_cdf" "double_exponential_cdf_log"
#> [118,] "double_exponential_lccdf" "double_exponential_lcdf"
#> [119,] "double_exponential_lpdf" "double_exponential_rng"
#> [120,] "eigen_comparisons" "eigendecompose"
#> [121,] "eigendecompose_sym" "eigenvalues"
#> [122,] "eigenvalues_sym" "eigenvectors"
#> [123,] "eigenvectors_sym" "elementwise_check"
#> [124,] "elt_divide" "elt_multiply"
#> [125,] "erf" "erfc"
#> [126,] "error_index" "eval"
#> [127,] "exp" "exp2"
#> [128,] "exp_mod_normal_ccdf_log" "exp_mod_normal_cdf"
#> [129,] "exp_mod_normal_cdf_log" "exp_mod_normal_lccdf"
#> [130,] "exp_mod_normal_lcdf" "exp_mod_normal_lpdf"
#> [131,] "exp_mod_normal_rng" "expm1"
#> [132,] "exponential_ccdf_log" "exponential_cdf"
#> [133,] "exponential_cdf_log" "exponential_lccdf"
#> [134,] "exponential_lcdf" "exponential_lpdf"
#> [135,] "exponential_rng" "fabs"
#> [136,] "factor_U" "factor_cov_matrix"
#> [137,] "falling_factorial" "fdim"
#> [138,] "fft" "fill"
#> [139,] "finite_diff_gradient" "finite_diff_gradient_auto"
#> [140,] "finite_diff_stepsize" "floor"
#> [141,] "fma" "fmax"
#> [142,] "fmin" "fmod"
#> [143,] "for_each" "forward_as"
#> [144,] "frechet_ccdf_log" "frechet_cdf"
#> [145,] "frechet_cdf_log" "frechet_lccdf"
#> [146,] "frechet_lcdf" "frechet_lpdf"
#> [147,] "frechet_rng" "gamma_ccdf_log"
#> [148,] "gamma_cdf" "gamma_cdf_log"
#> [149,] "gamma_lccdf" "gamma_lcdf"
#> [150,] "gamma_lpdf" "gamma_p"
#> [151,] "gamma_q" "gamma_rng"
#> [152,] "gaussian_dlm_obs_lpdf" "gaussian_dlm_obs_rng"
#> [153,] "generalized_inverse" "get"
#> [154,] "get_base1" "get_base1_lhs"
#> [155,] "get_imag" "get_lp"
#> [156,] "get_real" "gp_dot_prod_cov"
#> [157,] "gp_exp_quad_cov" "gp_exponential_cov"
#> [158,] "gp_matern32_cov" "gp_matern52_cov"
#> [159,] "gp_periodic_cov" "grad_2F1"
#> [160,] "grad_F32" "grad_inc_beta"
#> [161,] "grad_pFq" "grad_reg_inc_beta"
#> [162,] "grad_reg_inc_gamma" "grad_reg_lower_inc_gamma"
#> [163,] "gumbel_ccdf_log" "gumbel_cdf"
#> [164,] "gumbel_cdf_log" "gumbel_lccdf"
#> [165,] "gumbel_lcdf" "gumbel_lpdf"
#> [166,] "gumbel_rng" "hcubature"
#> [167,] "head" "hmm_check"
#> [168,] "hmm_hidden_state_prob" "hmm_latent_rng"
#> [169,] "hmm_marginal" "holder"
#> [170,] "hypergeometric_1F0" "hypergeometric_2F1"
#> [171,] "hypergeometric_2F2" "hypergeometric_3F2"
#> [172,] "hypergeometric_lpmf" "hypergeometric_pFq"
#> [173,] "hypergeometric_rng" "hypot"
#> [174,] "i_times" "identity_constrain"
#> [175,] "identity_free" "identity_matrix"
#> [176,] "if_else" "imag"
#> [177,] "inc_beta" "inc_beta_dda"
#> [178,] "inc_beta_ddb" "inc_beta_ddz"
#> [179,] "include_summand" "index_apply"
#> [180,] "index_type" "init_threadpool_tbb"
#> [181,] "initialize" "initialize_fill"
#> [182,] "int_step" "integrate_1d"
#> [183,] "integrate_1d_adapter" "integrate_ode_rk45"
#> [184,] "integrate_ode_std_vector_interface_adapter" "inv"
#> [185,] "inv_Phi" "inv_chi_square_ccdf_log"
#> [186,] "inv_chi_square_cdf" "inv_chi_square_cdf_log"
#> [187,] "inv_chi_square_lccdf" "inv_chi_square_lcdf"
#> [188,] "inv_chi_square_lpdf" "inv_chi_square_rng"
#> [189,] "inv_cloglog" "inv_erfc"
#> [190,] "inv_gamma_ccdf_log" "inv_gamma_cdf"
#> [191,] "inv_gamma_cdf_log" "inv_gamma_lccdf"
#> [192,] "inv_gamma_lcdf" "inv_gamma_lpdf"
#> [193,] "inv_gamma_rng" "inv_inc_beta"
#> [194,] "inv_logit" "inv_sqrt"
#> [195,] "inv_square" "inv_wishart_cholesky_lpdf"
#> [196,] "inv_wishart_cholesky_rng" "inv_wishart_lpdf"
#> [197,] "inv_wishart_rng" "invalid_argument"
#> [198,] "invalid_argument_vec" "inverse"
#> [199,] "inverse_softmax" "inverse_spd"
#> [200,] "is_any_nan" "is_arena_matrix"
#> [201,] "is_autodiff" "is_base_pointer_convertible"
#> [202,] "is_cholesky_factor" "is_cholesky_factor_corr"
#> [203,] "is_column_index" "is_complex"
#> [204,] "is_constant" "is_container"
#> [205,] "is_container_or_var_matrix" "is_corr_matrix"
#> [206,] "is_dense_dynamic" "is_detected"
#> [207,] "is_double_or_int" "is_eigen"
#> [208,] "is_eigen_dense_base" "is_eigen_dense_dynamic"
#> [209,] "is_eigen_matrix" "is_eigen_matrix_base"
#> [210,] "is_eigen_sparse_base" "is_fvar"
#> [211,] "is_inf" "is_integer"
#> [212,] "is_kernel_expression" "is_ldlt_factor"
#> [213,] "is_less_or_equal" "is_lower_triangular"
#> [214,] "is_mat_finite" "is_matching_dims"
#> [215,] "is_matching_size" "is_matrix"
#> [216,] "is_matrix_cl" "is_nan"
#> [217,] "is_nonpositive_integer" "is_nonzero_size"
#> [218,] "is_not_nan" "is_ordered"
#> [219,] "is_plain_type" "is_pos_definite"
#> [220,] "is_positive" "is_real"
#> [221,] "is_rev_matrix" "is_scal_finite"
#> [222,] "is_size_match" "is_square"
#> [223,] "is_stan_scalar" "is_stan_scalar_or_eigen"
#> [224,] "is_string_convertible" "is_symmetric"
#> [225,] "is_tuple" "is_uninitialized"
#> [226,] "is_unit_vector" "is_var"
#> [227,] "is_var_and_matrix_types" "is_var_dense_dynamic"
#> [228,] "is_var_eigen" "is_var_matrix"
#> [229,] "is_var_or_arithmetic" "is_vari"
#> [230,] "is_vector" "is_vector_like"
#> [231,] "isfinite" "isinf"
#> [232,] "isnan" "isnormal"
#> [233,] "lambert_w" "lb_constrain"
#> [234,] "lb_free" "lbeta"
#> [235,] "ldexp" "lgamma"
#> [236,] "lgamma_stirling" "lgamma_stirling_diff"
#> [237,] "linspaced_array" "linspaced_int_array"
#> [238,] "linspaced_row_vector" "linspaced_vector"
#> [239,] "lkj_corr_cholesky_lpdf" "lkj_corr_cholesky_rng"
#> [240,] "lkj_corr_lpdf" "lkj_corr_rng"
#> [241,] "lkj_cov_lpdf" "lmgamma"
#> [242,] "lmultiply" "log"
#> [243,] "log10" "log1m"
#> [244,] "log1m_exp" "log1m_inv_logit"
#> [245,] "log1p" "log1p_exp"
#> [246,] "log2" "log_determinant"
#> [247,] "log_determinant_ldlt" "log_determinant_spd"
#> [248,] "log_diff_exp" "log_falling_factorial"
#> [249,] "log_inv_logit" "log_inv_logit_diff"
#> [250,] "log_mix" "log_modified_bessel_first_kind"
#> [251,] "log_rising_factorial" "log_softmax"
#> [252,] "log_sum_exp" "log_sum_exp_signed"
#> [253,] "logb" "logical_and"
#> [254,] "logical_eq" "logical_gt"
#> [255,] "logical_gte" "logical_lt"
#> [256,] "logical_lte" "logical_negation"
#> [257,] "logical_neq" "logical_or"
#> [258,] "logistic_ccdf_log" "logistic_cdf"
#> [259,] "logistic_cdf_log" "logistic_lccdf"
#> [260,] "logistic_lcdf" "logistic_lpdf"
#> [261,] "logistic_rng" "logit"
#> [262,] "loglogistic_cdf" "loglogistic_lpdf"
#> [263,] "loglogistic_rng" "lognormal_ccdf_log"
#> [264,] "lognormal_cdf" "lognormal_cdf_log"
#> [265,] "lognormal_lccdf" "lognormal_lcdf"
#> [266,] "lognormal_lpdf" "lognormal_rng"
#> [267,] "lub_constrain" "lub_free"
#> [268,] "make_iter_name" "make_nu"
#> [269,] "map_rect" "map_rect_combine"
#> [270,] "map_rect_concurrent" "map_rect_mpi"
#> [271,] "map_rect_reduce" "matrix_exp"
#> [272,] "matrix_exp_2x2" "matrix_exp_action_handler"
#> [273,] "matrix_exp_multiply" "matrix_exp_pade"
#> [274,] "matrix_normal_prec_lpdf" "matrix_normal_prec_rng"
#> [275,] "matrix_power" "max"
#> [276,] "max_size" "max_size_mvt"
#> [277,] "mdivide_left" "mdivide_left_ldlt"
#> [278,] "mdivide_left_spd" "mdivide_left_tri"
#> [279,] "mdivide_left_tri_low" "mdivide_right"
#> [280,] "mdivide_right_ldlt" "mdivide_right_spd"
#> [281,] "mdivide_right_tri" "mdivide_right_tri_low"
#> [282,] "mean" "min"
#> [283,] "minus" "modified_bessel_first_kind"
#> [284,] "modified_bessel_second_kind" "modify_eigen_options"
#> [285,] "modulus" "mpi_cluster"
#> [286,] "mpi_command" "mpi_distributed_apply"
#> [287,] "mpi_parallel_call" "multi_gp_cholesky_lpdf"
#> [288,] "multi_gp_lpdf" "multi_normal_cholesky_lpdf"
#> [289,] "multi_normal_cholesky_rng" "multi_normal_lpdf"
#> [290,] "multi_normal_prec_lpdf" "multi_normal_prec_rng"
#> [291,] "multi_normal_rng" "multi_student_t_cholesky_lpdf"
#> [292,] "multi_student_t_cholesky_rng" "multi_student_t_lpdf"
#> [293,] "multi_student_t_rng" "multinomial_logit_lpmf"
#> [294,] "multinomial_logit_rng" "multinomial_lpmf"
#> [295,] "multinomial_rng" "multiply"
#> [296,] "multiply_log" "multiply_lower_tri_self_transpose"
#> [297,] "neg_binomial_2_ccdf_log" "neg_binomial_2_cdf"
#> [298,] "neg_binomial_2_cdf_log" "neg_binomial_2_lccdf"
#> [299,] "neg_binomial_2_lcdf" "neg_binomial_2_log_glm_lpmf"
#> [300,] "neg_binomial_2_log_lpmf" "neg_binomial_2_log_rng"
#> [301,] "neg_binomial_2_lpmf" "neg_binomial_2_rng"
#> [302,] "neg_binomial_ccdf_log" "neg_binomial_cdf"
#> [303,] "neg_binomial_cdf_log" "neg_binomial_lccdf"
#> [304,] "neg_binomial_lcdf" "neg_binomial_lpmf"
#> [305,] "neg_binomial_rng" "norm"
#> [306,] "norm1" "norm2"
#> [307,] "normal_ccdf_log" "normal_cdf"
#> [308,] "normal_cdf_log" "normal_id_glm_lpdf"
#> [309,] "normal_lccdf" "normal_lcdf"
#> [310,] "normal_lpdf" "normal_rng"
#> [311,] "normal_sufficient_lpdf" "num_elements"
#> [312,] "ode_ckrk" "ode_rk45"
#> [313,] "ode_store_sensitivities" "offset_multiplier_constrain"
#> [314,] "offset_multiplier_free" "one_hot_array"
#> [315,] "one_hot_int_array" "one_hot_row_vector"
#> [316,] "one_hot_vector" "ones_array"
#> [317,] "ones_int_array" "ones_row_vector"
#> [318,] "ones_vector" "operands_and_partials"
#> [319,] "operator_addition" "operator_division"
#> [320,] "operator_equal_equal" "operator_minus"
#> [321,] "operator_multiplication" "operator_not_equal"
#> [322,] "operator_plus" "operator_subtraction"
#> [323,] "ordered_constrain" "ordered_free"
#> [324,] "ordered_logistic_glm_lpmf" "ordered_logistic_lpmf"
#> [325,] "ordered_logistic_rng" "ordered_probit_lpmf"
#> [326,] "ordered_probit_rng" "out_of_range"
#> [327,] "owens_t" "pareto_ccdf_log"
#> [328,] "pareto_cdf" "pareto_cdf_log"
#> [329,] "pareto_lccdf" "pareto_lcdf"
#> [330,] "pareto_lpdf" "pareto_rng"
#> [331,] "pareto_type_2_ccdf_log" "pareto_type_2_cdf"
#> [332,] "pareto_type_2_cdf_log" "pareto_type_2_lccdf"
#> [333,] "pareto_type_2_lcdf" "pareto_type_2_lpdf"
#> [334,] "pareto_type_2_rng" "partials_propagator"
#> [335,] "partials_return_type" "partials_type"
#> [336,] "plain_type" "plus"
#> [337,] "poisson_binomial_ccdf_log" "poisson_binomial_cdf"
#> [338,] "poisson_binomial_cdf_log" "poisson_binomial_lccdf"
#> [339,] "poisson_binomial_lcdf" "poisson_binomial_log_probs"
#> [340,] "poisson_binomial_lpmf" "poisson_binomial_rng"
#> [341,] "poisson_ccdf_log" "poisson_cdf"
#> [342,] "poisson_cdf_log" "poisson_lccdf"
#> [343,] "poisson_lcdf" "poisson_log_glm_lpmf"
#> [344,] "poisson_log_lpmf" "poisson_log_rng"
#> [345,] "poisson_lpmf" "poisson_rng"
#> [346,] "polar" "positive_constrain"
#> [347,] "positive_free" "positive_ordered_constrain"
#> [348,] "positive_ordered_free" "possibly_sum"
#> [349,] "pow" "primitive_value"
#> [350,] "prob_constrain" "prob_free"
#> [351,] "prod" "proj"
#> [352,] "promote_args" "promote_elements"
#> [353,] "promote_scalar" "promote_scalar_type"
#> [354,] "pseudo_eigenvalues" "pseudo_eigenvectors"
#> [355,] "qr" "qr_Q"
#> [356,] "qr_R" "qr_thin"
#> [357,] "qr_thin_Q" "qr_thin_R"
#> [358,] "quad_form" "quad_form_diag"
#> [359,] "quad_form_sym" "quantile"
#> [360,] "rank" "rayleigh_ccdf_log"
#> [361,] "rayleigh_cdf" "rayleigh_cdf_log"
#> [362,] "rayleigh_lccdf" "rayleigh_lcdf"
#> [363,] "rayleigh_lpdf" "rayleigh_rng"
#> [364,] "read_corr_L" "read_corr_matrix"
#> [365,] "read_cov_L" "read_cov_matrix"
#> [366,] "real" "reduce_sum"
#> [367,] "reduce_sum_static" "ref_type"
#> [368,] "rep_array" "rep_matrix"
#> [369,] "rep_row_vector" "rep_vector"
#> [370,] "require_generics" "require_helpers"
#> [371,] "resize" "return_type"
#> [372,] "reverse" "rising_factorial"
#> [373,] "round" "row"
#> [374,] "rows" "rows_dot_product"
#> [375,] "rows_dot_self" "scalar_seq_view"
#> [376,] "scalar_type" "scalbn"
#> [377,] "scale_matrix_exp_multiply" "scaled_add"
#> [378,] "scaled_inv_chi_square_ccdf_log" "scaled_inv_chi_square_cdf"
#> [379,] "scaled_inv_chi_square_cdf_log" "scaled_inv_chi_square_lccdf"
#> [380,] "scaled_inv_chi_square_lcdf" "scaled_inv_chi_square_lpdf"
#> [381,] "scaled_inv_chi_square_rng" "sd"
#> [382,] "segment" "select"
#> [383,] "seq_view" "serializer"
#> [384,] "sign" "signbit"
#> [385,] "simplex_constrain" "simplex_free"
#> [386,] "sin" "singular_values"
#> [387,] "sinh" "size"
#> [388,] "size_mvt" "size_zero"
#> [389,] "skew_double_exponential_ccdf_log" "skew_double_exponential_cdf"
#> [390,] "skew_double_exponential_cdf_log" "skew_double_exponential_lccdf"
#> [391,] "skew_double_exponential_lcdf" "skew_double_exponential_lpdf"
#> [392,] "skew_double_exponential_rng" "skew_normal_ccdf_log"
#> [393,] "skew_normal_cdf" "skew_normal_cdf_log"
#> [394,] "skew_normal_lccdf" "skew_normal_lcdf"
#> [395,] "skew_normal_lpdf" "skew_normal_rng"
#> [396,] "softmax" "sort_asc"
#> [397,] "sort_desc" "sort_indices"
#> [398,] "sort_indices_asc" "sort_indices_desc"
#> [399,] "sqrt" "square"
#> [400,] "squared_distance" "stan_print"
#> [401,] "static_select" "std_normal_ccdf_log"
#> [402,] "std_normal_cdf" "std_normal_cdf_log"
#> [403,] "std_normal_lccdf" "std_normal_lcdf"
#> [404,] "std_normal_log_qf" "std_normal_lpdf"
#> [405,] "std_normal_rng" "step"
#> [406,] "stochastic_column_constrain" "stochastic_column_free"
#> [407,] "stochastic_row_constrain" "stochastic_row_free"
#> [408,] "student_t_ccdf_log" "student_t_cdf"
#> [409,] "student_t_cdf_log" "student_t_lccdf"
#> [410,] "student_t_lcdf" "student_t_lpdf"
#> [411,] "student_t_rng" "sub_col"
#> [412,] "sub_row" "subtract"
#> [413,] "sum" "sum_to_zero_constrain"
#> [414,] "sum_to_zero_free" "svd"
#> [415,] "svd_U" "svd_V"
#> [416,] "symmetrize_from_lower_tri" "symmetrize_from_upper_tri"
#> [417,] "system_error" "tail"
#> [418,] "tan" "tanh"
#> [419,] "tcrossprod" "tgamma"
#> [420,] "throw_domain_error" "throw_domain_error_mat"
#> [421,] "throw_domain_error_vec" "to_array_1d"
#> [422,] "to_array_2d" "to_complex"
#> [423,] "to_int" "to_matrix"
#> [424,] "to_ref" "to_row_vector"
#> [425,] "to_vector" "trace"
#> [426,] "trace_gen_inv_quad_form_ldlt" "trace_gen_quad_form"
#> [427,] "trace_inv_quad_form_ldlt" "trace_quad_form"
#> [428,] "transpose" "trigamma"
#> [429,] "trunc" "typedefs"
#> [430,] "ub_constrain" "ub_free"
#> [431,] "uniform_ccdf_log" "uniform_cdf"
#> [432,] "uniform_cdf_log" "uniform_lccdf"
#> [433,] "uniform_lcdf" "uniform_lpdf"
#> [434,] "uniform_rng" "uniform_simplex"
#> [435,] "unit_vector_constrain" "unit_vector_free"
#> [436,] "unitspaced_array" "validate_non_negative_index"
#> [437,] "validate_positive_index" "validate_unit_vector_index"
#> [438,] "value_of" "value_of_rec"
#> [439,] "value_type" "variance"
#> [440,] "vec_concat" "vector_seq_view"
#> [441,] "void_t" "von_mises_ccdf_log"
#> [442,] "von_mises_cdf" "von_mises_cdf_log"
#> [443,] "von_mises_lccdf" "von_mises_lcdf"
#> [444,] "von_mises_lpdf" "von_mises_rng"
#> [445,] "weibull_ccdf_log" "weibull_cdf"
#> [446,] "weibull_cdf_log" "weibull_lccdf"
#> [447,] "weibull_lcdf" "weibull_lpdf"
#> [448,] "weibull_rng" "welford_covar_estimator"
#> [449,] "welford_var_estimator" "wiener5_lpdf"
#> [450,] "wiener_full_lpdf" "wiener_lpdf"
#> [451,] "wishart_cholesky_lpdf" "wishart_cholesky_rng"
#> [452,] "wishart_lpdf" "wishart_rng"
#> [453,] "zeros_array" "zeros_int_array"
#> [454,] "zeros_row_vector" "zeros_vector"
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 (x − a)⊤(x − a)
which has a global minimum when x = a. To
find this minimum with autodifferentiation, we need to define the
objective function. Then, its gradient with respect to x, which we know is 2(x − a) 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 2I, 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
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.
Next, we consider the system of differential equations $$\frac{d}{dt}\mathbf{y} = \mathbf{A}\mathbf{y}$$ where A is a square matrix such as that for a simple harmonic oscillator
$$\mathbf{A} = \begin{bmatrix}0 & 1 \\ -1 & -\theta\end{bmatrix}$$ for θ ∈ (0, 1). The solution for yt = etAy0 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.
map_rect
FunctionThe 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(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, 226 − 5 = 67, 108, 859 is a prime number.
reduce_sum
FunctionThe 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:
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' <0x55ff7c550880>
#> 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.