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