| 1 | /** |
| 2 | * Copyright 2014-2024, XGBoost Contributors |
| 3 | */ |
| 4 | #include <dmlc/common.h> |
| 5 | #include <dmlc/omp.h> |
| 6 | #include <xgboost/c_api.h> |
| 7 | #include <xgboost/context.h> |
| 8 | #include <xgboost/data.h> |
| 9 | #include <xgboost/logging.h> |
| 10 | |
| 11 | #include <algorithm> |
| 12 | #include <cmath> |
| 13 | #include <cstdint> |
| 14 | #include <cstdio> |
| 15 | #include <cstring> |
| 16 | #include <memory> |
| 17 | #include <limits> |
| 18 | #include <sstream> |
| 19 | #include <string> |
| 20 | #include <utility> |
| 21 | #include <vector> |
| 22 | |
| 23 | #include "../../src/c_api/c_api_error.h" |
| 24 | #include "../../src/c_api/c_api_utils.h" // MakeSparseFromPtr |
| 25 | #include "../../src/common/threading_utils.h" |
| 26 | #include "../../src/data/array_interface.h" // for ArrayInterface |
| 27 | |
| 28 | #include "./xgboost_R.h" // Must follow other includes. |
| 29 | |
| 30 | #ifdef _MSC_VER |
| 31 | #error "Compilation of R package with MSVC is not supported due to issues handling R headers" |
| 32 | #endif |
| 33 | |
| 34 | namespace { |
| 35 | |
| 36 | /* Note: this class is used as a throwable exception. |
| 37 | Some xgboost C functions that use callbacks will catch exceptions |
| 38 | that happen inside of the callback execution, hence it purposefully |
| 39 | doesn't inherit from 'std::exception' even if used as such. */ |
| 40 | struct ErrorWithUnwind {}; |
| 41 | |
| 42 | void ThrowExceptionFromRError(void *, Rboolean jump) { |
| 43 | if (jump) { |
| 44 | throw ErrorWithUnwind(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | struct PtrToConstChar { |
| 49 | const char *ptr; |
| 50 | }; |
| 51 | |
| 52 | SEXP WrappedMkChar(void *void_ptr) { |
| 53 | return Rf_mkChar(static_cast<PtrToConstChar*>(void_ptr)->ptr); |
| 54 | } |
| 55 | |
| 56 | SEXP SafeMkChar(const char *c_str, SEXP continuation_token) { |
| 57 | PtrToConstChar ptr_struct{c_str}; |
| 58 | return R_UnwindProtect( |
| 59 | WrappedMkChar, static_cast<void*>(&ptr_struct), |
| 60 | ThrowExceptionFromRError, nullptr, |
| 61 | continuation_token); |
| 62 | } |
| 63 | |
| 64 | struct RFunAndEnv { |
| 65 | SEXP R_fun; |
| 66 | SEXP R_calling_env; |
| 67 | }; |
| 68 | |
| 69 | SEXP WrappedExecFun(void *void_ptr) { |
| 70 | RFunAndEnv *r_fun_and_env = static_cast<RFunAndEnv*>(void_ptr); |
| 71 | SEXP f_expr = Rf_protect(Rf_lang1(r_fun_and_env->R_fun)); |
| 72 | SEXP out = Rf_protect(Rf_eval(f_expr, r_fun_and_env->R_calling_env)); |
| 73 | Rf_unprotect(2); |
| 74 | return out; |
| 75 | } |
| 76 | |
| 77 | SEXP SafeExecFun(SEXP R_fun, SEXP R_calling_env, SEXP continuation_token) { |
| 78 | RFunAndEnv r_fun_and_env{R_fun, R_calling_env}; |
| 79 | return R_UnwindProtect( |
| 80 | WrappedExecFun, static_cast<void*>(&r_fun_and_env), |
| 81 | ThrowExceptionFromRError, nullptr, |
| 82 | continuation_token); |
| 83 | } |
| 84 | |
| 85 | SEXP WrappedAllocReal(void *void_ptr) { |
| 86 | size_t *size = static_cast<size_t*>(void_ptr); |
| 87 | return Rf_allocVector(REALSXP, *size); |
| 88 | } |
| 89 | |
| 90 | SEXP SafeAllocReal(size_t size, SEXP continuation_token) { |
| 91 | return R_UnwindProtect( |
| 92 | WrappedAllocReal, static_cast<void*>(&size), |
| 93 | ThrowExceptionFromRError, nullptr, |
| 94 | continuation_token); |
| 95 | } |
| 96 | |
| 97 | SEXP WrappedAllocInteger(void *void_ptr) { |
| 98 | size_t *size = static_cast<size_t*>(void_ptr); |
| 99 | return Rf_allocVector(INTSXP, *size); |
| 100 | } |
| 101 | |
| 102 | SEXP SafeAllocInteger(size_t size, SEXP continuation_token) { |
| 103 | return R_UnwindProtect( |
| 104 | WrappedAllocInteger, static_cast<void*>(&size), |
| 105 | ThrowExceptionFromRError, nullptr, |
| 106 | continuation_token); |
| 107 | } |
| 108 | |
| 109 | [[nodiscard]] std::string MakeArrayInterfaceFromRMat(SEXP R_mat) { |
| 110 | SEXP mat_dims = Rf_getAttrib(R_mat, R_DimSymbol); |
| 111 | if (Rf_xlength(mat_dims) > 2) { |
| 112 | LOG(FATAL) << "Passed input array with more than two dimensions, which is not supported."; |
| 113 | } |
| 114 | const int *ptr_mat_dims = INTEGER(mat_dims); |
| 115 | |
| 116 | // Lambda for type dispatch. |
| 117 | auto make_matrix = [=](auto const *ptr) { |
| 118 | using namespace xgboost; // NOLINT |
| 119 | using T = std::remove_pointer_t<decltype(ptr)>; |
| 120 | |
| 121 | auto m = linalg::MatrixView<T>{ |
| 122 | common::Span{ptr, |
| 123 | static_cast<std::size_t>(ptr_mat_dims[0]) * static_cast<std::size_t>(ptr_mat_dims[1])}, |
| 124 | {ptr_mat_dims[0], ptr_mat_dims[1]}, // Shape |
| 125 | DeviceOrd::CPU(), |
| 126 | linalg::Order::kF // R uses column-major |
| 127 | }; |
| 128 | CHECK(m.FContiguous()); |
| 129 | return linalg::ArrayInterfaceStr(m); |
| 130 | }; |
| 131 | |
| 132 | const SEXPTYPE arr_type = TYPEOF(R_mat); |
| 133 | switch (arr_type) { |
| 134 | case REALSXP: |
| 135 | return make_matrix(REAL(R_mat)); |
| 136 | case INTSXP: |
| 137 | return make_matrix(INTEGER(R_mat)); |
| 138 | case LGLSXP: |
| 139 | return make_matrix(LOGICAL(R_mat)); |
| 140 | default: |
| 141 | LOG(FATAL) << "Array or matrix has unsupported type."; |
| 142 | } |
| 143 | |
| 144 | LOG(FATAL) << "Not reachable"; |
| 145 | return ""; |
| 146 | } |
| 147 | |
| 148 | [[nodiscard]] std::string MakeArrayInterfaceFromRVector(SEXP R_vec) { |
| 149 | const size_t vec_len = Rf_xlength(R_vec); |
| 150 | |
| 151 | // Lambda for type dispatch. |
| 152 | auto make_vec = [=](auto const *ptr) { |
| 153 | using namespace xgboost; // NOLINT |
| 154 | auto v = linalg::MakeVec(ptr, vec_len); |
| 155 | return linalg::ArrayInterfaceStr(v); |
| 156 | }; |
| 157 | |
| 158 | const SEXPTYPE arr_type = TYPEOF(R_vec); |
| 159 | switch (arr_type) { |
| 160 | case REALSXP: |
| 161 | return make_vec(REAL(R_vec)); |
| 162 | case INTSXP: |
| 163 | return make_vec(INTEGER(R_vec)); |
| 164 | case LGLSXP: |
| 165 | return make_vec(LOGICAL(R_vec)); |
| 166 | default: |
| 167 | LOG(FATAL) << "Array or matrix has unsupported type."; |
| 168 | } |
| 169 | |
| 170 | LOG(FATAL) << "Not reachable"; |
| 171 | return ""; |
| 172 | } |
| 173 | |
| 174 | [[nodiscard]] std::string MakeArrayInterfaceFromRDataFrame(SEXP R_df) { |
| 175 | auto make_vec = [&](auto const *ptr, std::size_t len) { |
| 176 | auto v = xgboost::linalg::MakeVec(ptr, len); |
| 177 | return xgboost::linalg::ArrayInterface(v); |
| 178 | }; |
| 179 | |
| 180 | R_xlen_t n_features = Rf_xlength(R_df); |
| 181 | std::vector<xgboost::Json> array(n_features); |
| 182 | CHECK_GT(n_features, 0); |
| 183 | std::size_t len = Rf_xlength(VECTOR_ELT(R_df, 0)); |
| 184 | |
| 185 | // The `data.frame` in R actually converts all data into numeric. The other type |
| 186 | // handlers here are not used. At the moment they are kept as a reference for when we |
| 187 | // can avoid making data copies during transformation. |
| 188 | for (R_xlen_t i = 0; i < n_features; ++i) { |
| 189 | switch (TYPEOF(VECTOR_ELT(R_df, i))) { |
| 190 | case INTSXP: { |
| 191 | auto const *ptr = INTEGER(VECTOR_ELT(R_df, i)); |
| 192 | array[i] = make_vec(ptr, len); |
| 193 | break; |
| 194 | } |
| 195 | case REALSXP: { |
| 196 | auto const *ptr = REAL(VECTOR_ELT(R_df, i)); |
| 197 | array[i] = make_vec(ptr, len); |
| 198 | break; |
| 199 | } |
| 200 | case LGLSXP: { |
| 201 | auto const *ptr = LOGICAL(VECTOR_ELT(R_df, i)); |
| 202 | array[i] = make_vec(ptr, len); |
| 203 | break; |
| 204 | } |
| 205 | default: { |
| 206 | LOG(FATAL) << "data.frame has unsupported type."; |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | xgboost::Json jinterface{std::move(array)}; |
| 212 | return xgboost::Json::Dump(jinterface); |
| 213 | } |
| 214 | |
| 215 | void AddMissingToJson(xgboost::Json *jconfig, SEXP missing, SEXPTYPE arr_type) { |
| 216 | if (Rf_isNull(missing) || ISNAN(Rf_asReal(missing))) { |
| 217 | // missing is not specified |
| 218 | if (arr_type == REALSXP) { |
| 219 | (*jconfig)["missing"] = std::numeric_limits<double>::quiet_NaN(); |
| 220 | } else { |
| 221 | (*jconfig)["missing"] = R_NaInt; |
| 222 | } |
| 223 | } else { |
| 224 | // missing specified |
| 225 | (*jconfig)["missing"] = Rf_asReal(missing); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | [[nodiscard]] std::string MakeJsonConfigForArray(SEXP missing, SEXP n_threads, SEXPTYPE arr_type) { |
| 230 | using namespace ::xgboost; // NOLINT |
| 231 | Json jconfig{Object{}}; |
| 232 | AddMissingToJson(&jconfig, missing, arr_type); |
| 233 | jconfig["nthread"] = Rf_asInteger(n_threads); |
| 234 | return Json::Dump(jconfig); |
| 235 | } |
| 236 | |
| 237 | // Allocate a R vector and copy an array interface encoded object to it. |
| 238 | [[nodiscard]] SEXP CopyArrayToR(const char *array_str, SEXP ctoken) { |
| 239 | xgboost::ArrayInterface<1> array{xgboost::StringView{array_str}}; |
| 240 | // R supports only int and double. |
| 241 | bool is_int_type = |
| 242 | xgboost::DispatchDType(array.type, [](auto t) { return std::is_integral_v<decltype(t)>; }); |
| 243 | bool is_float = xgboost::DispatchDType( |
| 244 | array.type, [](auto v) { return std::is_floating_point_v<decltype(v)>; }); |
| 245 | CHECK(is_int_type || is_float) << "Internal error: Invalid DType."; |
| 246 | CHECK(array.is_contiguous) << "Internal error: Return by XGBoost should be contiguous"; |
| 247 | |
| 248 | // Note: the only case in which this will receive an integer type is |
| 249 | // for the 'indptr' part of the quantile cut outputs, which comes |
| 250 | // in sorted order, so the last element contains the maximum value. |
| 251 | bool fits_into_C_int = xgboost::DispatchDType(array.type, [&](auto t) { |
| 252 | using T = decltype(t); |
| 253 | if (!std::is_integral_v<decltype(t)>) { |
| 254 | return false; |
| 255 | } |
| 256 | auto ptr = static_cast<T const *>(array.data); |
| 257 | T last_elt = ptr[array.n - 1]; |
| 258 | if (last_elt < 0) { |
| 259 | last_elt = -last_elt; // no std::abs overload for all possible types |
| 260 | } |
| 261 | return last_elt <= std::numeric_limits<int>::max(); |
| 262 | }); |
| 263 | bool use_int = is_int_type && fits_into_C_int; |
| 264 | |
| 265 | // Allocate memory in R |
| 266 | SEXP out = |
| 267 | Rf_protect(use_int ? SafeAllocInteger(array.n, ctoken) : SafeAllocReal(array.n, ctoken)); |
| 268 | |
| 269 | xgboost::DispatchDType(array.type, [&](auto t) { |
| 270 | using T = decltype(t); |
| 271 | auto in_ptr = static_cast<T const *>(array.data); |
| 272 | if (use_int) { |
| 273 | auto out_ptr = INTEGER(out); |
| 274 | std::copy_n(in_ptr, array.n, out_ptr); |
| 275 | } else { |
| 276 | auto out_ptr = REAL(out); |
| 277 | std::copy_n(in_ptr, array.n, out_ptr); |
| 278 | } |
| 279 | }); |
| 280 | |
| 281 | Rf_unprotect(1); |
| 282 | return out; |
| 283 | } |
| 284 | } // namespace |
| 285 | |
| 286 | /*! |
| 287 | * \brief macro to annotate begin of api |
| 288 | */ |
| 289 | #define R_API_BEGIN() \ |
| 290 | try { \ |
| 291 | /* Note: an R error triggers a long jump, hence all C++ objects that |
| 292 | allocated memory through non-R allocators, including the exception |
| 293 | object, need to be destructed before triggering the R error. |
| 294 | In order to preserve the error message, it gets copied to a temporary |
| 295 | buffer, and the R error section is reached through a 'goto' statement |
| 296 | that bypasses usual function control flow. */ |
| 297 | namespace { |
| 298 | constexpr std::size_t MsgSize = 512; |
| 299 | char cpp_ex_msg[MsgSize]; |
| 300 | } // anonymous namespace |
| 301 | |
| 302 | /*! |
| 303 | * \brief macro to annotate end of api |
| 304 | */ |
| 305 | #define R_API_END() \ |
| 306 | } \ |
| 307 | catch (std::exception & e) { \ |
| 308 | cpp_ex_msg[MsgSize - 1] = 0; \ |
| 309 | std::strncpy(cpp_ex_msg, e.what(), MsgSize - 1); \ |
| 310 | goto throw_cpp_ex_as_R_err; \ |
| 311 | } \ |
| 312 | if (false) { \ |
| 313 | throw_cpp_ex_as_R_err: \ |
| 314 | Rf_error("%s", cpp_ex_msg); \ |
| 315 | } |
| 316 | |
| 317 | /** |
| 318 | * @brief Macro for checking XGBoost return code. |
| 319 | */ |
| 320 | #define CHECK_CALL(__rc) \ |
| 321 | if ((__rc) != 0) { \ |
| 322 | Rf_error("%s", XGBGetLastError()); \ |
| 323 | } |
| 324 | |
| 325 | using dmlc::BeginPtr; |
| 326 | |
| 327 | XGB_DLL SEXP XGCheckNullPtr_R(SEXP handle) { |
| 328 | return Rf_ScalarLogical(R_ExternalPtrAddr(handle) == nullptr); |
| 329 | } |
| 330 | |
| 331 | XGB_DLL SEXP XGSetArrayDimNamesInplace_R(SEXP arr, SEXP dim_names) { |
| 332 | Rf_setAttrib(arr, R_DimNamesSymbol, dim_names); |
| 333 | return R_NilValue; |
| 334 | } |
| 335 | |
| 336 | XGB_DLL SEXP XGSetVectorNamesInplace_R(SEXP arr, SEXP names) { |
| 337 | Rf_setAttrib(arr, R_NamesSymbol, names); |
| 338 | return R_NilValue; |
| 339 | } |
| 340 | |
| 341 | namespace { |
| 342 | void _DMatrixFinalizer(SEXP ext) { |
| 343 | R_API_BEGIN(); |
| 344 | if (R_ExternalPtrAddr(ext) == NULL) return; |
| 345 | CHECK_CALL(XGDMatrixFree(R_ExternalPtrAddr(ext))); |
| 346 | R_ClearExternalPtr(ext); |
| 347 | R_API_END(); |
| 348 | } |
| 349 | } /* namespace */ |
| 350 | |
| 351 | XGB_DLL SEXP XGBSetGlobalConfig_R(SEXP json_str) { |
| 352 | R_API_BEGIN(); |
| 353 | CHECK_CALL(XGBSetGlobalConfig(CHAR(Rf_asChar(json_str)))); |
| 354 | R_API_END(); |
| 355 | return R_NilValue; |
| 356 | } |
| 357 | |
| 358 | XGB_DLL SEXP XGBGetGlobalConfig_R() { |
| 359 | const char* json_str; |
| 360 | R_API_BEGIN(); |
| 361 | CHECK_CALL(XGBGetGlobalConfig(&json_str)); |
| 362 | R_API_END(); |
| 363 | return Rf_mkString(json_str); |
| 364 | } |
| 365 | |
| 366 | XGB_DLL SEXP XGDMatrixCreateFromURI_R(SEXP uri, SEXP silent, SEXP data_split_mode) { |
| 367 | SEXP ret = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 368 | SEXP uri_char = Rf_protect(Rf_asChar(uri)); |
| 369 | const char *uri_ptr = CHAR(uri_char); |
| 370 | R_API_BEGIN(); |
| 371 | xgboost::Json jconfig{xgboost::Object{}}; |
| 372 | jconfig["uri"] = std::string(uri_ptr); |
| 373 | jconfig["silent"] = Rf_asLogical(silent); |
| 374 | jconfig["data_split_mode"] = Rf_asInteger(data_split_mode); |
| 375 | const std::string sconfig = xgboost::Json::Dump(jconfig); |
| 376 | DMatrixHandle handle; |
| 377 | CHECK_CALL(XGDMatrixCreateFromURI(sconfig.c_str(), &handle)); |
| 378 | R_SetExternalPtrAddr(ret, handle); |
| 379 | R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE); |
| 380 | R_API_END(); |
| 381 | Rf_unprotect(2); |
| 382 | return ret; |
| 383 | } |
| 384 | |
| 385 | XGB_DLL SEXP XGDMatrixCreateFromMat_R(SEXP mat, SEXP missing, SEXP n_threads) { |
| 386 | SEXP ret = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 387 | R_API_BEGIN(); |
| 388 | |
| 389 | DMatrixHandle handle; |
| 390 | int res_code; |
| 391 | { |
| 392 | auto array_str = MakeArrayInterfaceFromRMat(mat); |
| 393 | auto config_str = MakeJsonConfigForArray(missing, n_threads, TYPEOF(mat)); |
| 394 | |
| 395 | res_code = XGDMatrixCreateFromDense(array_str.c_str(), config_str.c_str(), &handle); |
| 396 | } |
| 397 | CHECK_CALL(res_code); |
| 398 | R_SetExternalPtrAddr(ret, handle); |
| 399 | R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE); |
| 400 | R_API_END(); |
| 401 | Rf_unprotect(1); |
| 402 | return ret; |
| 403 | } |
| 404 | |
| 405 | XGB_DLL SEXP XGDMatrixCreateFromDF_R(SEXP df, SEXP missing, SEXP n_threads) { |
| 406 | SEXP ret = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 407 | R_API_BEGIN(); |
| 408 | |
| 409 | DMatrixHandle handle; |
| 410 | std::int32_t rc{0}; |
| 411 | { |
| 412 | const std::string sinterface = MakeArrayInterfaceFromRDataFrame(df); |
| 413 | xgboost::Json jconfig{xgboost::Object{}}; |
| 414 | jconfig["missing"] = Rf_asReal(missing); |
| 415 | jconfig["nthread"] = Rf_asInteger(n_threads); |
| 416 | std::string sconfig = xgboost::Json::Dump(jconfig); |
| 417 | |
| 418 | rc = XGDMatrixCreateFromColumnar(sinterface.c_str(), sconfig.c_str(), &handle); |
| 419 | } |
| 420 | |
| 421 | CHECK_CALL(rc); |
| 422 | R_SetExternalPtrAddr(ret, handle); |
| 423 | R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE); |
| 424 | R_API_END(); |
| 425 | Rf_unprotect(1); |
| 426 | |
| 427 | return ret; |
| 428 | } |
| 429 | |
| 430 | namespace { |
| 431 | void CreateFromSparse(SEXP indptr, SEXP indices, SEXP data, std::string *indptr_str, |
| 432 | std::string *indices_str, std::string *data_str) { |
| 433 | const int *p_indptr = INTEGER(indptr); |
| 434 | const int *p_indices = INTEGER(indices); |
| 435 | const double *p_data = REAL(data); |
| 436 | |
| 437 | auto nindptr = static_cast<std::size_t>(Rf_xlength(indptr)); |
| 438 | auto ndata = static_cast<std::size_t>(Rf_xlength(data)); |
| 439 | CHECK_EQ(ndata, p_indptr[nindptr - 1]); |
| 440 | xgboost::detail::MakeSparseFromPtr(p_indptr, p_indices, p_data, nindptr, indptr_str, indices_str, |
| 441 | data_str); |
| 442 | } |
| 443 | } // namespace |
| 444 | |
| 445 | XGB_DLL SEXP XGDMatrixCreateFromCSC_R(SEXP indptr, SEXP indices, SEXP data, SEXP num_row, |
| 446 | SEXP missing, SEXP n_threads) { |
| 447 | SEXP ret = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 448 | R_API_BEGIN(); |
| 449 | std::int32_t threads = Rf_asInteger(n_threads); |
| 450 | DMatrixHandle handle; |
| 451 | |
| 452 | int res_code; |
| 453 | { |
| 454 | using xgboost::Integer; |
| 455 | using xgboost::Json; |
| 456 | using xgboost::Object; |
| 457 | std::string sindptr, sindices, sdata; |
| 458 | CreateFromSparse(indptr, indices, data, &sindptr, &sindices, &sdata); |
| 459 | auto nrow = static_cast<std::size_t>(INTEGER(num_row)[0]); |
| 460 | |
| 461 | Json jconfig{Object{}}; |
| 462 | // Construct configuration |
| 463 | jconfig["nthread"] = Integer{threads}; |
| 464 | AddMissingToJson(&jconfig, missing, TYPEOF(data)); |
| 465 | std::string config; |
| 466 | Json::Dump(jconfig, &config); |
| 467 | res_code = XGDMatrixCreateFromCSC(sindptr.c_str(), sindices.c_str(), sdata.c_str(), nrow, |
| 468 | config.c_str(), &handle); |
| 469 | } |
| 470 | CHECK_CALL(res_code); |
| 471 | |
| 472 | R_SetExternalPtrAddr(ret, handle); |
| 473 | R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE); |
| 474 | R_API_END(); |
| 475 | Rf_unprotect(1); |
| 476 | return ret; |
| 477 | } |
| 478 | |
| 479 | XGB_DLL SEXP XGDMatrixCreateFromCSR_R(SEXP indptr, SEXP indices, SEXP data, SEXP num_col, |
| 480 | SEXP missing, SEXP n_threads) { |
| 481 | SEXP ret = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 482 | R_API_BEGIN(); |
| 483 | std::int32_t threads = Rf_asInteger(n_threads); |
| 484 | DMatrixHandle handle; |
| 485 | |
| 486 | int res_code; |
| 487 | { |
| 488 | using xgboost::Integer; |
| 489 | using xgboost::Json; |
| 490 | using xgboost::Object; |
| 491 | |
| 492 | std::string sindptr, sindices, sdata; |
| 493 | CreateFromSparse(indptr, indices, data, &sindptr, &sindices, &sdata); |
| 494 | auto ncol = static_cast<std::size_t>(INTEGER(num_col)[0]); |
| 495 | |
| 496 | Json jconfig{Object{}}; |
| 497 | // Construct configuration |
| 498 | jconfig["nthread"] = Integer{threads}; |
| 499 | AddMissingToJson(&jconfig, missing, TYPEOF(data)); |
| 500 | std::string config; |
| 501 | Json::Dump(jconfig, &config); |
| 502 | res_code = XGDMatrixCreateFromCSR(sindptr.c_str(), sindices.c_str(), sdata.c_str(), ncol, |
| 503 | config.c_str(), &handle); |
| 504 | } |
| 505 | CHECK_CALL(res_code); |
| 506 | R_SetExternalPtrAddr(ret, handle); |
| 507 | R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE); |
| 508 | R_API_END(); |
| 509 | Rf_unprotect(1); |
| 510 | return ret; |
| 511 | } |
| 512 | |
| 513 | XGB_DLL SEXP XGDMatrixSliceDMatrix_R(SEXP handle, SEXP idxset, SEXP allow_groups) { |
| 514 | SEXP ret = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 515 | R_API_BEGIN(); |
| 516 | R_xlen_t len = Rf_xlength(idxset); |
| 517 | const int *idxset_ = INTEGER(idxset); |
| 518 | DMatrixHandle res; |
| 519 | |
| 520 | int res_code; |
| 521 | { |
| 522 | std::vector<int> idxvec(len); |
| 523 | #ifndef _MSC_VER |
| 524 | #pragma omp simd |
| 525 | #endif |
| 526 | for (R_xlen_t i = 0; i < len; ++i) { |
| 527 | idxvec[i] = idxset_[i] - 1; |
| 528 | } |
| 529 | res_code = XGDMatrixSliceDMatrixEx(R_ExternalPtrAddr(handle), |
| 530 | BeginPtr(idxvec), len, |
| 531 | &res, |
| 532 | Rf_asLogical(allow_groups)); |
| 533 | } |
| 534 | CHECK_CALL(res_code); |
| 535 | R_SetExternalPtrAddr(ret, res); |
| 536 | R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE); |
| 537 | R_API_END(); |
| 538 | Rf_unprotect(1); |
| 539 | return ret; |
| 540 | } |
| 541 | |
| 542 | XGB_DLL SEXP XGDMatrixSaveBinary_R(SEXP handle, SEXP fname, SEXP silent) { |
| 543 | R_API_BEGIN(); |
| 544 | CHECK_CALL(XGDMatrixSaveBinary(R_ExternalPtrAddr(handle), |
| 545 | CHAR(Rf_asChar(fname)), |
| 546 | Rf_asInteger(silent))); |
| 547 | R_API_END(); |
| 548 | return R_NilValue; |
| 549 | } |
| 550 | |
| 551 | XGB_DLL SEXP XGDMatrixSetInfo_R(SEXP handle, SEXP field, SEXP array) { |
| 552 | R_API_BEGIN(); |
| 553 | SEXP field_ = Rf_protect(Rf_asChar(field)); |
| 554 | SEXP arr_dim = Rf_getAttrib(array, R_DimSymbol); |
| 555 | int res_code; |
| 556 | { |
| 557 | const std::string array_str = Rf_isNull(arr_dim)? |
| 558 | MakeArrayInterfaceFromRVector(array) : MakeArrayInterfaceFromRMat(array); |
| 559 | res_code = XGDMatrixSetInfoFromInterface( |
| 560 | R_ExternalPtrAddr(handle), CHAR(field_), array_str.c_str()); |
| 561 | } |
| 562 | CHECK_CALL(res_code); |
| 563 | Rf_unprotect(1); |
| 564 | R_API_END(); |
| 565 | return R_NilValue; |
| 566 | } |
| 567 | |
| 568 | XGB_DLL SEXP XGDMatrixSetStrFeatureInfo_R(SEXP handle, SEXP field, SEXP array) { |
| 569 | R_API_BEGIN(); |
| 570 | size_t len{0}; |
| 571 | if (!Rf_isNull(array)) { |
| 572 | len = Rf_xlength(array); |
| 573 | } |
| 574 | |
| 575 | SEXP str_info_holder = Rf_protect(Rf_allocVector(VECSXP, len)); |
| 576 | if (TYPEOF(array) == STRSXP) { |
| 577 | for (size_t i = 0; i < len; ++i) { |
| 578 | SET_VECTOR_ELT(str_info_holder, i, STRING_ELT(array, i)); |
| 579 | } |
| 580 | } else { |
| 581 | for (size_t i = 0; i < len; ++i) { |
| 582 | SET_VECTOR_ELT(str_info_holder, i, Rf_asChar(VECTOR_ELT(array, i))); |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | SEXP field_ = Rf_protect(Rf_asChar(field)); |
| 587 | const char *name = CHAR(field_); |
| 588 | int res_code; |
| 589 | { |
| 590 | std::vector<std::string> str_info; |
| 591 | str_info.reserve(len); |
| 592 | for (size_t i = 0; i < len; ++i) { |
| 593 | str_info.emplace_back(CHAR(VECTOR_ELT(str_info_holder, i))); |
| 594 | } |
| 595 | std::vector<char const*> vec(len); |
| 596 | std::transform(str_info.cbegin(), str_info.cend(), vec.begin(), |
| 597 | [](std::string const &str) { return str.c_str(); }); |
| 598 | res_code = XGDMatrixSetStrFeatureInfo(R_ExternalPtrAddr(handle), name, vec.data(), len); |
| 599 | } |
| 600 | CHECK_CALL(res_code); |
| 601 | Rf_unprotect(2); |
| 602 | R_API_END(); |
| 603 | return R_NilValue; |
| 604 | } |
| 605 | |
| 606 | XGB_DLL SEXP XGDMatrixGetStrFeatureInfo_R(SEXP handle, SEXP field) { |
| 607 | SEXP ret; |
| 608 | R_API_BEGIN(); |
| 609 | char const **out_features{nullptr}; |
| 610 | bst_ulong len{0}; |
| 611 | const char *name = CHAR(Rf_asChar(field)); |
| 612 | XGDMatrixGetStrFeatureInfo(R_ExternalPtrAddr(handle), name, &len, &out_features); |
| 613 | |
| 614 | if (len > 0) { |
| 615 | ret = Rf_protect(Rf_allocVector(STRSXP, len)); |
| 616 | for (size_t i = 0; i < len; ++i) { |
| 617 | SET_STRING_ELT(ret, i, Rf_mkChar(out_features[i])); |
| 618 | } |
| 619 | } else { |
| 620 | ret = Rf_protect(R_NilValue); |
| 621 | } |
| 622 | R_API_END(); |
| 623 | Rf_unprotect(1); |
| 624 | return ret; |
| 625 | } |
| 626 | |
| 627 | XGB_DLL SEXP XGDMatrixGetFloatInfo_R(SEXP handle, SEXP field) { |
| 628 | SEXP ret; |
| 629 | R_API_BEGIN(); |
| 630 | bst_ulong olen; |
| 631 | const float *res; |
| 632 | CHECK_CALL(XGDMatrixGetFloatInfo(R_ExternalPtrAddr(handle), CHAR(Rf_asChar(field)), &olen, &res)); |
| 633 | ret = Rf_protect(Rf_allocVector(REALSXP, olen)); |
| 634 | std::copy(res, res + olen, REAL(ret)); |
| 635 | R_API_END(); |
| 636 | Rf_unprotect(1); |
| 637 | return ret; |
| 638 | } |
| 639 | |
| 640 | XGB_DLL SEXP XGDMatrixGetUIntInfo_R(SEXP handle, SEXP field) { |
| 641 | SEXP ret; |
| 642 | R_API_BEGIN(); |
| 643 | bst_ulong olen; |
| 644 | const unsigned *res; |
| 645 | CHECK_CALL(XGDMatrixGetUIntInfo(R_ExternalPtrAddr(handle), CHAR(Rf_asChar(field)), &olen, &res)); |
| 646 | ret = Rf_protect(Rf_allocVector(INTSXP, olen)); |
| 647 | std::copy(res, res + olen, INTEGER(ret)); |
| 648 | R_API_END(); |
| 649 | Rf_unprotect(1); |
| 650 | return ret; |
| 651 | } |
| 652 | |
| 653 | XGB_DLL SEXP XGDMatrixNumRow_R(SEXP handle) { |
| 654 | bst_ulong nrow; |
| 655 | R_API_BEGIN(); |
| 656 | CHECK_CALL(XGDMatrixNumRow(R_ExternalPtrAddr(handle), &nrow)); |
| 657 | R_API_END(); |
| 658 | return Rf_ScalarInteger(static_cast<int>(nrow)); |
| 659 | } |
| 660 | |
| 661 | XGB_DLL SEXP XGDMatrixNumCol_R(SEXP handle) { |
| 662 | bst_ulong ncol; |
| 663 | R_API_BEGIN(); |
| 664 | CHECK_CALL(XGDMatrixNumCol(R_ExternalPtrAddr(handle), &ncol)); |
| 665 | R_API_END(); |
| 666 | return Rf_ScalarInteger(static_cast<int>(ncol)); |
| 667 | } |
| 668 | |
| 669 | XGB_DLL SEXP XGProxyDMatrixCreate_R() { |
| 670 | SEXP out = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 671 | R_API_BEGIN(); |
| 672 | DMatrixHandle proxy_dmat_handle; |
| 673 | CHECK_CALL(XGProxyDMatrixCreate(&proxy_dmat_handle)); |
| 674 | R_SetExternalPtrAddr(out, proxy_dmat_handle); |
| 675 | R_RegisterCFinalizerEx(out, _DMatrixFinalizer, TRUE); |
| 676 | R_API_END(); |
| 677 | Rf_unprotect(1); |
| 678 | return out; |
| 679 | } |
| 680 | |
| 681 | XGB_DLL SEXP XGProxyDMatrixSetDataDense_R(SEXP handle, SEXP R_mat) { |
| 682 | R_API_BEGIN(); |
| 683 | DMatrixHandle proxy_dmat = R_ExternalPtrAddr(handle); |
| 684 | int res_code; |
| 685 | { |
| 686 | std::string array_str = MakeArrayInterfaceFromRMat(R_mat); |
| 687 | res_code = XGProxyDMatrixSetDataDense(proxy_dmat, array_str.c_str()); |
| 688 | } |
| 689 | CHECK_CALL(res_code); |
| 690 | R_API_END(); |
| 691 | return R_NilValue; |
| 692 | } |
| 693 | |
| 694 | XGB_DLL SEXP XGProxyDMatrixSetDataCSR_R(SEXP handle, SEXP lst) { |
| 695 | R_API_BEGIN(); |
| 696 | DMatrixHandle proxy_dmat = R_ExternalPtrAddr(handle); |
| 697 | int res_code; |
| 698 | { |
| 699 | std::string array_str_indptr = MakeArrayInterfaceFromRVector(VECTOR_ELT(lst, 0)); |
| 700 | std::string array_str_indices = MakeArrayInterfaceFromRVector(VECTOR_ELT(lst, 1)); |
| 701 | std::string array_str_data = MakeArrayInterfaceFromRVector(VECTOR_ELT(lst, 2)); |
| 702 | const int ncol = Rf_asInteger(VECTOR_ELT(lst, 3)); |
| 703 | res_code = XGProxyDMatrixSetDataCSR(proxy_dmat, |
| 704 | array_str_indptr.c_str(), |
| 705 | array_str_indices.c_str(), |
| 706 | array_str_data.c_str(), |
| 707 | ncol); |
| 708 | } |
| 709 | CHECK_CALL(res_code); |
| 710 | R_API_END(); |
| 711 | return R_NilValue; |
| 712 | } |
| 713 | |
| 714 | XGB_DLL SEXP XGProxyDMatrixSetDataColumnar_R(SEXP handle, SEXP lst) { |
| 715 | R_API_BEGIN(); |
| 716 | DMatrixHandle proxy_dmat = R_ExternalPtrAddr(handle); |
| 717 | int res_code; |
| 718 | { |
| 719 | std::string sinterface = MakeArrayInterfaceFromRDataFrame(lst); |
| 720 | res_code = XGProxyDMatrixSetDataColumnar(proxy_dmat, sinterface.c_str()); |
| 721 | } |
| 722 | CHECK_CALL(res_code); |
| 723 | R_API_END(); |
| 724 | return R_NilValue; |
| 725 | } |
| 726 | |
| 727 | namespace { |
| 728 | |
| 729 | struct _RDataIterator { |
| 730 | SEXP f_next; |
| 731 | SEXP f_reset; |
| 732 | SEXP calling_env; |
| 733 | SEXP continuation_token; |
| 734 | |
| 735 | _RDataIterator( |
| 736 | SEXP f_next, SEXP f_reset, SEXP calling_env, SEXP continuation_token) : |
| 737 | f_next(f_next), f_reset(f_reset), calling_env(calling_env), |
| 738 | continuation_token(continuation_token) {} |
| 739 | |
| 740 | void reset() { |
| 741 | SafeExecFun(this->f_reset, this->calling_env, this->continuation_token); |
| 742 | } |
| 743 | |
| 744 | int next() { |
| 745 | SEXP R_res = Rf_protect( |
| 746 | SafeExecFun(this->f_next, this->calling_env, this->continuation_token)); |
| 747 | int res = Rf_asInteger(R_res); |
| 748 | Rf_unprotect(1); |
| 749 | return res; |
| 750 | } |
| 751 | }; |
| 752 | |
| 753 | void _reset_RDataIterator(DataIterHandle iter) { |
| 754 | static_cast<_RDataIterator*>(iter)->reset(); |
| 755 | } |
| 756 | |
| 757 | int _next_RDataIterator(DataIterHandle iter) { |
| 758 | return static_cast<_RDataIterator*>(iter)->next(); |
| 759 | } |
| 760 | |
| 761 | SEXP XGDMatrixCreateFromCallbackGeneric_R( |
| 762 | SEXP f_next, SEXP f_reset, SEXP calling_env, SEXP proxy_dmat, |
| 763 | SEXP n_threads, SEXP missing, SEXP max_bin, SEXP ref_dmat, |
| 764 | SEXP cache_prefix, bool as_quantile_dmatrix) { |
| 765 | SEXP continuation_token = Rf_protect(R_MakeUnwindCont()); |
| 766 | SEXP out = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 767 | R_API_BEGIN(); |
| 768 | DMatrixHandle out_dmat; |
| 769 | |
| 770 | int res_code; |
| 771 | try { |
| 772 | _RDataIterator data_iterator(f_next, f_reset, calling_env, continuation_token); |
| 773 | |
| 774 | std::string str_cache_prefix; |
| 775 | xgboost::Json jconfig{xgboost::Object{}}; |
| 776 | jconfig["missing"] = Rf_asReal(missing); |
| 777 | if (!Rf_isNull(n_threads)) { |
| 778 | jconfig["nthread"] = Rf_asInteger(n_threads); |
| 779 | } |
| 780 | if (as_quantile_dmatrix) { |
| 781 | if (!Rf_isNull(max_bin)) { |
| 782 | jconfig["max_bin"] = Rf_asInteger(max_bin); |
| 783 | } |
| 784 | } else { |
| 785 | str_cache_prefix = std::string(CHAR(Rf_asChar(cache_prefix))); |
| 786 | jconfig["cache_prefix"] = str_cache_prefix; |
| 787 | } |
| 788 | std::string json_str = xgboost::Json::Dump(jconfig); |
| 789 | |
| 790 | DMatrixHandle ref_dmat_handle = nullptr; |
| 791 | if (as_quantile_dmatrix && !Rf_isNull(ref_dmat)) { |
| 792 | ref_dmat_handle = R_ExternalPtrAddr(ref_dmat); |
| 793 | } |
| 794 | |
| 795 | if (as_quantile_dmatrix) { |
| 796 | res_code = XGQuantileDMatrixCreateFromCallback( |
| 797 | &data_iterator, |
| 798 | R_ExternalPtrAddr(proxy_dmat), |
| 799 | ref_dmat_handle, |
| 800 | _reset_RDataIterator, |
| 801 | _next_RDataIterator, |
| 802 | json_str.c_str(), |
| 803 | &out_dmat); |
| 804 | } else { |
| 805 | res_code = XGDMatrixCreateFromCallback( |
| 806 | &data_iterator, |
| 807 | R_ExternalPtrAddr(proxy_dmat), |
| 808 | _reset_RDataIterator, |
| 809 | _next_RDataIterator, |
| 810 | json_str.c_str(), |
| 811 | &out_dmat); |
| 812 | } |
| 813 | } catch (ErrorWithUnwind &e) { |
| 814 | R_ContinueUnwind(continuation_token); |
| 815 | } |
| 816 | CHECK_CALL(res_code); |
| 817 | |
| 818 | R_SetExternalPtrAddr(out, out_dmat); |
| 819 | R_RegisterCFinalizerEx(out, _DMatrixFinalizer, TRUE); |
| 820 | R_API_END(); |
| 821 | Rf_unprotect(2); |
| 822 | return out; |
| 823 | } |
| 824 | |
| 825 | } /* namespace */ |
| 826 | |
| 827 | XGB_DLL SEXP XGQuantileDMatrixCreateFromCallback_R( |
| 828 | SEXP f_next, SEXP f_reset, SEXP calling_env, SEXP proxy_dmat, |
| 829 | SEXP n_threads, SEXP missing, SEXP max_bin, SEXP ref_dmat) { |
| 830 | return XGDMatrixCreateFromCallbackGeneric_R( |
| 831 | f_next, f_reset, calling_env, proxy_dmat, |
| 832 | n_threads, missing, max_bin, ref_dmat, |
| 833 | R_NilValue, true); |
| 834 | } |
| 835 | |
| 836 | XGB_DLL SEXP XGDMatrixCreateFromCallback_R( |
| 837 | SEXP f_next, SEXP f_reset, SEXP calling_env, SEXP proxy_dmat, |
| 838 | SEXP n_threads, SEXP missing, SEXP cache_prefix) { |
| 839 | return XGDMatrixCreateFromCallbackGeneric_R( |
| 840 | f_next, f_reset, calling_env, proxy_dmat, |
| 841 | n_threads, missing, R_NilValue, R_NilValue, |
| 842 | cache_prefix, false); |
| 843 | } |
| 844 | |
| 845 | XGB_DLL SEXP XGDMatrixFree_R(SEXP proxy_dmat) { |
| 846 | _DMatrixFinalizer(proxy_dmat); |
| 847 | return R_NilValue; |
| 848 | } |
| 849 | |
| 850 | XGB_DLL SEXP XGGetRNAIntAsDouble() { |
| 851 | double sentinel_as_double = static_cast<double>(R_NaInt); |
| 852 | return Rf_ScalarReal(sentinel_as_double); |
| 853 | } |
| 854 | |
| 855 | XGB_DLL SEXP XGDuplicate_R(SEXP obj) { |
| 856 | return Rf_duplicate(obj); |
| 857 | } |
| 858 | |
| 859 | XGB_DLL SEXP XGPointerEqComparison_R(SEXP obj1, SEXP obj2) { |
| 860 | return Rf_ScalarLogical(R_ExternalPtrAddr(obj1) == R_ExternalPtrAddr(obj2)); |
| 861 | } |
| 862 | |
| 863 | XGB_DLL SEXP XGDMatrixGetQuantileCut_R(SEXP handle) { |
| 864 | const char *out_names[] = {"indptr", "data", ""}; |
| 865 | SEXP continuation_token = Rf_protect(R_MakeUnwindCont()); |
| 866 | SEXP out = Rf_protect(Rf_mkNamed(VECSXP, out_names)); |
| 867 | R_API_BEGIN(); |
| 868 | const char *out_indptr; |
| 869 | const char *out_data; |
| 870 | CHECK_CALL(XGDMatrixGetQuantileCut(R_ExternalPtrAddr(handle), "{}", &out_indptr, &out_data)); |
| 871 | try { |
| 872 | SET_VECTOR_ELT(out, 0, CopyArrayToR(out_indptr, continuation_token)); |
| 873 | SET_VECTOR_ELT(out, 1, CopyArrayToR(out_data, continuation_token)); |
| 874 | } catch (ErrorWithUnwind &e) { |
| 875 | R_ContinueUnwind(continuation_token); |
| 876 | } |
| 877 | R_API_END(); |
| 878 | Rf_unprotect(2); |
| 879 | return out; |
| 880 | } |
| 881 | |
| 882 | XGB_DLL SEXP XGDMatrixNumNonMissing_R(SEXP handle) { |
| 883 | SEXP out = Rf_protect(Rf_allocVector(REALSXP, 1)); |
| 884 | R_API_BEGIN(); |
| 885 | bst_ulong out_; |
| 886 | CHECK_CALL(XGDMatrixNumNonMissing(R_ExternalPtrAddr(handle), &out_)); |
| 887 | REAL(out)[0] = static_cast<double>(out_); |
| 888 | R_API_END(); |
| 889 | Rf_unprotect(1); |
| 890 | return out; |
| 891 | } |
| 892 | |
| 893 | XGB_DLL SEXP XGDMatrixGetDataAsCSR_R(SEXP handle) { |
| 894 | const char *out_names[] = {"indptr", "indices", "data", "ncols", ""}; |
| 895 | SEXP out = Rf_protect(Rf_mkNamed(VECSXP, out_names)); |
| 896 | R_API_BEGIN(); |
| 897 | |
| 898 | bst_ulong nrows, ncols, nnz; |
| 899 | CHECK_CALL(XGDMatrixNumRow(R_ExternalPtrAddr(handle), &nrows)); |
| 900 | CHECK_CALL(XGDMatrixNumCol(R_ExternalPtrAddr(handle), &ncols)); |
| 901 | CHECK_CALL(XGDMatrixNumNonMissing(R_ExternalPtrAddr(handle), &nnz)); |
| 902 | if (std::max(nrows, ncols) > std::numeric_limits<int>::max()) { |
| 903 | Rf_error("%s", "Error: resulting DMatrix data does not fit into R 'dgRMatrix'."); |
| 904 | } |
| 905 | |
| 906 | SET_VECTOR_ELT(out, 0, Rf_allocVector(INTSXP, nrows + 1)); |
| 907 | SET_VECTOR_ELT(out, 1, Rf_allocVector(INTSXP, nnz)); |
| 908 | SET_VECTOR_ELT(out, 2, Rf_allocVector(REALSXP, nnz)); |
| 909 | SET_VECTOR_ELT(out, 3, Rf_ScalarInteger(ncols)); |
| 910 | |
| 911 | std::unique_ptr<bst_ulong[]> indptr(new bst_ulong[nrows + 1]); |
| 912 | std::unique_ptr<unsigned[]> indices(new unsigned[nnz]); |
| 913 | std::unique_ptr<float[]> data(new float[nnz]); |
| 914 | |
| 915 | CHECK_CALL(XGDMatrixGetDataAsCSR(R_ExternalPtrAddr(handle), |
| 916 | "{}", |
| 917 | indptr.get(), |
| 918 | indices.get(), |
| 919 | data.get())); |
| 920 | |
| 921 | std::copy(indptr.get(), indptr.get() + nrows + 1, INTEGER(VECTOR_ELT(out, 0))); |
| 922 | std::copy(indices.get(), indices.get() + nnz, INTEGER(VECTOR_ELT(out, 1))); |
| 923 | std::copy(data.get(), data.get() + nnz, REAL(VECTOR_ELT(out, 2))); |
| 924 | |
| 925 | R_API_END(); |
| 926 | Rf_unprotect(1); |
| 927 | return out; |
| 928 | } |
| 929 | |
| 930 | // functions related to booster |
| 931 | namespace { |
| 932 | void _BoosterFinalizer(SEXP R_ptr) { |
| 933 | if (R_ExternalPtrAddr(R_ptr) == NULL) return; |
| 934 | CHECK_CALL(XGBoosterFree(R_ExternalPtrAddr(R_ptr))); |
| 935 | R_ClearExternalPtr(R_ptr); |
| 936 | } |
| 937 | |
| 938 | /* Booster is represented as an altrep list with one element which |
| 939 | corresponds to an 'externalptr' holding the C object, forbidding |
| 940 | modification by not implementing setters, and adding custom serialization. */ |
| 941 | R_altrep_class_t XGBAltrepPointerClass; |
| 942 | |
| 943 | R_xlen_t XGBAltrepPointerLength_R(SEXP R_altrepped_obj) { |
| 944 | return 1; |
| 945 | } |
| 946 | |
| 947 | SEXP XGBAltrepPointerGetElt_R(SEXP R_altrepped_obj, R_xlen_t idx) { |
| 948 | return R_altrep_data1(R_altrepped_obj); |
| 949 | } |
| 950 | |
| 951 | SEXP XGBMakeEmptyAltrep() { |
| 952 | SEXP class_name = Rf_protect(Rf_mkString("xgb.Booster")); |
| 953 | SEXP elt_names = Rf_protect(Rf_mkString("ptr")); |
| 954 | SEXP R_ptr = Rf_protect(R_MakeExternalPtr(nullptr, R_NilValue, R_NilValue)); |
| 955 | SEXP R_altrepped_obj = Rf_protect(R_new_altrep(XGBAltrepPointerClass, R_ptr, R_NilValue)); |
| 956 | Rf_setAttrib(R_altrepped_obj, R_NamesSymbol, elt_names); |
| 957 | Rf_setAttrib(R_altrepped_obj, R_ClassSymbol, class_name); |
| 958 | Rf_unprotect(4); |
| 959 | return R_altrepped_obj; |
| 960 | } |
| 961 | |
| 962 | /* Note: the idea for separating this function from the one above is to be |
| 963 | able to trigger all R allocations first before doing non-R allocations. */ |
| 964 | void XGBAltrepSetPointer(SEXP R_altrepped_obj, BoosterHandle handle) { |
| 965 | SEXP R_ptr = R_altrep_data1(R_altrepped_obj); |
| 966 | R_SetExternalPtrAddr(R_ptr, handle); |
| 967 | R_RegisterCFinalizerEx(R_ptr, _BoosterFinalizer, TRUE); |
| 968 | } |
| 969 | |
| 970 | SEXP XGBAltrepSerializer_R(SEXP R_altrepped_obj) { |
| 971 | R_API_BEGIN(); |
| 972 | BoosterHandle handle = R_ExternalPtrAddr(R_altrep_data1(R_altrepped_obj)); |
| 973 | char const *serialized_bytes; |
| 974 | bst_ulong serialized_length; |
| 975 | CHECK_CALL(XGBoosterSerializeToBuffer( |
| 976 | handle, &serialized_length, &serialized_bytes)); |
| 977 | SEXP R_state = Rf_protect(Rf_allocVector(RAWSXP, serialized_length)); |
| 978 | if (serialized_length != 0) { |
| 979 | std::memcpy(RAW(R_state), serialized_bytes, serialized_length); |
| 980 | } |
| 981 | Rf_unprotect(1); |
| 982 | return R_state; |
| 983 | R_API_END(); |
| 984 | return R_NilValue; /* <- should not be reached */ |
| 985 | } |
| 986 | |
| 987 | SEXP XGBAltrepDeserializer_R(SEXP /*unused*/, SEXP R_state) { |
| 988 | SEXP R_altrepped_obj = Rf_protect(XGBMakeEmptyAltrep()); |
| 989 | R_API_BEGIN(); |
| 990 | BoosterHandle handle = nullptr; |
| 991 | CHECK_CALL(XGBoosterCreate(nullptr, 0, &handle)); |
| 992 | int res_code = XGBoosterUnserializeFromBuffer(handle, |
| 993 | RAW(R_state), |
| 994 | Rf_xlength(R_state)); |
| 995 | if (res_code != 0) { |
| 996 | XGBoosterFree(handle); |
| 997 | } |
| 998 | CHECK_CALL(res_code); |
| 999 | XGBAltrepSetPointer(R_altrepped_obj, handle); |
| 1000 | R_API_END(); |
| 1001 | Rf_unprotect(1); |
| 1002 | return R_altrepped_obj; |
| 1003 | } |
| 1004 | |
| 1005 | // https://purrple.cat/blog/2018/10/14/altrep-and-cpp/ |
| 1006 | Rboolean XGBAltrepInspector_R( |
| 1007 | SEXP x, int pre, int deep, int pvec, |
| 1008 | void (*inspect_subtree)(SEXP, int, int, int)) { |
| 1009 | Rprintf("Altrepped external pointer [address:%p]\n", |
| 1010 | R_ExternalPtrAddr(R_altrep_data1(x))); |
| 1011 | return TRUE; |
| 1012 | } |
| 1013 | |
| 1014 | SEXP XGBAltrepDuplicate_R(SEXP R_altrepped_obj, Rboolean deep) { |
| 1015 | R_API_BEGIN(); |
| 1016 | if (!deep) { |
| 1017 | SEXP out = Rf_protect(XGBMakeEmptyAltrep()); |
| 1018 | R_set_altrep_data1(out, R_altrep_data1(R_altrepped_obj)); |
| 1019 | Rf_unprotect(1); |
| 1020 | return out; |
| 1021 | } else { |
| 1022 | SEXP out = Rf_protect(XGBMakeEmptyAltrep()); |
| 1023 | char const *serialized_bytes; |
| 1024 | bst_ulong serialized_length; |
| 1025 | CHECK_CALL(XGBoosterSerializeToBuffer( |
| 1026 | R_ExternalPtrAddr(R_altrep_data1(R_altrepped_obj)), |
| 1027 | &serialized_length, &serialized_bytes)); |
| 1028 | BoosterHandle new_handle = nullptr; |
| 1029 | CHECK_CALL(XGBoosterCreate(nullptr, 0, &new_handle)); |
| 1030 | int res_code = XGBoosterUnserializeFromBuffer(new_handle, |
| 1031 | serialized_bytes, |
| 1032 | serialized_length); |
| 1033 | if (res_code != 0) { |
| 1034 | XGBoosterFree(new_handle); |
| 1035 | } |
| 1036 | CHECK_CALL(res_code); |
| 1037 | XGBAltrepSetPointer(out, new_handle); |
| 1038 | Rf_unprotect(1); |
| 1039 | return out; |
| 1040 | } |
| 1041 | R_API_END(); |
| 1042 | return R_NilValue; /* <- should not be reached */ |
| 1043 | } |
| 1044 | |
| 1045 | } /* namespace */ |
| 1046 | |
| 1047 | XGB_DLL void XGBInitializeAltrepClass_R(DllInfo *dll) { |
| 1048 | XGBAltrepPointerClass = R_make_altlist_class("XGBAltrepPointerClass", "xgboost", dll); |
| 1049 | R_set_altrep_Length_method(XGBAltrepPointerClass, XGBAltrepPointerLength_R); |
| 1050 | R_set_altlist_Elt_method(XGBAltrepPointerClass, XGBAltrepPointerGetElt_R); |
| 1051 | R_set_altrep_Inspect_method(XGBAltrepPointerClass, XGBAltrepInspector_R); |
| 1052 | R_set_altrep_Serialized_state_method(XGBAltrepPointerClass, XGBAltrepSerializer_R); |
| 1053 | R_set_altrep_Unserialize_method(XGBAltrepPointerClass, XGBAltrepDeserializer_R); |
| 1054 | R_set_altrep_Duplicate_method(XGBAltrepPointerClass, XGBAltrepDuplicate_R); |
| 1055 | } |
| 1056 | |
| 1057 | XGB_DLL SEXP XGBoosterCreate_R(SEXP dmats) { |
| 1058 | SEXP out = Rf_protect(XGBMakeEmptyAltrep()); |
| 1059 | R_API_BEGIN(); |
| 1060 | R_xlen_t len = Rf_xlength(dmats); |
| 1061 | BoosterHandle handle; |
| 1062 | |
| 1063 | int res_code; |
| 1064 | { |
| 1065 | std::vector<void*> dvec(len); |
| 1066 | for (R_xlen_t i = 0; i < len; ++i) { |
| 1067 | dvec[i] = R_ExternalPtrAddr(VECTOR_ELT(dmats, i)); |
| 1068 | } |
| 1069 | res_code = XGBoosterCreate(BeginPtr(dvec), dvec.size(), &handle); |
| 1070 | } |
| 1071 | CHECK_CALL(res_code); |
| 1072 | XGBAltrepSetPointer(out, handle); |
| 1073 | R_API_END(); |
| 1074 | Rf_unprotect(1); |
| 1075 | return out; |
| 1076 | } |
| 1077 | |
| 1078 | XGB_DLL SEXP XGBoosterReset_R(SEXP handle) { |
| 1079 | R_API_BEGIN(); |
| 1080 | CHECK_CALL(XGBoosterReset(R_ExternalPtrAddr(handle))); |
| 1081 | R_API_END(); |
| 1082 | return R_NilValue; |
| 1083 | } |
| 1084 | |
| 1085 | XGB_DLL SEXP XGBoosterCopyInfoFromDMatrix_R(SEXP booster, SEXP dmat) { |
| 1086 | R_API_BEGIN(); |
| 1087 | char const **feature_names; |
| 1088 | bst_ulong len_feature_names = 0; |
| 1089 | CHECK_CALL(XGDMatrixGetStrFeatureInfo(R_ExternalPtrAddr(dmat), |
| 1090 | "feature_name", |
| 1091 | &len_feature_names, |
| 1092 | &feature_names)); |
| 1093 | if (len_feature_names) { |
| 1094 | CHECK_CALL(XGBoosterSetStrFeatureInfo(R_ExternalPtrAddr(booster), |
| 1095 | "feature_name", |
| 1096 | feature_names, |
| 1097 | len_feature_names)); |
| 1098 | } |
| 1099 | |
| 1100 | char const **feature_types; |
| 1101 | bst_ulong len_feature_types = 0; |
| 1102 | CHECK_CALL(XGDMatrixGetStrFeatureInfo(R_ExternalPtrAddr(dmat), |
| 1103 | "feature_type", |
| 1104 | &len_feature_types, |
| 1105 | &feature_types)); |
| 1106 | if (len_feature_types) { |
| 1107 | CHECK_CALL(XGBoosterSetStrFeatureInfo(R_ExternalPtrAddr(booster), |
| 1108 | "feature_type", |
| 1109 | feature_types, |
| 1110 | len_feature_types)); |
| 1111 | } |
| 1112 | R_API_END(); |
| 1113 | return R_NilValue; |
| 1114 | } |
| 1115 | |
| 1116 | XGB_DLL SEXP XGBoosterSetStrFeatureInfo_R(SEXP handle, SEXP field, SEXP features) { |
| 1117 | R_API_BEGIN(); |
| 1118 | SEXP field_char = Rf_protect(Rf_asChar(field)); |
| 1119 | bst_ulong len_features = Rf_xlength(features); |
| 1120 | |
| 1121 | int res_code; |
| 1122 | { |
| 1123 | std::vector<const char*> str_arr(len_features); |
| 1124 | for (bst_ulong idx = 0; idx < len_features; idx++) { |
| 1125 | str_arr[idx] = CHAR(STRING_ELT(features, idx)); |
| 1126 | } |
| 1127 | res_code = XGBoosterSetStrFeatureInfo(R_ExternalPtrAddr(handle), |
| 1128 | CHAR(field_char), |
| 1129 | str_arr.data(), |
| 1130 | len_features); |
| 1131 | } |
| 1132 | CHECK_CALL(res_code); |
| 1133 | Rf_unprotect(1); |
| 1134 | R_API_END(); |
| 1135 | return R_NilValue; |
| 1136 | } |
| 1137 | |
| 1138 | XGB_DLL SEXP XGBoosterGetStrFeatureInfo_R(SEXP handle, SEXP field) { |
| 1139 | R_API_BEGIN(); |
| 1140 | bst_ulong len; |
| 1141 | const char **out_features; |
| 1142 | SEXP field_char = Rf_protect(Rf_asChar(field)); |
| 1143 | CHECK_CALL(XGBoosterGetStrFeatureInfo(R_ExternalPtrAddr(handle), |
| 1144 | CHAR(field_char), &len, &out_features)); |
| 1145 | SEXP out = Rf_protect(Rf_allocVector(STRSXP, len)); |
| 1146 | for (bst_ulong idx = 0; idx < len; idx++) { |
| 1147 | SET_STRING_ELT(out, idx, Rf_mkChar(out_features[idx])); |
| 1148 | } |
| 1149 | Rf_unprotect(2); |
| 1150 | return out; |
| 1151 | R_API_END(); |
| 1152 | return R_NilValue; /* <- should not be reached */ |
| 1153 | } |
| 1154 | |
| 1155 | XGB_DLL SEXP XGBoosterBoostedRounds_R(SEXP handle) { |
| 1156 | SEXP out = Rf_protect(Rf_allocVector(INTSXP, 1)); |
| 1157 | R_API_BEGIN(); |
| 1158 | CHECK_CALL(XGBoosterBoostedRounds(R_ExternalPtrAddr(handle), INTEGER(out))); |
| 1159 | R_API_END(); |
| 1160 | Rf_unprotect(1); |
| 1161 | return out; |
| 1162 | } |
| 1163 | |
| 1164 | /* Note: R's integer class is 32-bit-and-signed only, while xgboost |
| 1165 | supports more, so it returns it as a floating point instead */ |
| 1166 | XGB_DLL SEXP XGBoosterGetNumFeature_R(SEXP handle) { |
| 1167 | SEXP out = Rf_protect(Rf_allocVector(REALSXP, 1)); |
| 1168 | R_API_BEGIN(); |
| 1169 | bst_ulong res; |
| 1170 | CHECK_CALL(XGBoosterGetNumFeature(R_ExternalPtrAddr(handle), &res)); |
| 1171 | REAL(out)[0] = static_cast<double>(res); |
| 1172 | R_API_END(); |
| 1173 | Rf_unprotect(1); |
| 1174 | return out; |
| 1175 | } |
| 1176 | |
| 1177 | XGB_DLL SEXP XGBoosterSetParam_R(SEXP handle, SEXP name, SEXP val) { |
| 1178 | R_API_BEGIN(); |
| 1179 | SEXP name_ = Rf_protect(Rf_asChar(name)); |
| 1180 | SEXP val_ = Rf_protect(Rf_asChar(val)); |
| 1181 | CHECK_CALL(XGBoosterSetParam(R_ExternalPtrAddr(handle), |
| 1182 | CHAR(name_), |
| 1183 | CHAR(val_))); |
| 1184 | Rf_unprotect(2); |
| 1185 | R_API_END(); |
| 1186 | return R_NilValue; |
| 1187 | } |
| 1188 | |
| 1189 | XGB_DLL SEXP XGBoosterUpdateOneIter_R(SEXP handle, SEXP iter, SEXP dtrain) { |
| 1190 | R_API_BEGIN(); |
| 1191 | CHECK_CALL(XGBoosterUpdateOneIter(R_ExternalPtrAddr(handle), |
| 1192 | Rf_asInteger(iter), |
| 1193 | R_ExternalPtrAddr(dtrain))); |
| 1194 | R_API_END(); |
| 1195 | return R_NilValue; |
| 1196 | } |
| 1197 | |
| 1198 | XGB_DLL SEXP XGBoosterTrainOneIter_R(SEXP handle, SEXP dtrain, SEXP iter, SEXP grad, SEXP hess) { |
| 1199 | R_API_BEGIN(); |
| 1200 | CHECK_EQ(Rf_xlength(grad), Rf_xlength(hess)) << "gradient and hess must have same length."; |
| 1201 | SEXP gdim = Rf_protect(Rf_getAttrib(grad, R_DimSymbol)); |
| 1202 | SEXP hdim = Rf_protect(Rf_getAttrib(hess, R_DimSymbol)); |
| 1203 | |
| 1204 | int res_code; |
| 1205 | { |
| 1206 | const std::string s_grad = Rf_isNull(gdim)? |
| 1207 | MakeArrayInterfaceFromRVector(grad) : MakeArrayInterfaceFromRMat(grad); |
| 1208 | const std::string s_hess = Rf_isNull(hdim)? |
| 1209 | MakeArrayInterfaceFromRVector(hess) : MakeArrayInterfaceFromRMat(hess); |
| 1210 | res_code = XGBoosterTrainOneIter(R_ExternalPtrAddr(handle), R_ExternalPtrAddr(dtrain), |
| 1211 | Rf_asInteger(iter), s_grad.c_str(), s_hess.c_str()); |
| 1212 | } |
| 1213 | CHECK_CALL(res_code); |
| 1214 | |
| 1215 | Rf_unprotect(2); |
| 1216 | R_API_END(); |
| 1217 | return R_NilValue; |
| 1218 | } |
| 1219 | |
| 1220 | XGB_DLL SEXP XGBoosterEvalOneIter_R(SEXP handle, SEXP iter, SEXP dmats, SEXP evnames) { |
| 1221 | const char *ret; |
| 1222 | R_API_BEGIN(); |
| 1223 | CHECK_EQ(Rf_xlength(dmats), Rf_xlength(evnames)) |
| 1224 | << "dmats and evnams must have same length"; |
| 1225 | R_xlen_t len = Rf_xlength(dmats); |
| 1226 | SEXP evnames_lst = Rf_protect(Rf_allocVector(VECSXP, len)); |
| 1227 | for (R_xlen_t i = 0; i < len; i++) { |
| 1228 | SET_VECTOR_ELT(evnames_lst, i, Rf_asChar(VECTOR_ELT(evnames, i))); |
| 1229 | } |
| 1230 | |
| 1231 | int res_code; |
| 1232 | { |
| 1233 | std::vector<void*> vec_dmats(len); |
| 1234 | std::vector<std::string> vec_names; |
| 1235 | vec_names.reserve(len); |
| 1236 | std::vector<const char*> vec_sptr(len); |
| 1237 | for (R_xlen_t i = 0; i < len; ++i) { |
| 1238 | vec_dmats[i] = R_ExternalPtrAddr(VECTOR_ELT(dmats, i)); |
| 1239 | vec_names.emplace_back(CHAR(VECTOR_ELT(evnames_lst, i))); |
| 1240 | } |
| 1241 | for (R_xlen_t i = 0; i < len; ++i) { |
| 1242 | vec_sptr[i] = vec_names[i].c_str(); |
| 1243 | } |
| 1244 | res_code = XGBoosterEvalOneIter(R_ExternalPtrAddr(handle), |
| 1245 | Rf_asInteger(iter), |
| 1246 | BeginPtr(vec_dmats), |
| 1247 | BeginPtr(vec_sptr), |
| 1248 | len, &ret); |
| 1249 | } |
| 1250 | CHECK_CALL(res_code); |
| 1251 | Rf_unprotect(1); |
| 1252 | R_API_END(); |
| 1253 | return Rf_mkString(ret); |
| 1254 | } |
| 1255 | |
| 1256 | namespace { |
| 1257 | |
| 1258 | struct ProxyDmatrixError : public std::exception {}; |
| 1259 | |
| 1260 | struct ProxyDmatrixWrapper { |
| 1261 | DMatrixHandle proxy_dmat_handle; |
| 1262 | |
| 1263 | ProxyDmatrixWrapper() { |
| 1264 | int res_code = XGProxyDMatrixCreate(&this->proxy_dmat_handle); |
| 1265 | if (res_code != 0) { |
| 1266 | throw ProxyDmatrixError(); |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | ~ProxyDmatrixWrapper() { |
| 1271 | if (this->proxy_dmat_handle) { |
| 1272 | XGDMatrixFree(this->proxy_dmat_handle); |
| 1273 | this->proxy_dmat_handle = nullptr; |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | DMatrixHandle get_handle() { |
| 1278 | return this->proxy_dmat_handle; |
| 1279 | } |
| 1280 | }; |
| 1281 | |
| 1282 | std::unique_ptr<ProxyDmatrixWrapper> GetProxyDMatrixWithBaseMargin(SEXP base_margin) { |
| 1283 | if (Rf_isNull(base_margin)) { |
| 1284 | return std::unique_ptr<ProxyDmatrixWrapper>(nullptr); |
| 1285 | } |
| 1286 | |
| 1287 | SEXP base_margin_dim = Rf_getAttrib(base_margin, R_DimSymbol); |
| 1288 | int res_code; |
| 1289 | try { |
| 1290 | const std::string array_str = Rf_isNull(base_margin_dim)? |
| 1291 | MakeArrayInterfaceFromRVector(base_margin) : MakeArrayInterfaceFromRMat(base_margin); |
| 1292 | std::unique_ptr<ProxyDmatrixWrapper> proxy_dmat(new ProxyDmatrixWrapper()); |
| 1293 | res_code = XGDMatrixSetInfoFromInterface(proxy_dmat->get_handle(), |
| 1294 | "base_margin", |
| 1295 | array_str.c_str()); |
| 1296 | if (res_code != 0) { |
| 1297 | throw ProxyDmatrixError(); |
| 1298 | } |
| 1299 | return proxy_dmat; |
| 1300 | } catch(ProxyDmatrixError &err) { |
| 1301 | Rf_error("%s", XGBGetLastError()); |
| 1302 | } |
| 1303 | } |
| 1304 | |
| 1305 | enum class PredictionInputType {DMatrix, DenseMatrix, CSRMatrix, DataFrame}; |
| 1306 | |
| 1307 | SEXP XGBoosterPredictGeneric(SEXP handle, SEXP input_data, SEXP json_config, |
| 1308 | PredictionInputType input_type, SEXP missing, |
| 1309 | SEXP base_margin) { |
| 1310 | SEXP r_out_result = R_NilValue; |
| 1311 | R_API_BEGIN(); |
| 1312 | SEXP json_config_ = Rf_protect(Rf_asChar(json_config)); |
| 1313 | char const *c_json_config = CHAR(json_config_); |
| 1314 | |
| 1315 | bst_ulong out_dim; |
| 1316 | bst_ulong const *out_shape; |
| 1317 | float const *out_result; |
| 1318 | |
| 1319 | int res_code; |
| 1320 | { |
| 1321 | switch (input_type) { |
| 1322 | case PredictionInputType::DMatrix: { |
| 1323 | res_code = XGBoosterPredictFromDMatrix(R_ExternalPtrAddr(handle), |
| 1324 | R_ExternalPtrAddr(input_data), c_json_config, |
| 1325 | &out_shape, &out_dim, &out_result); |
| 1326 | break; |
| 1327 | } |
| 1328 | |
| 1329 | case PredictionInputType::CSRMatrix: { |
| 1330 | std::unique_ptr<ProxyDmatrixWrapper> proxy_dmat = GetProxyDMatrixWithBaseMargin( |
| 1331 | base_margin); |
| 1332 | DMatrixHandle proxy_dmat_handle = proxy_dmat.get()? proxy_dmat->get_handle() : nullptr; |
| 1333 | |
| 1334 | SEXP indptr = VECTOR_ELT(input_data, 0); |
| 1335 | SEXP indices = VECTOR_ELT(input_data, 1); |
| 1336 | SEXP data = VECTOR_ELT(input_data, 2); |
| 1337 | const int ncol_csr = Rf_asInteger(VECTOR_ELT(input_data, 3)); |
| 1338 | const SEXPTYPE type_data = TYPEOF(data); |
| 1339 | CHECK_EQ(type_data, REALSXP); |
| 1340 | std::string sindptr, sindices, sdata; |
| 1341 | CreateFromSparse(indptr, indices, data, &sindptr, &sindices, &sdata); |
| 1342 | |
| 1343 | xgboost::StringView json_str(c_json_config); |
| 1344 | xgboost::Json new_json = xgboost::Json::Load(json_str); |
| 1345 | AddMissingToJson(&new_json, missing, type_data); |
| 1346 | const std::string new_c_json = xgboost::Json::Dump(new_json); |
| 1347 | |
| 1348 | res_code = XGBoosterPredictFromCSR( |
| 1349 | R_ExternalPtrAddr(handle), sindptr.c_str(), sindices.c_str(), sdata.c_str(), |
| 1350 | ncol_csr, new_c_json.c_str(), proxy_dmat_handle, &out_shape, &out_dim, &out_result); |
| 1351 | break; |
| 1352 | } |
| 1353 | |
| 1354 | case PredictionInputType::DenseMatrix: { |
| 1355 | std::unique_ptr<ProxyDmatrixWrapper> proxy_dmat = GetProxyDMatrixWithBaseMargin( |
| 1356 | base_margin); |
| 1357 | DMatrixHandle proxy_dmat_handle = proxy_dmat.get()? proxy_dmat->get_handle() : nullptr; |
| 1358 | const std::string array_str = MakeArrayInterfaceFromRMat(input_data); |
| 1359 | |
| 1360 | xgboost::StringView json_str(c_json_config); |
| 1361 | xgboost::Json new_json = xgboost::Json::Load(json_str); |
| 1362 | AddMissingToJson(&new_json, missing, TYPEOF(input_data)); |
| 1363 | const std::string new_c_json = xgboost::Json::Dump(new_json); |
| 1364 | |
| 1365 | res_code = XGBoosterPredictFromDense( |
| 1366 | R_ExternalPtrAddr(handle), array_str.c_str(), new_c_json.c_str(), |
| 1367 | proxy_dmat_handle, &out_shape, &out_dim, &out_result); |
| 1368 | break; |
| 1369 | } |
| 1370 | |
| 1371 | case PredictionInputType::DataFrame: { |
| 1372 | std::unique_ptr<ProxyDmatrixWrapper> proxy_dmat = GetProxyDMatrixWithBaseMargin( |
| 1373 | base_margin); |
| 1374 | DMatrixHandle proxy_dmat_handle = proxy_dmat.get()? proxy_dmat->get_handle() : nullptr; |
| 1375 | |
| 1376 | const std::string df_str = MakeArrayInterfaceFromRDataFrame(input_data); |
| 1377 | |
| 1378 | xgboost::StringView json_str(c_json_config); |
| 1379 | xgboost::Json new_json = xgboost::Json::Load(json_str); |
| 1380 | AddMissingToJson(&new_json, missing, REALSXP); |
| 1381 | const std::string new_c_json = xgboost::Json::Dump(new_json); |
| 1382 | |
| 1383 | res_code = XGBoosterPredictFromColumnar( |
| 1384 | R_ExternalPtrAddr(handle), df_str.c_str(), new_c_json.c_str(), |
| 1385 | proxy_dmat_handle, &out_shape, &out_dim, &out_result); |
| 1386 | break; |
| 1387 | } |
| 1388 | } |
| 1389 | } |
| 1390 | CHECK_CALL(res_code); |
| 1391 | |
| 1392 | SEXP r_out_shape = Rf_protect(Rf_allocVector(INTSXP, out_dim)); |
| 1393 | size_t len = 1; |
| 1394 | int *r_out_shape_ = INTEGER(r_out_shape); |
| 1395 | for (size_t i = 0; i < out_dim; ++i) { |
| 1396 | r_out_shape_[out_dim - i - 1] = out_shape[i]; |
| 1397 | len *= out_shape[i]; |
| 1398 | } |
| 1399 | r_out_result = Rf_protect(Rf_allocVector(REALSXP, len)); |
| 1400 | std::copy(out_result, out_result + len, REAL(r_out_result)); |
| 1401 | |
| 1402 | if (out_dim > 1) { |
| 1403 | Rf_setAttrib(r_out_result, R_DimSymbol, r_out_shape); |
| 1404 | } |
| 1405 | |
| 1406 | R_API_END(); |
| 1407 | Rf_unprotect(3); |
| 1408 | |
| 1409 | return r_out_result; |
| 1410 | } |
| 1411 | |
| 1412 | } // namespace |
| 1413 | |
| 1414 | XGB_DLL SEXP XGBoosterPredictFromDMatrix_R(SEXP handle, SEXP dmat, SEXP json_config) { |
| 1415 | return XGBoosterPredictGeneric(handle, dmat, json_config, |
| 1416 | PredictionInputType::DMatrix, R_NilValue, R_NilValue); |
| 1417 | } |
| 1418 | |
| 1419 | XGB_DLL SEXP XGBoosterPredictFromDense_R(SEXP handle, SEXP R_mat, SEXP missing, |
| 1420 | SEXP json_config, SEXP base_margin) { |
| 1421 | return XGBoosterPredictGeneric(handle, R_mat, json_config, |
| 1422 | PredictionInputType::DenseMatrix, missing, base_margin); |
| 1423 | } |
| 1424 | |
| 1425 | XGB_DLL SEXP XGBoosterPredictFromCSR_R(SEXP handle, SEXP lst, SEXP missing, |
| 1426 | SEXP json_config, SEXP base_margin) { |
| 1427 | return XGBoosterPredictGeneric(handle, lst, json_config, |
| 1428 | PredictionInputType::CSRMatrix, missing, base_margin); |
| 1429 | } |
| 1430 | |
| 1431 | XGB_DLL SEXP XGBoosterPredictFromColumnar_R(SEXP handle, SEXP R_df, SEXP missing, |
| 1432 | SEXP json_config, SEXP base_margin) { |
| 1433 | return XGBoosterPredictGeneric(handle, R_df, json_config, |
| 1434 | PredictionInputType::DataFrame, missing, base_margin); |
| 1435 | } |
| 1436 | |
| 1437 | XGB_DLL SEXP XGBoosterLoadModel_R(SEXP handle, SEXP fname) { |
| 1438 | R_API_BEGIN(); |
| 1439 | CHECK_CALL(XGBoosterLoadModel(R_ExternalPtrAddr(handle), CHAR(Rf_asChar(fname)))); |
| 1440 | R_API_END(); |
| 1441 | return R_NilValue; |
| 1442 | } |
| 1443 | |
| 1444 | XGB_DLL SEXP XGBoosterSaveModel_R(SEXP handle, SEXP fname) { |
| 1445 | R_API_BEGIN(); |
| 1446 | CHECK_CALL(XGBoosterSaveModel(R_ExternalPtrAddr(handle), CHAR(Rf_asChar(fname)))); |
| 1447 | R_API_END(); |
| 1448 | return R_NilValue; |
| 1449 | } |
| 1450 | |
| 1451 | XGB_DLL SEXP XGBoosterLoadModelFromRaw_R(SEXP handle, SEXP raw) { |
| 1452 | R_API_BEGIN(); |
| 1453 | CHECK_CALL(XGBoosterLoadModelFromBuffer(R_ExternalPtrAddr(handle), |
| 1454 | RAW(raw), |
| 1455 | Rf_xlength(raw))); |
| 1456 | R_API_END(); |
| 1457 | return R_NilValue; |
| 1458 | } |
| 1459 | |
| 1460 | XGB_DLL SEXP XGBoosterSaveModelToRaw_R(SEXP handle, SEXP json_config) { |
| 1461 | SEXP ret; |
| 1462 | R_API_BEGIN(); |
| 1463 | bst_ulong olen; |
| 1464 | char const *c_json_config = CHAR(Rf_asChar(json_config)); |
| 1465 | char const *raw; |
| 1466 | CHECK_CALL(XGBoosterSaveModelToBuffer(R_ExternalPtrAddr(handle), c_json_config, &olen, &raw)) |
| 1467 | ret = Rf_protect(Rf_allocVector(RAWSXP, olen)); |
| 1468 | if (olen != 0) { |
| 1469 | std::memcpy(RAW(ret), raw, olen); |
| 1470 | } |
| 1471 | R_API_END(); |
| 1472 | Rf_unprotect(1); |
| 1473 | return ret; |
| 1474 | } |
| 1475 | |
| 1476 | XGB_DLL SEXP XGBoosterSaveJsonConfig_R(SEXP handle) { |
| 1477 | const char* ret; |
| 1478 | R_API_BEGIN(); |
| 1479 | bst_ulong len {0}; |
| 1480 | CHECK_CALL(XGBoosterSaveJsonConfig(R_ExternalPtrAddr(handle), |
| 1481 | &len, |
| 1482 | &ret)); |
| 1483 | R_API_END(); |
| 1484 | return Rf_mkString(ret); |
| 1485 | } |
| 1486 | |
| 1487 | XGB_DLL SEXP XGBoosterLoadJsonConfig_R(SEXP handle, SEXP value) { |
| 1488 | R_API_BEGIN(); |
| 1489 | CHECK_CALL(XGBoosterLoadJsonConfig(R_ExternalPtrAddr(handle), CHAR(Rf_asChar(value)))); |
| 1490 | R_API_END(); |
| 1491 | return R_NilValue; |
| 1492 | } |
| 1493 | |
| 1494 | XGB_DLL SEXP XGBoosterSerializeToBuffer_R(SEXP handle) { |
| 1495 | SEXP ret; |
| 1496 | R_API_BEGIN(); |
| 1497 | bst_ulong out_len; |
| 1498 | const char *raw; |
| 1499 | CHECK_CALL(XGBoosterSerializeToBuffer(R_ExternalPtrAddr(handle), &out_len, &raw)); |
| 1500 | ret = Rf_protect(Rf_allocVector(RAWSXP, out_len)); |
| 1501 | if (out_len != 0) { |
| 1502 | memcpy(RAW(ret), raw, out_len); |
| 1503 | } |
| 1504 | R_API_END(); |
| 1505 | Rf_unprotect(1); |
| 1506 | return ret; |
| 1507 | } |
| 1508 | |
| 1509 | XGB_DLL SEXP XGBoosterUnserializeFromBuffer_R(SEXP handle, SEXP raw) { |
| 1510 | R_API_BEGIN(); |
| 1511 | CHECK_CALL(XGBoosterUnserializeFromBuffer(R_ExternalPtrAddr(handle), |
| 1512 | RAW(raw), |
| 1513 | Rf_xlength(raw))); |
| 1514 | R_API_END(); |
| 1515 | return R_NilValue; |
| 1516 | } |
| 1517 | |
| 1518 | XGB_DLL SEXP XGBoosterDumpModel_R(SEXP handle, SEXP fmap, SEXP with_stats, SEXP dump_format) { |
| 1519 | SEXP out; |
| 1520 | SEXP continuation_token = Rf_protect(R_MakeUnwindCont()); |
| 1521 | SEXP dump_format_ = Rf_protect(Rf_asChar(dump_format)); |
| 1522 | SEXP fmap_ = Rf_protect(Rf_asChar(fmap)); |
| 1523 | R_API_BEGIN(); |
| 1524 | bst_ulong olen; |
| 1525 | const char **res; |
| 1526 | const char *fmt = CHAR(dump_format_); |
| 1527 | CHECK_CALL(XGBoosterDumpModelEx(R_ExternalPtrAddr(handle), |
| 1528 | CHAR(fmap_), |
| 1529 | Rf_asInteger(with_stats), |
| 1530 | fmt, |
| 1531 | &olen, &res)); |
| 1532 | out = Rf_protect(Rf_allocVector(STRSXP, olen)); |
| 1533 | try { |
| 1534 | if (!strcmp("json", fmt)) { |
| 1535 | std::stringstream stream; |
| 1536 | stream << "[\n"; |
| 1537 | for (size_t i = 0; i < olen; ++i) { |
| 1538 | stream << res[i]; |
| 1539 | if (i < olen - 1) { |
| 1540 | stream << ",\n"; |
| 1541 | } else { |
| 1542 | stream << "\n"; |
| 1543 | } |
| 1544 | } |
| 1545 | stream << "]"; |
| 1546 | const std::string temp_str = stream.str(); |
| 1547 | SET_STRING_ELT(out, 0, SafeMkChar(temp_str.c_str(), continuation_token)); |
| 1548 | } else { |
| 1549 | for (size_t i = 0; i < olen; ++i) { |
| 1550 | std::stringstream stream; |
| 1551 | stream << "booster[" << i <<"]\n" << res[i]; |
| 1552 | const std::string temp_str = stream.str(); |
| 1553 | SET_STRING_ELT(out, i, SafeMkChar(temp_str.c_str(), continuation_token)); |
| 1554 | } |
| 1555 | } |
| 1556 | } catch (ErrorWithUnwind &e) { |
| 1557 | R_ContinueUnwind(continuation_token); |
| 1558 | } |
| 1559 | R_API_END(); |
| 1560 | Rf_unprotect(4); |
| 1561 | return out; |
| 1562 | } |
| 1563 | |
| 1564 | XGB_DLL SEXP XGBoosterGetAttr_R(SEXP handle, SEXP name) { |
| 1565 | SEXP out; |
| 1566 | R_API_BEGIN(); |
| 1567 | int success; |
| 1568 | const char *val; |
| 1569 | CHECK_CALL(XGBoosterGetAttr(R_ExternalPtrAddr(handle), |
| 1570 | CHAR(Rf_asChar(name)), |
| 1571 | &val, |
| 1572 | &success)); |
| 1573 | if (success) { |
| 1574 | out = Rf_protect(Rf_allocVector(STRSXP, 1)); |
| 1575 | SET_STRING_ELT(out, 0, Rf_mkChar(val)); |
| 1576 | } else { |
| 1577 | out = Rf_protect(R_NilValue); |
| 1578 | } |
| 1579 | R_API_END(); |
| 1580 | Rf_unprotect(1); |
| 1581 | return out; |
| 1582 | } |
| 1583 | |
| 1584 | XGB_DLL SEXP XGBoosterSetAttr_R(SEXP handle, SEXP name, SEXP val) { |
| 1585 | R_API_BEGIN(); |
| 1586 | const char *v = nullptr; |
| 1587 | SEXP name_ = Rf_protect(Rf_asChar(name)); |
| 1588 | SEXP val_; |
| 1589 | int n_protected = 1; |
| 1590 | if (!Rf_isNull(val)) { |
| 1591 | val_ = Rf_protect(Rf_asChar(val)); |
| 1592 | n_protected++; |
| 1593 | v = CHAR(val_); |
| 1594 | } |
| 1595 | |
| 1596 | CHECK_CALL(XGBoosterSetAttr(R_ExternalPtrAddr(handle), |
| 1597 | CHAR(name_), v)); |
| 1598 | Rf_unprotect(n_protected); |
| 1599 | R_API_END(); |
| 1600 | return R_NilValue; |
| 1601 | } |
| 1602 | |
| 1603 | XGB_DLL SEXP XGBoosterGetAttrNames_R(SEXP handle) { |
| 1604 | SEXP out; |
| 1605 | R_API_BEGIN(); |
| 1606 | bst_ulong len; |
| 1607 | const char **res; |
| 1608 | CHECK_CALL(XGBoosterGetAttrNames(R_ExternalPtrAddr(handle), |
| 1609 | &len, &res)); |
| 1610 | if (len > 0) { |
| 1611 | out = Rf_protect(Rf_allocVector(STRSXP, len)); |
| 1612 | for (size_t i = 0; i < len; ++i) { |
| 1613 | SET_STRING_ELT(out, i, Rf_mkChar(res[i])); |
| 1614 | } |
| 1615 | } else { |
| 1616 | out = Rf_protect(R_NilValue); |
| 1617 | } |
| 1618 | R_API_END(); |
| 1619 | Rf_unprotect(1); |
| 1620 | return out; |
| 1621 | } |
| 1622 | |
| 1623 | XGB_DLL SEXP XGBoosterFeatureScore_R(SEXP handle, SEXP json_config) { |
| 1624 | SEXP out_features_sexp; |
| 1625 | SEXP out_scores_sexp; |
| 1626 | SEXP out_shape_sexp; |
| 1627 | SEXP r_out = Rf_protect(Rf_allocVector(VECSXP, 3)); |
| 1628 | |
| 1629 | R_API_BEGIN(); |
| 1630 | char const *c_json_config = CHAR(Rf_asChar(json_config)); |
| 1631 | bst_ulong out_n_features; |
| 1632 | char const **out_features; |
| 1633 | |
| 1634 | bst_ulong out_dim; |
| 1635 | bst_ulong const *out_shape; |
| 1636 | float const *out_scores; |
| 1637 | |
| 1638 | CHECK_CALL(XGBoosterFeatureScore(R_ExternalPtrAddr(handle), c_json_config, |
| 1639 | &out_n_features, &out_features, |
| 1640 | &out_dim, &out_shape, &out_scores)); |
| 1641 | out_shape_sexp = Rf_protect(Rf_allocVector(INTSXP, out_dim)); |
| 1642 | size_t len = 1; |
| 1643 | int *out_shape_sexp_ = INTEGER(out_shape_sexp); |
| 1644 | for (size_t i = 0; i < out_dim; ++i) { |
| 1645 | out_shape_sexp_[i] = out_shape[i]; |
| 1646 | len *= out_shape[i]; |
| 1647 | } |
| 1648 | |
| 1649 | out_features_sexp = Rf_protect(Rf_allocVector(STRSXP, out_n_features)); |
| 1650 | for (size_t i = 0; i < out_n_features; ++i) { |
| 1651 | SET_STRING_ELT(out_features_sexp, i, Rf_mkChar(out_features[i])); |
| 1652 | } |
| 1653 | |
| 1654 | out_scores_sexp = Rf_protect(Rf_allocVector(REALSXP, len)); |
| 1655 | std::copy(out_scores, out_scores + len, REAL(out_scores_sexp)); |
| 1656 | |
| 1657 | SET_VECTOR_ELT(r_out, 0, out_features_sexp); |
| 1658 | SET_VECTOR_ELT(r_out, 1, out_shape_sexp); |
| 1659 | SET_VECTOR_ELT(r_out, 2, out_scores_sexp); |
| 1660 | |
| 1661 | R_API_END(); |
| 1662 | Rf_unprotect(4); |
| 1663 | |
| 1664 | return r_out; |
| 1665 | } |
| 1666 | |
| 1667 | XGB_DLL SEXP XGBoosterSlice_R(SEXP handle, SEXP begin_layer, SEXP end_layer, SEXP step) { |
| 1668 | SEXP out = Rf_protect(XGBMakeEmptyAltrep()); |
| 1669 | R_API_BEGIN(); |
| 1670 | BoosterHandle handle_out = nullptr; |
| 1671 | CHECK_CALL(XGBoosterSlice(R_ExternalPtrAddr(handle), |
| 1672 | Rf_asInteger(begin_layer), |
| 1673 | Rf_asInteger(end_layer), |
| 1674 | Rf_asInteger(step), |
| 1675 | &handle_out)); |
| 1676 | XGBAltrepSetPointer(out, handle_out); |
| 1677 | R_API_END(); |
| 1678 | Rf_unprotect(1); |
| 1679 | return out; |
| 1680 | } |
| 1681 | |
| 1682 | XGB_DLL SEXP XGBoosterSliceAndReplace_R(SEXP handle, SEXP begin_layer, SEXP end_layer, SEXP step) { |
| 1683 | R_API_BEGIN(); |
| 1684 | BoosterHandle old_handle = R_ExternalPtrAddr(handle); |
| 1685 | BoosterHandle new_handle = nullptr; |
| 1686 | CHECK_CALL(XGBoosterSlice(old_handle, |
| 1687 | Rf_asInteger(begin_layer), |
| 1688 | Rf_asInteger(end_layer), |
| 1689 | Rf_asInteger(step), |
| 1690 | &new_handle)); |
| 1691 | R_SetExternalPtrAddr(handle, new_handle); |
| 1692 | CHECK_CALL(XGBoosterFree(old_handle)); |
| 1693 | R_API_END(); |
| 1694 | return R_NilValue; |
| 1695 | } |