stop application if pushed thread had exception in Perl - r

I have aplication which runs in parallel mode. Jobs are runing using threads with implmented subroutine. Subroutine "worker3" have three argumens, one parameter and two path for files.
This subroutine execute R script using system commands.
if ($ENV{"model"} eq "alaef_cy40_5km"){
sub worker3 {
my $parameter2 = $_[0];
print $parameter2, "\n";
$ENV{"grb_path"} = $models{$model}{"grb"}{"path"}{$parameter2};
$ENV{"grb_file"} = $models{$model}{"grb"}{"file"}{$parameter2};
print"FROM sub:", "\n";
print $ENV{"grb_path"}, "\n";
print $ENV{"grb_file"}, "\n";
say "Job Started\n";
system("Rscript $root/read_ALAEF.R #_ ");
}
for my $param( 'T2m','RH2m'){
push #threads, my $thr1=threads ->create('worker3', $param ,$ENV{"grb_file"},$ENV{"grb_path"})
}
$_->join() for threads->list();
}
Problem is when R script finish with Execution halted, application final status is ok. What i need is when R script finished with error, the whole program needs to be stopped.
So, if one thread fails, application needs to stops, and display error.
This is output:
T2m
FROM sub:
/data/nwp/products/a-laef_stream
A-LAEF_mem_{MBR2}_{YYYY}{MM}{DD}{HH}_surface.grb
Job Started
RH2m
FROM sub:
/data/nwp/products/a-laef_stream
A-LAEF_mem_{MBR2}_{YYYY}{MM}{DD}{HH}_surface.grb
Job Started
-- Attaching packages --------------------------------------- tidyverse 1.3.1 --
v ggplot2 3.3.5 v purrr 0.3.4
v tibble 3.1.6 v dplyr 1.0.7
v tidyr 1.1.4 v stringr 1.4.0
v readr 2.1.0 v forcats 0.5.1
-- Attaching packages --------------------------------------- tidyverse 1.3.1 --
v ggplot2 3.3.5 v purrr 0.3.4
v tibble 3.1.6 v dplyr 1.0.7
v tidyr 1.1.4 v stringr 1.4.0
v readr 2.1.0 v forcats 0.5.1
-- Conflicts ------------------------------------------ tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::lag() masks stats::lag()
here() starts at /work/users/p6095/2022-02-19_00/harp.119
Loading required package: harpIO
Attaching package: 'harpIO'
The following object is masked from 'package:purrr':
accumulate
Loading required package: harpPoint
Loading required package: harpVis
Loading required package: shiny
-- Conflicts ------------------------------------------ tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::lag() masks stats::lag()
here() starts at /work/users/p6095/2022-02-19_00/harp.119
Loading required package: harpIO
Attaching package: 'harpIO'
The following object is masked from 'package:purrr':
accumulate
Loading required package: harpPoint
Loading required package: harpVis
Loading required package: shiny
Loading required package: harpSpatial
Error: unexpected string constant in:
"
'4'"
Execution halted
Loading required package: harpSpatial
Error: unexpected string constant in:
"
'4'"
Execution halted
----------------------------------------------------
Application finished OK at: 21-02-2022 15:46:11 UTC
----------------------------------------------------
As you see, it shows that application finished OK, no matter if is the error inside R code. I need this : if pushed thread had exception -> stop application perl

Here is an example of how you can stop the main program with a status message if one of the executables run by a given thread fails:
First, I constructed a dummy executable foo.pl like this:
use feature qw(say);
use strict;
use warnings;
my ($id, $force_fail) = #ARGV;
my $thread1_exit_value = $force_fail ? 2 : 0;
if ($id == 1) {
sleep 2;
exit $thread1_exit_value;
}
elsif ($id == 2) {
sleep 5;
exit 0;
}
Then the main program like this:
use v5.20; # experimental signatures requires perl >= 5.20
use feature qw(say);
use strict;
use warnings;
use experimental qw(signatures);
use threads;
{
my #threads;
my $force_fail = 1;
my $start_time = time;
for (1..2) {
my $thr = threads->create(
sub {
my $res = system "foo.pl", $_, $force_fail; $res
}
);
push #threads, $thr;
}
my $fail = 0;
for my $i (0..$#threads) {
my $thr = $threads[$i];
if ($fail) {
say "detaching thread $i..";
$thr->detach();
}
else {
say "joining thread $i..";
my $res = $thr->join();
if (command_failed($res, $i)) {
$fail = 1;
}
}
}
my $total_time = time - $start_time;
say "Program " . ($fail ? "failed" : "succeeded") . " after $total_time seconds";
}
sub command_failed( $res, $id ) {
if ($res == -1) {
say "thread $id failed to execute: $!";
return 1;
}
elsif ($res & 127) {
printf "thread $id died from signal %d\n", $res & 127;
return 1;
}
else {
my $rcode = $res >> 8;
if ($rcode != 0) {
say "thread $id exited with return value $rcode";
return 1;
}
return 0;
}
}
When setting $force_fail = 1 on line 9 of the main script, the output is:
joining thread 0..
thread 0 exited with return value 2
detaching thread 1..
Program failed after 2 seconds
On the other hand, when setting $force_fail = 0 the output is:
joining thread 0..
joining thread 1..
Program succeeded after 5 seconds

Related

Error in ImageCollection$select() Error in py_get_attr_impl(x, name, silent) : OverflowError: Python int too large to convert to C long

I'm trying to apply $select at a imageCollection object in rgee but I face the error when I source my script: Error in py_get_attr_impl(x, name, silent) :
OverflowError: Python int too large to convert to C long
When I run every command individually,line by line, in R studio console no problem happens.
Here is the shapefile used in this example : https://mega.nz/file/RkcDxARZ#9lgwP6-RMGE1DgMZ5eE6YoxI8cmYER6iJflVUzsmGtI
rgee version: rgee 1.1.4
R version: 4.2.1
Operating System: Win 10
If I run this code in R Studio console it executes and finish without problems, when I source the script it does not work.
shid<-shapefile("D:/temp/rgee_example/feat1.shp")
ids<-shid$text1
require(rgee)
require(mapview)
ee_Initialize(drive = TRUE)
shp<-ee$FeatureCollection("users/********/feat1")
sentinel2 <- ee$ImageCollection$Dataset$COPERNICUS_S2$
filterDate("2021-08-01","2021-08-30")$
filterBounds(shp)
#info<-sentinel2$getInfo()
sentBands<-sentinel2$toBands()
nshp<-shp$filter('text1 == "id1"')
k=1
#for(k in 1:length(ids)){
#nshp<-shp$filter(paste0("'text1 == " ,'"', ids[k] ,'"', "'"))
sentBands<-sentBands$clip(nshp)
info<-sentBands$getInfo()
b2Sele<-NULL
for(i in 1:length(info$bands)){
imId<-info$bands[[i]]$id
if(length(grep("_B2",imId))==1)b2Sele[length(b2Sele)+1]<-imId
}
sentB2 <- sentBands$select(c(b2Sele))
ee_raster <- ee_as_raster(
image = sentB2,
region = nshp$geometry(),
dsn = paste0("D:/gee/sentinel2/date_stack/sentinel2_B2_",ids[k],".tif"),
via = "drive"
)
> source("~/.active-rstudio-document")
── rgee 1.1.4 ─────────────────────────────────────────────────────── earthengine-api 0.1.318 ──
✔ user: not_defined
✔ Google Drive credentials: FOUND
✔ Initializing Google Earth Engine: DONE!
✔ Earth Engine account: users/*********
────────────────────────────────────────────────────────────────────────────────────────────────
Error in py_get_attr_impl(x, name, silent) :
OverflowError: Python int too large to convert to C long

Error when running Rcpp in linux batch mode

I am trying to run a very simple model with rstan in batch mode and have some errors. I do not have any errors when I try to run the same code not in batch mode.
The community from STAN Forums helped me to understand that the issue is that Rcpp instead of STAN is not working properly on the server of my university. We reached this understanding from a test trying to run a very simple Rcpp code in batch mode and not in batch mode. The Rcpp code is:
### Libraries
library(Rcpp)
Rcpp::sourceCpp(code='
#include <Rcpp.h>
// [[Rcpp::export]]
int fibonacci(const int x) {
if (x == 0) return(0);
if (x == 1) return(1);
return (fibonacci(x - 1)) + fibonacci(x - 2);
}',
verbose = TRUE,
rebuild = TRUE
)
The results are below.
Not in batch mode:
Generated R functions
-------------------------------------------------------
`.sourceCpp_1_DLLInfo` <- dyn.load('/tmp/RtmpDNL6of/sourceCpp-x86_64-pc-linux-gnu-1.0.7/sourcecpp_178b21d435d91/sourceCpp_4.so')
fibonacci <- Rcpp:::sourceCppFunction(function(x) {}, FALSE, `.sourceCpp_1_DLLInfo`, 'sourceCpp_1_fibonacci')
rm(`.sourceCpp_1_DLLInfo`)
Building shared library
--------------------------------------------------------
DIR: /tmp/RtmpDNL6of/sourceCpp-x86_64-pc-linux-gnu-1.0.7/sourcecpp_178b21d435d91
/hpc/apps/R/4.1.2/lib64/R/bin/R CMD SHLIB --preclean -o 'sourceCpp_4.so' 'file178b25628f5ea.cpp'
g++ -std=gnu++14 -I"/hpc/apps/R/4.1.2/lib64/R/include" -DNDEBUG -I"/hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include" -I"/tmp/RtmpDNL6of/sourceCpp-x86_64-pc-linux-gnu-1.0.7" -I/hpc/apps/zlib/1.2.8/include -I/hpc/apps/pcre/8.38/include -I/hpc/apps/bzip2/1.0.6/include -I/hpc/apps/curl/7.54.1/include -I/hpc/apps/cairo/1.14.12/include -fpic -g -O2 -c file178b25628f5ea.cpp -o file178b25628f5ea.o
g++ -std=gnu++14 -shared -L/hpc/apps/R/4.1.2/lib64/R/lib -L/hpc/apps/zlib/1.2.8/lib -L/hpc/apps/pcre/8.38/lib -L/hpc/apps/bzip2/1.0.6/lib -L/hpc/apps/curl/7.54.1/lib -L/hpc/apps/cairo/1.14.12/lib -o sourceCpp_4.so file178b25628f5ea.o -L/hpc/apps/R/4.1.2/lib64/R/lib -lR
In batch mode:
Generated R functions
-------------------------------------------------------
`.sourceCpp_1_DLLInfo` <- dyn.load('/localscratch/250948.1.ragatkolab.q/RtmpDlK5Sy/sourceCpp-x86_64-pc-linux-gnu-1.0.7/sourcecpp_142bd68d660f1/sourceCpp_2.so')
fibonacci <- Rcpp:::sourceCppFunction(function(x) {}, FALSE, `.sourceCpp_1_DLLInfo`, 'sourceCpp_1_fibonacci')
rm(`.sourceCpp_1_DLLInfo`)
Building shared library
--------------------------------------------------------
DIR: /localscratch/250948.1.mylab.q/RtmpDlK5Sy/sourceCpp-x86_64-pc-linux-gnu-1.0.7/sourcecpp_142bd68d660f1
/hpc/apps/R/4.1.2/lib64/R/bin/R CMD SHLIB -o 'sourceCpp_2.so' 'file142bd64ebe902.cpp'
g++ -std=gnu++14 -I"/hpc/apps/R/4.1.2/lib64/R/include" -DNDEBUG -I"/hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include" -I"/localscratch/250948.1.ragatkolab.q/RtmpDlK5Sy/sourceCpp-x86_64-pc-linux-gnu-1.0.7" -I/hpc/apps/zlib/1.2.8/include -I/hpc/apps/pcre/8.38/include -I/hpc/apps/bzip2/1.0.6/include -I/hpc/apps/curl/7.54.1/include -I/hpc/apps/cairo/1.14.12/include -fpic -g -O2 -c file142bd64ebe902.cpp -o file142bd64ebe902.o
In file included from /hpc/apps/gcc/9.1.0/include/c++/9.1.0/x86_64-pc-linux-gnu/bits/c++config.h:524,
from /hpc/apps/gcc/9.1.0/include/c++/9.1.0/cmath:41,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp/platform/compiler.h:100,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp/r/headers.h:66,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/RcppCommon.h:30,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp.h:27,
from file142bd64ebe902.cpp:2:
/hpc/apps/gcc/9.1.0/include/c++/9.1.0/x86_64-pc-linux-gnu/bits/os_defines.h:39:10: fatal error: features.h: No such file or directory
39 | #include <features.h>
| ^~~~~~~~~~~~
compilation terminated.
make: *** [file142bd64ebe902.o] Error 1
Error in Rcpp::sourceCpp(code = "\n #include <Rcpp.h>\n\n // [[Rcpp::export]]\n int fibonacci(const int x) {\n if (x == 0) return(0);\n if (x == 1) return(1);\n return (fibonacci(x - 1)) + fibonacci(x - 2);\n }", :
Error 1 occurred building shared library.
WARNING: The tools required to build C++ code for R were not found.
Please install GNU development tools including a C++ compiler.
Execution halted
Then, they asked me to modify my makevars file - which I did using the R-package usethis::edit_r_makevars() - adding the lines:
CXXFLAGS += -I"/hpc/apps/gcc/9.1.0/include/c++/9.1.0/parallel/"
CXX14FLAGS += -I"/hpc/apps/gcc/9.1.0/include/c++/9.1.0/parallel/"
Once I did this modification (I hope I did it correctly), my error message change to:
Generated extern "C" functions
--------------------------------------------------------
#include <Rcpp.h>
#ifdef RCPP_USE_GLOBAL_ROSTREAM
Rcpp::Rostream<true>& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
Rcpp::Rostream<false>& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
#endif
// fibonacci
int fibonacci(const int x);
RcppExport SEXP sourceCpp_1_fibonacci(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const int >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(fibonacci(x));
return rcpp_result_gen;
END_RCPP
}
Generated R functions
-------------------------------------------------------
`.sourceCpp_1_DLLInfo` <- dyn.load('/localscratch/251578.1.mylablab.q/RtmpCHyEAd/sourceCpp-x86_64-pc-linux-gnu-1.0.7/sourcecpp_1e50364a03315/sourceCpp_2.so')
fibonacci <- Rcpp:::sourceCppFunction(function(x) {}, FALSE, `.sourceCpp_1_DLLInfo`, 'sourceCpp_1_fibonacci')
rm(`.sourceCpp_1_DLLInfo`)
Building shared library
--------------------------------------------------------
DIR: /localscratch/251578.1.mylablab.q/RtmpCHyEAd/sourceCpp-x86_64-pc-linux-gnu-1.0.7/sourcecpp_1e50364a03315
/hpc/apps/R/4.1.2/lib64/R/bin/R CMD SHLIB -o 'sourceCpp_2.so' 'file1e50325e7686.cpp'
g++ -std=gnu++14 -I"/hpc/apps/R/4.1.2/lib64/R/include" -DNDEBUG -I"/hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include" -I"/localscratch/251578.1.mylablab.q/RtmpCHyEAd/sourceCpp-x86_64-pc-linux-gnu-1.0.7" -I/hpc/apps/zlib/1.2.8/include -I/hpc/apps/pcre/8.38/include -I/hpc/apps/bzip2/1.0.6/include -I/hpc/apps/curl/7.54.1/include -I/hpc/apps/cairo/1.14.12/include -fpic -g -O2 -I"/hpc/apps/gcc/9.1.0/include/c++/9.1.0/parallel/" -c file1e50325e7686.cpp -o file1e50325e7686.o
In file included from /hpc/apps/gcc/11.1.0/include/c++/11.1.0/x86_64-pc-linux-gnu/bits/c++config.h:571,
from /hpc/apps/gcc/11.1.0/include/c++/11.1.0/cmath:41,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp/platform/compiler.h:100,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp/r/headers.h:66,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/RcppCommon.h:30,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp.h:27,
from file1e50325e7686.cpp:2:
/hpc/apps/gcc/11.1.0/include/c++/11.1.0/x86_64-pc-linux-gnu/bits/os_defines.h:44:19: error: missing binary operator before token "("
44 | #if __GLIBC_PREREQ(2,15) && defined(_GNU_SOURCE)
| ^
/hpc/apps/gcc/11.1.0/include/c++/11.1.0/x86_64-pc-linux-gnu/bits/os_defines.h:52:19: error: missing binary operator before token "("
52 | #if __GLIBC_PREREQ(2, 27)
| ^
In file included from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp/platform/compiler.h:100,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp/r/headers.h:66,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/RcppCommon.h:30,
from /hpc/home/user/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp.h:27,
from file1e50325e7686.cpp:2:
/hpc/apps/gcc/11.1.0/include/c++/11.1.0/cmath:45:15: fatal error: math.h: No such file or directory
45 | #include_next <math.h>
| ^~~~~~~~
compilation terminated.
make: *** [file1e50325e7686.o] Error 1
Error in Rcpp::sourceCpp(code = "\n #include <Rcpp.h>\n\n // [[Rcpp::export]]\n int fibonacci(const int x) {\n if (x == 0) return(0);\n if (x == 1) return(1);\n return (fibonacci(x - 1)) + fibonacci(x - 2);\n }", :
Error 1 occurred building shared library.
WARNING: The tools required to build C++ code for R were not found.
Please install GNU development tools including a C++ compiler.
Execution halted
My knowledge in Linux is limited and I am afraid that my question is out of scope for STAN Forums. Any thoughts how to proceed?
I fear your problem is still local. On the computing you use, someone may have set up R in way that makes it differ between interactive R use, and what you call batch use.
But that is non-standard, and at your end. In general, it just works. Using a minimally modified version of your program (which I still find confusing: it loads doParallel, registers cores but ... triggers to parallel code -- anyway) it works just fine:
Using Rscript
edd#rob:~/git/stackoverflow/70470842(master)$ Rscript answer.R
Loading required package: foreach
Loading required package: iterators
Loading required package: parallel
Fib(10) is 55
edd#rob:~/git/stackoverflow/70470842(master)$
Using R in batch mode
edd#rob:~/git/stackoverflow/70470842(master)$ R -s -f answer.R
Loading required package: foreach
Loading required package: iterators
Loading required package: parallel
Fib(10) is 55
edd#rob:~/git/stackoverflow/70470842(master)$
Using our littler frontend
edd#rob:~/git/stackoverflow/70470842(master)$ r answer.R
Loading required package: foreach
Loading required package: iterators
Loading required package: utils
Loading required package: parallel
Fib(10) is 55
edd#rob:~/git/stackoverflow/70470842(master)$
Modified source code
library(doParallel) # Library
ncores <- 5 # Simulation parameters
n_sim <- 5
registerDoParallel(ncores)
Rcpp::sourceCpp(code='
#include <Rcpp.h>
// [[Rcpp::export]]
int fibonacci(const int x) {
if (x == 0) return(0);
if (x == 1) return(1);
return (fibonacci(x - 1)) + fibonacci(x - 2);
}'
)
cat("Fib(10) is ", fibonacci(10), "\n")
For future reference, I interacted with IT team from my institution after feedback received here and STAN Forums, and they finally found a solution. In their words:
"Compute nodes aren't normally used for development. So certain development packages are not installed by default. We installed "glibc-devel" and "glibc-headers" on the compute nodes.
So, it seems that when run interactively the job was running on the submit node (which had these libraries installed) and when run from the scheduler it was run on the compute nodes (which did not have the library installed). The reason for the discrepancy being that the libraries in question have traditionally been only used during development and compilation. This use posed a unique use case."

Internal function of R package not found when using foreach with checkpoint

This is a follow-up question of this question: How to set .libPaths (checkpoint) on workers when running parallel computation in R
Based on the answer I put the following code (simplified example) into an R package called 'test1':
#' #export
f <- function() {
`%dopar%` <- foreach::`%dopar%`
doFuture::registerDoFuture()
libs <- .libPaths()
res <- foreach::foreach(x = 1:2) %dopar% {
cat(sprintf("Initial Library paths used by worker (PID %d):\n", Sys.getpid()))
cat(sprintf(" - %s\n", sQuote(.libPaths()[1])))
## Use the same library paths as the master R session
.libPaths(libs)
cat(sprintf("Library paths used by worker (PID %d):\n", Sys.getpid()))
cat(sprintf(" - %s\n", sQuote(.libPaths()[1])))
x + g()
}
res
}
g <- function() {
h()
}
h <- function() {
runif(1)
}
Then I called checkpoint::checkpoint("2018-07-24") and installed the package into the checkpoint library. The following code then produced this error:
checkpoint::checkpoint("2018-07-24")
future::plan("multisession")
test1::f()
Initial Library paths used by worker (PID 16880):
- 'C:/Programme/R-3.5.1/library'
Library paths used by worker (PID 16880):
- '.../.checkpoint/2018-07-24/lib/x86_64-w64-mingw32/3.5.1'
Initial Library paths used by worker (PID 3916):
- 'C:/Programme/R-3.5.1/library'
Library paths used by worker (PID 3916):
- '.../.checkpoint/2018-07-24/lib/x86_64-w64-mingw32/3.5.1'
Error in { : task 1 failed - "could not find function "h""
When I explicitly call test1:::g() inside the foreach call, it works though. Can someone explain, why I have to explicitly call a function of my own package inside a foreach loop with :::? It looks like g() seems to be found, but h() then not?

Building package with Rcpp, generated .h file missing header

I am currently building a package in RStudio that uses Rcpp. I have defined the following .cpp file, which works with Rcpp::sourceCpp.
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::interfaces(r, cpp)]]
#include <Rcpp.h>
#include <unordered_set>
using namespace Rcpp;
// [[Rcpp::export]]
std::unordered_set<int> traverse_cor(NumericMatrix x, float maxcor) {
std::unordered_set<int> elements;
int ncol = x.ncol();
for(int i = 0; i < ncol; i++) {
for(int j = 0; j < ncol; j++) {
if(i < j) {
if(x(i, j) > maxcor && x(i, j) < 1){
elements.insert(i + 1);
}
}
}
}
return elements;
}
I am following the directions from here and here. Next I call Rcpp::compileAttributes(). This produces the following files:
src/RcppExports.cpp
R/RcppExports.R
inst/include/mypackage.h
inst/include/mypackage_RcppExports.h
The generated mypackage_RcppExports.h file looks as follows:
// This file was generated by Rcpp::compileAttributes
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#ifndef __gwassim_RcppExports_h__
#define __gwassim_RcppExports_h__
#include <Rcpp.h>
namespace gwassim {
using namespace Rcpp;
namespace {
void validateSignature(const char* sig) {
Rcpp::Function require = Rcpp::Environment::base_env()["require"];
require("gwassim", Rcpp::Named("quietly") = true);
typedef int(*Ptr_validate)(const char*);
static Ptr_validate p_validate = (Ptr_validate)
R_GetCCallable("gwassim", "gwassim_RcppExport_validate");
if (!p_validate(sig)) {
throw Rcpp::function_not_exported(
"C++ function with signature '" + std::string(sig) + "' not found in gwassim");
}
}
}
inline std::unordered_set<int> traverse_cor(NumericMatrix x, float maxcor) {
typedef SEXP(*Ptr_traverse_cor)(SEXP,SEXP);
static Ptr_traverse_cor p_traverse_cor = NULL;
if (p_traverse_cor == NULL) {
validateSignature("std::unordered_set<int>(*traverse_cor)(NumericMatrix,float)");
p_traverse_cor = (Ptr_traverse_cor)R_GetCCallable("gwassim", "gwassim_traverse_cor");
}
RObject __result;
{
RNGScope __rngScope;
__result = p_traverse_cor(Rcpp::wrap(x), Rcpp::wrap(maxcor));
}
if (__result.inherits("interrupted-error"))
throw Rcpp::internal::InterruptedException();
if (__result.inherits("try-error"))
throw Rcpp::exception(as<std::string>(__result).c_str());
return Rcpp::as<std::unordered_set<int> >(__result);
}
}
#endif // __gwassim_RcppExports_h__
After attempting to build and reload the package, I receive the following errors (1):
../inst/include/gwassim_RcppExports.h:27:12: error: 'unordered_set' in
namespace 'std' does not name a type
And (2)
RcppExports.cpp:12:1: error: 'unordered_set' in namespace 'std' does
not name a type
I have limited C++ experience, but my sense is that these errors occur due to #include <unordered_set> being omitted. How do I get these automatically generated files to have the correct headers?
My sessionInfo is the following:
Session info ----------------------------------------------------------------------
setting value
version R version 3.1.0 (2014-04-10)
system x86_64, mingw32
ui RStudio (0.99.235)
language (EN)
collate English_United States.1252
tz America/New_York
Packages --------------------------------------------------------------------------
package * version date source
devtools 1.7.0.9000 2015-02-11 Github (hadley/devtools#9415a8a)
digest * 0.6.4 2013-12-03 CRAN (R 3.1.0)
memoise * 0.2.1 2014-04-22 CRAN (R 3.1.0)
mvtnorm 1.0-2 2014-12-18 CRAN (R 3.1.2)
Rcpp 0.11.4 2015-01-24 CRAN (R 3.1.2)
roxygen2 * 4.1.0 2014-12-13 CRAN (R 3.1.2)
rstudioapi * 0.2 2014-12-31 CRAN (R 3.1.2)
stringr * 0.6.2 2012-12-06 CRAN (R 3.0.0)
And my version of g++ is 4.6.3, as included in the RTools package for Windows. I have enabled C++11 features with the following:
Sys.setenv("PKG_CXXFLAGS"="-std=c++0x").
That is a finicky one. I think you want Section 3.5.2 of the Rcpp Attributes vignette and this trick:
The Package.h file does nothing other than include the
Package_RcppExports.h header. This is done so that package
authors can replace the Package.h header with a custom one
and still be able to include the automatically generated exports
(details on doing this are provided in the next section).
In passing, I think I also convinced you to create a package rather than to rely just on sourceCpp() :)
Edit: Doh!! I overlooked the part that
std::unordered_set<int> traverse_cor(NumericMatrix x, float maxcor)
is probably not an automatically wrappable function. You may need to convert your set into a vector (or list or ...) to get one of the types that matches naturally into R.

How to check platform in .onLoad in the R package

I am trying to check if the package is run on Windows during the loading of the package and load some additional files. For some reason this doesn't work (added to my zzz.R):
.onLoad <- function(libname, pkgname){
if(.Platform$OS.type == "windows") {
# do specific task here
}
}
How to make it work, is there a better way to do it?
EDIT to correct a wrong previous answer
After loading, loadNamespace looks for a hook function named .onLoad and calls it. The functions loadNamespace is usually called implicitly when library is used to load a package. However you can be useful at times to call these functions directly. So the following(essentially your code) works for me under windows platform.
.onLoad <- function(libname, pkgname ) {
if(.Platform$OS.type == "windows") print("windows")
else print("others")
}
Then you test it using:
loadNamespace("loadpkg")
[1] "windows"
<environment: namespace:loadpkg>
Note also you can have the same thing using library, but you should unload the namespace before (I guess it checks if the package is already loaded and don't call all hooks):
unloadNamespace("loadpkg")
library("loadpkg")
[1] "windows"
don't use this , it is a wrong but accepted solution
You should initialize function parameters:
.onLoad <- function(libname = find.package(pkg_name), pkgname = pkg_name){
if(.Platform$OS.type == "windows") {
# do specific task here
}
}

Resources