Rcpp::compileAttributes() not updating .R file - r

I am trying to build a package in R involving the Rcpp package. When I generated the package using the command Rcpp.package.skeleton("pck338").
By default, the files rcpp_hello_world.cpp is included, and the RcppExports.cpp file is included as well.
To my understanding, the compileAttributes() function needs to be run every time a new .cpp function is added to the src directory.
To that end, I wrote a simple function in the rcpp_dance.cpp file that goes like this:
# include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp:export]]
int rcpp_dance(int x) {
int val = x + 5;
return val;
}
However, when I run the compileAttributes(), the RcppExports.cpp stays the same, so the dance function is not converted to an R function. Why is this happening? Any specific and general feedback would be appreciated.

In a case like this where it smells like a possible error, check for a possible error. I learned (the hard way) to first assume I goofed...
In your case: :: != :.
You wanted Rcpp::export with two colons. Try that, rinse, repeat...
(And for the other conjecture: you need to re-run compileAttributes() each time an interface changes: adding or removing or renaming or retyping an argument in the signature, and of course adding or removing whole functions. But thankfully the function is so fast that you may as well get in the habit of running it often. If in doubt, run it.)

Related

Compatibility of Rcpp code involving std::transform in package

I am in the process of finishing a package I've been working on. All checks look good and it compiles without problems on my computer. win-builder has no problems with the package as well. As further check, I've tried to install from source on the computer of a colleague and it fails. The problem comes from a Rcpp function that I've taken from a StackOverflow thread on vector powers in Rcpp:
NumericVector vecpow(const NumericVector base, const NumericVector exp) {
NumericVector out(base.size());
std::transform(base.begin(), base.end(),
exp.begin(), out.begin(), ::pow);
return out;
}
This compiles and works fine for me, but throws an error for my colleague when installing, involving
error: no matching function function for call to 'transform'
and
candidate function template not viable: requires 4 arguments, but 5 were provided.
I can reproduce the error for instance by replacing ::pow in the original code by pow. I'm on Windows 8.1, my colleague is on Mac. The colleague maintains his own packages involving extensive amounts of Rcpp code and usually has no problems with compiling.
I assume that this might be a compiler problem. The original thread has some alternative code involving C++11 (thread is already five years old), so in principle, I could replace the problematic code using alternatives. However, as I'm not very experienced with this, this would be trial and error. My question is: Is there a simple reason why this error pops up? And how can I modify my code in order to be sure that the package will be installable and usable for most users?
the error is caused because the compiler can't match the std::pow function as binary operation (this may be due to the fact that it has at least two overloads and the compiler can't guess the types float/double) giving rise to the following note :
note: candidate template ignored: couldn't infer template argument '_BinaryOperation'
And then it falls back to the unary std::transform which only has 4 arguments pushing the second note:
note: candidate function template not viable: requires 4 arguments, but 5 were provided
Compilation stops as it hasn't found a valid std::transform to apply to the specified arguments.
Switching from pow to powf stops this issue as the compiler doesn't have to resolve any overloads, however precision might be lost due to this change :
Rcpp::cppFunction("NumericVector vecpow(const NumericVector base, const NumericVector exp) {
NumericVector out(base.size());
std::transform(base.begin(), base.end(),
exp.begin(), out.begin(), ::powf);
return out;
}
") -> pow
pow(1:5,5:1)
[1] 1 16 27 16 5
Another work around would be to use static cast i.e replace ::pow with static_cast<double(*)(double, double)>(::pow) to tell the compiler to use the double overload of pow

How to quit/exit from file included in the terminal

What can I do within a file "example.jl" to exit/return from a call to include() in the command line
julia> include("example.jl")
without existing julia itself. quit() will just terminate julia itself.
Edit: For me this would be useful while interactively developing code, for example to include a test file and return from the execution to the julia prompt when a certain condition is met or do only compile the tests I am currently working on without reorganizing the code to much.
I'm not quite sure what you're looking to do, but it sounds like you might be better off writing your code as a function, and use a return to exit. You could even call the function in the include.
Kristoffer will not love it, but
stop(text="Stop.") = throw(StopException(text))
struct StopException{T}
S::T
end
function Base.showerror(io::IO, ex::StopException, bt; backtrace=true)
Base.with_output_color(get(io, :color, false) ? :green : :nothing, io) do io
showerror(io, ex.S)
end
end
will give a nice, less alarming message than just throwing an error.
julia> stop("Stopped. Reason: Converged.")
ERROR: "Stopped. Reason: Converged."
Source: https://discourse.julialang.org/t/a-julia-equivalent-to-rs-stop/36568/12
You have a latent need for a debugging workflow in Julia. If you use Revise.jl and Rebugger.jl you can do exactly what you are asking for.
You can put in a breakpoint and step into code that is in an included file.
If you include a file from the julia prompt that you want tracked by Revise.jl, you need to use includet(.
The keyboard shortcuts in Rebugger let you iterate and inspect variables and modify code and rerun it from within an included file with real values.
Revise lets you reload functions and modules without needing to restart a julia session to pick up the changes.
https://timholy.github.io/Rebugger.jl/stable/
https://timholy.github.io/Revise.jl/stable/
The combination is very powerful and is described deeply by Tim Holy.
https://www.youtube.com/watch?v=SU0SmQnnGys
https://youtu.be/KuM0AGaN09s?t=515
Note that there are some limitations with Revise, such as it doesn't reset global variables, so if you are using some global count or something, it won't reset it for the next run through or when you go back into it. Also it isn't great with runtests.jl and the Test package. So as you develop with Revise, when you are done, you move it into your runtests.jl.
Also the Juno IDE (Atom + uber-juno package) has good support for code inspection and running line by line and the debugging has gotten some good support lately. I've used Rebugger from the julia prompt more than from the Juno IDE.
Hope that helps.
#DanielArndt is right.
It's just create a dummy function in your include file and put all the code inside (except other functions and variable declaration part that will be place before). So you can use return where you wish. The variables that only are used in the local context can stay inside dummy function. Then it's just call the new function in the end.
Suppose that the previous code is:
function func1(...)
....
end
function func2(...)
....
end
var1 = valor1
var2 = valor2
localVar = valor3
1st code part
# I want exit here!
2nd code part
Your code will look like this:
var1 = valor1
var2 = valor2
function func1(...)
....
end
function func2(...)
....
end
function dummy()
localVar = valor3
1st code part
return # it's the last running line!
2nd code part
end
dummy()
Other possibility is placing the top variables inside a function with a global prefix.
function dummy()
global var1 = valor1
global var2 = valor2
...
end
That global variables can be used inside auxiliary function (static scope) and outside in the REPL
Another variant only declares the variables and its posterior use is free
function dummy()
global var1, var2
...
end

Calling the original function after tweaking arguments is an incorrect use of the R-API?

I am trying to create a small extension for R here for embedding the current time on the R prompt: https://github.com/musically-ut/extPrompt
Things seem to be working overall, but R CMD check . raised a warning:
File '[truncated]..Rcheck/extPrompt/libs/extPrompt.so’:
Found non-API call to R: ‘ptr_R_ReadConsole’
Compiled code should not call non-API entry points in R.
The concerned file is this: https://github.com/musically-ut/extPrompt/blob/master/src/extPrompt.c and occurs on line 38, I think.
void extPrompt() {
// Initialize the plugin by replacing the R_ReadConsole function
old_R_ReadConsole = ptr_R_ReadConsole;
ptr_R_ReadConsole = extPrompt_ReadConsole;
// ...
}
int extPrompt_ReadConsole(const char *old_prompt, unsigned char *buf, int len,
int addtohistory) {
// ...
// Call the old function with the `new_prompt`
return (*old_R_ReadConsole)(new_prompt, buf, len, addtohistory);
}
I am trying to make the R_ReadConsole API call. However, since a different plugin (like mine) could have overridden it already, I do not want to directly invoke R_ReadConsole but the function which previously was at ptr_R_ReadConsole.
Is this an incorrect use of the API?
From the r-devel mailing list:
As for incorrectly using the API - yes. Since R CMD check is telling
you this is a problem, it is officially a problem. This is of no
consequence if the package works for you and any users of it, and
the package is not to be hosted on CRAN. However, using this symbol in
your code may not work on all platforms, and is not guaranteed to
work in the future (but probably will!).

Clear the file stat cache in R?

In a RUnit test I have this snippet:
checkTrue(!file.exists(fname))
doSomething()
#cat(fname);print(file.info(fname))
checkTrue(file.exists(fname))
The second call to checkTrue() is failing, even though doSomething() creates a file. I've confirmed the file is there with the commented out line, shown above.
So, I'm wondering if the second call to file.exists is using cached data? In PHP there is a function called clearstatcache that stops this happening. Is there an R equivalent? (Or, perhaps, someone knows that R never caches results of stat calls?)
file.exists does not cache the result of the stat call, so there is no equivalent of PHP's clearstatcache. (Aside: that also means excessive use of calling file.exists, or any stat function, might degrade performance.)
As of R 3.0.1, file.exists uses an internal method. If you follow it through the source you will eventually end up with a call to R_FileExists, in sysutils.c:
Rboolean R_FileExists(const char *path)
{
struct stat sb;
return stat(R_ExpandFileName(path), &sb) == 0;
}
(On Windows it instead uses a call to _stat64 which I've just confirmed also does not do caching.)

Code auto-completion trouble with Rcpp and Netbeans/Eclipse

I'm trying to write some Rcpp code using Netbeans, primarily using the IDE for the method look-up / code completion. I've set up the project to include the R/include and R/library/Rcpp/include folders, and it seems this -almost- works. For example, if I write
#include <Rcpp.h>
Rcpp::CharacterVector x;
x. // hit CTRL+SPACE to pop-up methods available to x, no hits
However, if we look at what a CharacterVector is, we see:
typedef Vector<STRSXP> CharacterVector
which is defined in Rcpp/include/vector/instanstiation.h, so it should (?) just be inheriting all the methods available to the Rcpp::Vector class. Equivalently, if I write
Rcpp::Vector<STRSXP> x;
x. // hit CTRL+SPACE, and I do see a bunch of methods available
it does work. Furthermore, if I just copy the typedef declaration into my current source file, then the auto-completion does work.
So, I guess my question is - why does Netbeans struggle in finding the methods available to Rcpp::CharacterVector but not Rcpp::Vector?
Ultimately, it's not a big problem, but I am curious...

Resources