Re: [Rcpp-devel] new to R, so don't understand Rcpp limits

2017-08-04 Thread Christian Gunning
> | Hi,
> | I need to share some data between my Python code and my c++ code, C++
> does
> | not really have a lot of nice ideas like DataFrames. But if you save a
> | dataframe from Python into csv, you can readily read it using R. Csv is
> not
> | the best way to go, but it is a simple case.
>
> CSVs are indeed a terrible format, yet annoyingly common. Try binary
> alternatives if you can.
>

I disagree with Dirk that CSV is "a terrible format" - it excels (hah) at
human readability, is decently machine-readable and easily compressible,
but certainly is inappropriate for many tasks that require efficiency.


> | I have generally been noticing as I google around, that R has a healthy
> and
> | seemingly growing list of packages that can be accessed by c++ code. From
> | c++, R does not look so bad to me, and I would like to get access to this
> | large library of native routines in R.
> |
> | First on the list, is that I hope to read a dataframe or something like
> it
> | from data in a file, and then transform that dataframe or other tabular
> | object into something I can use in my c++ code for linear algebra, like
> an
> | Armadillo matrix.
> |
> | So is there any native code in the R world that I can use to read a
> | dataframe from a file?
>

First off, only use a data.frame if what you really want is a data.frame.
Otherwise, stick with a matrix (or convert to one as early as possible).

* Data.frame = ordered collection of like-sized vectors, possibly of
heterogeneous type.
* Matrix = ordered collection values, of known / fixed dimension, by
default represented internally as columns of vectors in both R and
armadillo (as in LAPACK).

In R, for modest-sized objects, going between these two types is
"relatively seamless". But in C++/Rcpp, the underlying differences are more
apparent to the user.  Matrices "just work" (e.g. easy construction of an
"identical" armadillo object), whereas data.frames require some care and
attention, and possibly extra object creation destruction.  When possible,
stick with matrices.


> |
> | I think Rcpp is really cool,
>
it might make me
> | a backdoor R user.
>

I became a backdoor C++ programmer through C++.  +1 really cool.

I found Google Protocol Buffers absurdly useful for moving between R and
cpp in complex projects.  It's well-documented, fast, encourages
separate/good metadata documentation, and works smoothly for R, C++, and
Python.   I never did use protobufs for vector data, though. I did write
some test code using repeated fields, but didn't get to the point of
comfort there. For arrays of fixed dimension, I can imagine using one field
per dimension to code that dimension's length, and then a final repeated
field with the payload.  See below for example.

Question for Dirk (et al):

Has anyone used protobuf messages for, e.g., passing arrays? Any obvious
downsides?  When I last googled, I didn't find much re protobuf repeated
fields or Rcpp + protobufs...


// File PbTest.proto
syntax = "proto2";
package Array;
// see
https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#fields

message a2d {
optional uint32 dim1 = 10;
optional uint32 dim2 = 20;
// add more dims here
//
// numeric vector
repeated float  payload = 50;
}

## File pbarray.R
library(RProtoBuf)
aa <- matrix(1:30, ncol=3)
bb <- new(P("Array.a2d", file='PbTest.proto'))
bb$dim1 <- dim(aa)[1]
bb$dim2 <- dim(aa)[2]
bb$add(field='payload', values=aa)

cat(as.character(bb))

best,
Christian
http://www.x14n.org
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] R.e. element wise multiplication of a subcube and a row of a matrix

2017-01-09 Thread Christian Gunning
> I am posting again a question about the subject cited. I tried to search
> this problem but did not find. My question is why we cannot multiply
> element wise a subcube and a row of a matrix.
>
> Any help would be appriciated. The following is sample code which is giving
> erros about the operand %.
>
>
> #include 
> using namespace Rcpp;
> using namespace RcppArmadillo;
> using namespace arma;
> //[[Rcpp::depends(RcppArmadillo)]]
> //[[Rcpp::export]]
>
> arma::rowvec sub(arma::cube a, arma::mat b)
> {
> rowvec x  =  a.subcube(0, 0, 0, 0, 2, 0)% b.row(0);
> return x;
> }

Shaami,

When posting questions to the list, please include a complete working example.
Hint - how would I paste your example into R and get a result?
What do you expect the result to be?
How does the result differ from your expectations?

best,
Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Timings for a program

2017-01-06 Thread Christian Gunning
Why is there a dot in ".*"? Are you perhaps thinking of Matlab?

On Fri, Jan 6, 2017 at 8:53 PM, Shaami  wrote:
> I have deleted two for loops from my code and trying to use vectors in place
> of them.

For reference, there's very little benefit to removing loops in a
compiled language.  What Martyn said is exactly correct - it's your
responsibility to understand the difference between an interpreted
language like R and a compiled language like C++.

Some rules of thumb:
* In both R and C++, avoid unnecessary memory allocations.
* In R, minimize the number of distinct function calls.
  - A single function call: val = sum(1:10)
  - 10 function calls: val = 0; for (ii in 1:10) { val = val + ii}


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Timings for a program

2017-01-05 Thread Christian Gunning
> I am new to Rcpp. I have converted my R program into an Rcpp program.
> I want to ask a general question. Using Rcpp, my code is taking about 3
> minutes to produce output for 100 observations. But it is taking about 2.45
> hours to produce output for 1000 observations. Any suggestions or technical
> hint for this type of problem.

First off, please include a minimal working example with your
question. Without more information, there's not much we can do to
help.

In the meantime, you might find this to be an interesting and helpful read:
http://www.burns-stat.com/documents/books/the-r-inferno/

Best,
Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
http://www.x14n.org
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp ISNAN slower than C ISNAN?

2016-12-14 Thread Christian Gunning
On Wed, Dec 14, 2016 at 12:23 PM, Johannes Kruisselbrink
 wrote:
>
> Good point. Actually, I didn't even realize there were so many is-nan
> functions to choose from. But indeed, we used the R-core ISNAN function on
> doubles accessed via Rcpp.

Me either :)
Of course, the above isn't particular to Rcpp, but I found that
tracking down the underlying machinery of ISNAN in the context of Rcpp
to be an interesting and useful exercise.

>> Based on the above, I added permutations to a *very* minimal test (no
>> return val, etc) that include Romain's suggestion:
>> https://github.com/helmingstay/rcpp-timings/tree/master/minimal
>> ## source('benchmarks.r')
>>
[...]
>
> Wow, thank you for the thorough comparison. I ran some tests myself based on
> your code. It seems that I cannot get the "CountNans_expr" version to
> compile, any ideas?  Same problem with the Rcpp sugar isnan version.

Can you be more specific?

> The std::isnan version, however, does work and, on my machine, actually
> outperforms the call function. So performance-wise this is a very
> interesting candidate.

Just to clarify, R's NA is subset of ieee NaN.  So std::isnan catches
both NAs and NaNs.  If you need to manually catch *just* NAs, then it
looks like you need to return to an R-core solution (please do correct
me if I muxed this up).
Ref: https://github.com/wch/r-source/blob/trunk/src/main/arithmetic.c#L108

best,
Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp ISNAN slower than C ISNAN?

2016-12-14 Thread Christian Gunning
> so skipping the entire object is not really an option.

Understood - just wanted to highlight the existence of Rcpp::is_nan /
Rcpp::any in case they were broadly relevant.

> Nevertheless, the question still remains why the rcpp isNaN call is so
> much slower.

Take care to distinguish the R-core ISNAN macro, the R_IsNaN function,
and the Rcpp::isNaN template function. Asides from sugar-stuff, all
the examples discussed here so far address the performance of R-core
ISNAN, given doubles that are accessed via Rcpp, correct?

I'm not qualified to answer, but your example piqued my interest.
Based on your previous email, I'm guessing you found this?

"Currently in C code ISNAN is a macro calling isnan. (Since this gives
problems on some C++ systems, if the R headers is called from C++ code
a function call is used.) "
http://www.hep.by/gnu/r-patched/r-exts/R-exts_133.html

Definitions from the horse's mouth:
https://github.com/wch/r-source/blob/trunk/src/include/R_ext/Arith.h#L66

Based on the above, I added permutations to a *very* minimal test (no
return val, etc) that include Romain's suggestion:
https://github.com/helmingstay/rcpp-timings/tree/master/minimal
## source('benchmarks.r')

I see that:
A) the sugar expression in slow
B) based on timings, ISNAN appears to call R_isnancpp, which is slow
C) std::count_if yields a modest improvement given B)
D) Using an inline function matching the definintion of ISNAN used in
a C envir [i.e., "isnan(xx)!=0", using math.h] appears to incur no
cost at all (example CountNans_expr)

This doesn't get to the *why*, but perhaps addresses the question of
intrinsic limitations in Rcpp. Perhaps others can comment on whether
D) is equivalent to driving without a seatbelt.

hth,
-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
http://www.x14n.org/
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp ISNAN slower than C ISNAN?

2016-12-13 Thread Christian Gunning
> |for (i = 0; i < numObjects; i++) {
> |  for (j = 0; j < numCodes; j++) {
> |dist = 0;
> |for (k = 0; k < numVars; k++) {
> |  if (!ISNAN(data[i * numVars + k])) {
> |tmp = data[i * numVars + k] - codes[j * numVars + k];
>
> Why not drop data and codes and use  sData1(i,k) - sData2(j,k)  ?

Or better yet, just use the original code with NumericMatrix:
sData1[i * numVars + k] does the right thing.
I don't get any timing difference based on this change.

Using Rcpp sugar
(https://cran.r-project.org/package=Rcpp/vignettes/Rcpp-sugar.pdf),
and moving the call outside the loop, appears to do the right thing.

## modified example
## see edits here:
https://github.com/helmingstay/rcpp-timings/blob/master/diff/rcppdist.cpp#L24
git clone https://github.com/helmingstay/rcpp-timings
cd rcpp-timings/diff
R --vanilla < glue.R

best,
Christian

>
> That still doesn't explain the slowdowns though.  Could you prepare a
> _complete_ yet minimal example along with mock data?
>
> Dirk
>
> --
> http://dirk.eddelbuettel.com | @eddelbuettel | e...@debian.org
>

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
http://www.x14n.org
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] RFC: Rcpp modules vs. RefClass

2016-12-05 Thread Christian Gunning
On Wed, Nov 30, 2016 at 8:23 AM, Whit Armstrong 
wrote:

> My point regarding the clang parser is that one really shouldn't have to
> write any R or Rcpp wrappers at all.
>

I realize this is a bit academic, but I suppose my position reduces to
"RefClass + Rcpp = no wrappers at all".

For many (most?) people, a central point of Rcpp is to A) make things
faster with minimal effort while B) still use R. RefClasses add native
reference semantics to R, and one motivation for my original question is
their relative newness.  Indeed, it looks like JMC did a big doc rework
this Sept (
https://github.com/wch/r-source/commits/trunk/src/library/methods/man/refClass.Rd).
Of course, RefClasses aren't as rich in, er, nuance as Cpp classes, but
that may be a feature for many folks.

With this in mind, I assert that using a RefClass to define an object's
data & methods, and then pushing "expensive" functionality to Cpp via Rcpp
attributes, is the minimum possible "effort" required to (for expensive and
effort suitably defined): A) achieve by-reference semantics using B)
compiled-language speedup that C) doesn't mutate the args of user-facing
functions.

One annoyance using the RefClass + Rcpp approach is messy argument passing.
With the Rcpp modules approach, Cpp data members of course need not be
passed to Cpp member functions  (though some still had to be set via R, of
course). With a RefClass, one possibility is to prepare one or more named
lists to pass to Rcpp functions. These lists then, kinda-sorta, fill the
role of a cpp class's self pointer.

I wrote up a minimal example to verify that this approach isn't too costly.
It's too painfully simple to test *much*, but it perhaps provides a useful
starting point:
https://github.com/helmingstay/test_code/tree/master/convolver

For production code, my thought is to prep the relevant lists during
initialize() and then lock() them... I haven't gotten there yet :)

-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] RFC: Rcpp modules vs. RefClass

2016-11-30 Thread Christian Gunning
On Mon, Nov 28, 2016 at 9:40 PM, Christian Gunning <x...@unm.edu> wrote:

>
> B) Are there any *gotchas* with using Rcpp "modify-in-place" functions
> inside RefClass methods?
>

After some reading, I'm going to answer my own question and point to one
possible *gotcha* that wasn't clear to me at first.

* From help("refClass-class"):
"In particular, methods should not use non-exported entries in the
package's namespace, because the methods may be inherited by a reference
class in another package."

* From vignette('Rcpp-attributes'):
"The compileAttributes function deals only with exporting C++ functions to
R . If you want the functions to additionally be publicly available from
your package’s namespace another step may be required."

So, the Rcpp helper functions used by refClass methods should be exported
from the package namespace to facilitate downstream inheritance, even if
the helper functions are not intended for public consumption.  Honestly,
this is unlikely to be an issue for average users.

best,
-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] RFC: Rcpp modules vs. RefClass

2016-11-30 Thread Christian Gunning
Whit,

I see that this could be useful in similar situations where Rcpp modules
excels (generating R bindings to existing C++ classes). Language preference
aside, it's less clear to me what advantage this approach (or Rcpp modules)
offers average users over RefClasses + Rcpp functions, where the RefClass
holds state, and the Rcpp functions operate on the state using by-reference
semantics.

-Christian

On Tue, Nov 29, 2016 at 5:33 AM, Whit Armstrong <armstrong.w...@gmail.com>
wrote:

> Have a look at this project:
> https://github.com/richfitz/RcppR6
>
>
> On Mon, Nov 28, 2016 at 11:40 PM, Christian Gunning <x...@unm.edu> wrote:
>
>> Dear List,
>>
>> The following is a general request for advice / comment on modern Rcpp
>> development best-practices for package & class development. I looked over
>> the Rcpp gallery, and didn't see anything obvious that answers my
>> questions  - perhaps this discussion could serve as a prototype for a new
>> post?
>>
>> ## Background
>>
>> I've used Rcpp modules for several projects where in-place modification
>> was required for performance reasons. I like the interface - it encourages
>> clean code, and yields a nice mix of performance and encapsulation.
>>
>> In the past, the lack of serialization has been a minor annoyance.
>> Honestly, it's not something I need, but I dislike having invalid objects
>> in the work-space after a quit/restart. I've spent a little time thinking
>> about work-arounds, which essentially boil down to moving back and forth
>> from an R list object.
>>
>> Looking towards the future, I also looked at the recent Rcpp dev history.
>> It looks like modules has had some maintenance issues - for example, the
>> last edits there (i..e, PR 454) were reverted due to Windows toolchain
>> issues (i.e., https://github.com/RcppCore/Rcpp/issues/463).  From my
>> outside perspective, it appears that the modules code is A) hard, and B)
>> not a current dev priority.
>>
>> ## A possible alternative: RefClass
>>
>> I'm able to achieve similar behavior (in-place modification using named
>> methods, relatively tidy code) using a combination of R RefClasses and Rcpp
>> attributes. This solves the issue of serialization, and yields reasonably
>> clean code. This has the added benefit of allowing easy mixing of R and C++
>> code in class methods.
>>
>> From a user perspective, RefClass methods are a nice place for Rcpp
>> functions that modify args in-place, since RefClass implies side-effects.
>> And, in terms of style, if all C++ method functions return void, and have
>> const-correct arglists, then the C++ function signatures provide something
>> of a interface spec.
>>
>> Minimal example:
>> https://gist.github.com/helmingstay/17d5d9f241c4170a29d1681db0111065
>>
>>
>> ## Summary of observations:
>>
>> * RefClass + attributes achieves similar outcomes to Rcpp modules, with
>> somewhat better support (serialization, documentation, future?).
>>
>> * Unique to Rcpp modules is the ability to auto-magically generate
>> RefClass-like R bindings for existing C++ class-based code.
>>
>> * For "mere mortals", Rcpp modules now look less attractive for routine
>> use, given available alternatives (i.e. for anything but binding
>> auto-generation)
>>
>>
>> ## Questions:
>>
>> A) Any obvious problems with the above observations?
>>
>> B) Are there any *gotchas* with using Rcpp "modify-in-place" functions
>> inside RefClass methods?
>>
>> C) Is anyone else doing this? Any suggested improvements on the above?
>>
>> Thanks much,
>> Christian Gunning
>> --
>> A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
>>
>> ___
>> Rcpp-devel mailing list
>> Rcpp-devel@lists.r-forge.r-project.org
>> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>>
>
>


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] RFC: Rcpp modules vs. RefClass

2016-11-29 Thread Christian Gunning
All,
Thanks for the comments, much appreciated.
To summarize what I'm hearing:

A) No major problems with the described approach
B) Not much evidence for previous use of this approach

On Tue, Nov 29, 2016 at 12:02 PM, Kevin Ushey  wrote:

> To be brief -- Rcpp modules are effectively in maintenance mode at this
> point; we don't plan to extend / improve modules beyond resolving issues if
> and when they come up.
>

Thanks, that answers one big question.


> We did get to the bottom of the posted issue
>

Yes, I realize that.  My point was that PR 454 remains un-merged, meaning
that the last attempted modules code work was ultimately unfruitful. It can
be challenging for end-users to distinguish between projects / code that is
"fully functional but no longer under active development" (ok) from
directions that code that is "unofficially deprecated".


> I'm not quite sure what the parallel between reference classes and modules
> are here
>

For a *user*, the resulting behavior is very similar.

One big point is Rcpp's by-reference semantics, which has caused perennial
confusion for users coming from a purely R background.  Of course,
by-reference semantics of Rcpp provides a big potential speed-up, but
yields R functions that commonly confuse new users. And yes, both Rcpp
functions and RefClasses are *labeled* with strongly worded warnings.
Still, RefClasses introduce novel R style & semantics. I strongly suspect
users are less likely to be surprised when "the_obj" is modified in-place
by a call to "the_obj$rcpp_add(1)" [RefClass, Rcpp modules]  versus
"rcpp_add(the_obj, 1)" [Rcpp attributes, non-const args].


>
> In sum, I think Rcpp modules are more geared towards developers who are
> primarily C++ programmers who just want a super-simple way to expose a C++
> class to R;
>

As a point of reference, I *literally* learned Cpp OO to use Rcpp modules
(thanks Romain!). This was quite a while ago, and I don't think Rcpp
attributes were around yet. Also, R RefClasses were still new, and no one
was talking about them. I really *liked* the Rcpp modules interface, but I
still don't really understand it. As far as I can tell, the approach I
describe here allows me to achieve the same end-goal as Rcpp modules with a
similar amount of effort using tools under active development.

The broader question of "best practices" remains - the Rcpp docs have
expanded considerably over the years (it even has a book!). A number of
great vignettes describing many "best practices" - in particular, I found a
recent re-read of the attributes vignette to be *very* helpful. I didn't
see much discussion of my particular question of how best to fit these
parts together. If I'm the only one interested in this, so be it :)

best,
Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] RFC: Rcpp modules vs. RefClass

2016-11-28 Thread Christian Gunning
Dear List,

The following is a general request for advice / comment on modern Rcpp
development best-practices for package & class development. I looked over
the Rcpp gallery, and didn't see anything obvious that answers my
questions  - perhaps this discussion could serve as a prototype for a new
post?

## Background

I've used Rcpp modules for several projects where in-place modification was
required for performance reasons. I like the interface - it encourages
clean code, and yields a nice mix of performance and encapsulation.

In the past, the lack of serialization has been a minor annoyance.
Honestly, it's not something I need, but I dislike having invalid objects
in the work-space after a quit/restart. I've spent a little time thinking
about work-arounds, which essentially boil down to moving back and forth
from an R list object.

Looking towards the future, I also looked at the recent Rcpp dev history.
It looks like modules has had some maintenance issues - for example, the
last edits there (i..e, PR 454) were reverted due to Windows toolchain
issues (i.e., https://github.com/RcppCore/Rcpp/issues/463).  From my
outside perspective, it appears that the modules code is A) hard, and B)
not a current dev priority.

## A possible alternative: RefClass

I'm able to achieve similar behavior (in-place modification using named
methods, relatively tidy code) using a combination of R RefClasses and Rcpp
attributes. This solves the issue of serialization, and yields reasonably
clean code. This has the added benefit of allowing easy mixing of R and C++
code in class methods.

>From a user perspective, RefClass methods are a nice place for Rcpp
functions that modify args in-place, since RefClass implies side-effects.
And, in terms of style, if all C++ method functions return void, and have
const-correct arglists, then the C++ function signatures provide something
of a interface spec.

Minimal example:
https://gist.github.com/helmingstay/17d5d9f241c4170a29d1681db0111065


## Summary of observations:

* RefClass + attributes achieves similar outcomes to Rcpp modules, with
somewhat better support (serialization, documentation, future?).

* Unique to Rcpp modules is the ability to auto-magically generate
RefClass-like R bindings for existing C++ class-based code.

* For "mere mortals", Rcpp modules now look less attractive for routine
use, given available alternatives (i.e. for anything but binding
auto-generation)


## Questions:

A) Any obvious problems with the above observations?

B) Are there any *gotchas* with using Rcpp "modify-in-place" functions
inside RefClass methods?

C) Is anyone else doing this? Any suggested improvements on the above?

Thanks much,
Christian Gunning
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp-devel Digest, Vol 85, Issue 8

2016-11-23 Thread Christian Gunning
On Wed, Nov 23, 2016 at 4:00 AM,
rcpp-devel-requ...@lists.r-forge.r-project.org <
rcpp-devel-requ...@lists.r-forge.r-project.org> wrote:

>
> Using the amazingly useful
>
> http://gallery.rcpp.org/articles/using-the-Rcpp-based-
> sample-implementation/
>
> I get a bunch of compiler warnings (copied in full below); the crux seems
> to be
>
> typename T1::elem_type = double; arma::uword = unsigned int]? is deprecated
>
>I could dig in and try to fix this myself but feel like it might be a
> deep rabbit hole for me ...  This is not critical, but it would
> certainly be nice to have my code compile clean.
>
>   (I'm happy to report this elsewhere if there is a more appropriate
> venue.)


Ben,

Good to hear it's been useful. I'll plan to take a look and clean it up
this weekend.

best,
-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Integrating C-library libmseed to R

2016-07-13 Thread Christian Gunning
On 12 July 2016 at 19:33, Leo Leo wrote:

> | Dear Rcpp_devel enthusiats,
> |
> | May I ask you for exploiting your potential? I am working on a package to
> | handle seismic data (https://github.com/coLeo Leo <
> behelfsadre...@googlemail.com>
> Cffeemuggler/eseis ).
> |
> | A key task is to be able to read and write the so called miniseed
> format. There
> | is a C-library for this job (
> https://seiscode.iris.washington.edu/projects/
> | libmseed/files).
> |
> | What would be needed to implement this library to my package? The goal
> would be
> | to have functions like read_mseed(file, ...) and write_mseed(data, file,
> ...).
> | According to the library documentation the functions that do this are
> | ms_readmsr(3) and ms_readtraces(3) as well as mst_pack(3) and
> mst_writemseed
> | (3).
>
> The very simplest option is probably to just copy the content of the
> library
> itself -- ie the *.c (or *.cpp) and *h files -- to your package's src/
> directory.  That way the content is present and can be used by your add-on
> functions.
>
> A slightly better and more involved option is to keep it in a subdirectory
> and have it built, say during configure.  You package then points to that
> (static) library from its src/Makevars.
>
> There are other options. But all this somehow requires you to know a little
> bit about library building, which then becomes OS-dependent as this is
> different between Linux and OS X, not to mention Windows.
>
> --
> A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
>

To add to Dirk's comments, a few questions to ask yourself:

* What is the license of libmseed?  Do you have permission to incorporate
it directly into your package?
* What is the license of your package?  Is it compatible with the license
of libmseed for incorporation?

* What are your platform requirements?  Do you want as broad an audience as
possible, or is this a project for a specific group that needs support on a
particular platform?  (As Dirk suggests, POSIX is the low-hanging fruit
here.  Also, have physical access to the platforms you plan to support is
very helpful).

* Minor language clarification: your original question asks "what would be
needed to implement" .  In software, the term "implement" commonly implies
"write anew".  My reading of your question is that you want to write as
little new code as possible, and re-use pre-existing code - is this
correct?  Again, the ability to directly incorporate other library code
into your package depends in some part on the licenses of both projects.

-hth
Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] rpois returns double?

2015-04-25 Thread Christian Gunning
Thanks all for the details, I appreciate the helpful answers!
-Christian

On Sat, Apr 25, 2015 at 12:46 PM, William Dunlap wdun...@tibco.com wrote:

  Note that the R function rpois() always returns an integer vector and
 thus
 commonly runs into problems when lambda is near or above 2^31 (the
 smallest positive integral double that cannot represented as a 32-bit
 signed
 integer).

   set.seed(1)
  rpois(10, 2^31)
  [1] 2147454617 NA NA NA 2147412285 NA
   NA
  [8] NA 2147469496 2147446621
 Warning message:
 In rpois(10, 2^31) : NAs produced
  storage.mode(.Last.value)
 [1] integer



  Bill Dunlap
 TIBCO Software
 wdunlap tibco.com

 On Sat, Apr 25, 2015 at 9:33 AM, Michael Weylandt 
 michael.weyla...@gmail.com wrote:


  On Apr 24, 2015, at 23:58, Christian Gunning x...@unm.edu wrote:

   Quick question, mainly out of curiousity.  I get that Rcpp uses the R
 api on the backend, and in the R api, R::rpois returns a double (and
 Rcpp::rpois returns NumericVector). The R C code doesn't offer much in the
 way of explanation of why double is returned, but always returns a floor() (
 https://svn.r-project.org/R/trunk/src/nmath/rpois.c).

  It seems to me that, in this case, upstream could (should?) cast to
 int.   Since it doesn't, downstream users like Rcpp and me must choose
 whether to follow upstream convention or to cast.  In this case, is the
 best practice to cast-to-int right away, or to follow along and just use
 doubles for everything?

  I've run into this recently with other RNG code that returns doubles
 for everything, and I'm wondering if there's an obvious tradeoff that I'm
 missing, like speed versus type-correctness?  If anyone has any insights,
 I'd love to hear them.


  The set of integers exactly representable by a double is a superset of
 those which can represented by a 32bit int.


 http://stackoverflow.com/questions/759201/representing-integers-in-doubles

 ___
 Rcpp-devel mailing list
 Rcpp-devel@lists.r-forge.r-project.org
 https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel





-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] rpois returns double?

2015-04-24 Thread Christian Gunning
Quick question, mainly out of curiousity.  I get that Rcpp uses the R api
on the backend, and in the R api, R::rpois returns a double (and
Rcpp::rpois returns NumericVector). The R C code doesn't offer much in the
way of explanation of why double is returned, but always returns a floor() (
https://svn.r-project.org/R/trunk/src/nmath/rpois.c).

It seems to me that, in this case, upstream could (should?) cast to int.
Since it doesn't, downstream users like Rcpp and me must choose whether to
follow upstream convention or to cast.  In this case, is the best
practice to cast-to-int right away, or to follow along and just use
doubles for everything?

I've run into this recently with other RNG code that returns doubles for
everything, and I'm wondering if there's an obvious tradeoff that I'm
missing, like speed versus type-correctness?  If anyone has any insights,
I'd love to hear them.

thanks,
Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] R.e. Using Rcpp and MATLAB MAT-File API to Read MAT Files

2015-03-25 Thread Christian Gunning
Can you provide a link to the mat.h file referenced in the source
(which I assume is the same as the API mentioned below)?

Also, see Dirk's comments about compilers here:
http://stackoverflow.com/questions/10723165/using-visual-c-with-r
and here:
dirk.eddelbuettel.com/code/rcpp/Rcpp-FAQ.pdf

Best,
Christian

 I'm trying to use the MATLAB Mat-File API to read data from MAT files into
 R. (I've tried using the R.matlab package, but the matrices I'm loading can
 be very large, and that method was too slow. In addition, some of the files
 I'm loading are v7.3 MAT files, which are not supported by the package.) I
 wrote the following simple function to start testing. It works fine if I
 compile without the Rcpp parts in Visual Studio (i.e. I can call matOpen
 and get a nonzero pointer), but when I run in R it crashes my R session
 without displaying Test.

 #include Rcpp.h
 #include mat.h

 using namespace Rcpp;

 // [[Rcpp::export]]
 NumericVector rcpp_mat_load() {

 MATFile* mf = matOpen(z:/temp/test.mat, r);
 printf(Test\n);
 double val = 10;
 NumericVector y = NumericVector::create(val);
 return y;
 }

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] R.e. A RcppArmadillo based program cannot compile under Windows and RStudio

2015-03-11 Thread Christian Gunning
No problem.
One more piece of list etiquette: when writing follow-up emails,
please CC the list in your response to individuals who have directly
answered you.  This prevents questions from being (privately) answered
repeatedly.

Two questions:

* Can you confirm that you do, in fact, have RcppArmadillo installed
by a call to library(RcppArmadillo)?

* You've looked over the Rcpp FAQ carefully?  Compilation on windows
is, er, different.
http://dirk.eddelbuettel.com/code/rcpp/Rcpp-FAQ.pdf

I don't have a windows machine, so I'm not able to reproduce your
problem.  Perhaps someone else can use the detailed information that
you've provided to identify the problem with your included example.

Best,
Christian

On Wed, Mar 11, 2015 at 9:38 AM, 烧锅炉的天使 pdslimo...@qq.com wrote:
 I am sorry for that not  include a short  informative title in my email.‍

 A RcppArmadillo based program cannot compile under Windows and RStudio ‍

 In RStudio
 ##
 Rcpp::sourceCpp('armaLU.cpp',verbose = TRUE)

 Generated extern C functions
 


 #include Rcpp.h
 // LU
 int LU();
 RcppExport SEXP sourceCpp_75578_LU() {
 BEGIN_RCPP
 Rcpp::RObject __result;
 Rcpp::RNGScope __rngScope;
 __result = Rcpp::wrap(LU());
 return __result;
 END_RCPP
 }

 Generated R functions
 ---

 `.sourceCpp_75578_DLLInfo` -
 dyn.load('C:/Users/lxh/AppData/Local/Temp/RtmporLzPl/sourcecpp_19a8798d5d84/sourceCpp_59453.dll')

 LU - Rcpp:::sourceCppFunction(function() {}, FALSE,
 `.sourceCpp_75578_DLLInfo`, 'sourceCpp_75578_LU')

 rm(`.sourceCpp_75578_DLLInfo`)

 Building shared library
 

 DIR: C:/Users/lxh/AppData/Local/Temp/RtmporLzPl/sourcecpp_19a8798d5d84

 C:/R-31~1.3/bin/i386/R CMD SHLIB -o sourceCpp_59453.dll  armaLU.cpp
 g++ -m32 -IC:/R-31~1.3/include -DNDEBUG
 -IC:/R-3.1.3/library/Rcpp/include
 -IC:/R-3.1.3/library/RcppArmadillo/include -ID:/Rstudio
 -Id:/RCompile/CRANpkg/extralibs64/local/include -O2 -Wall
 -mtune=core2 -c armaLU.cpp -o armaLU.o
 g++ -m32 -shared -s -static-libgcc -o sourceCpp_59453.dll tmp.def armaLU.o
 -LC:/R-31~1.3/bin/i386 -lRlapack -LC:/R-31~1.3/bin/i386 -lRblas -lgfortran
 -Ld:/RCompile/CRANpkg/extralibs64/local/lib/i386
 -Ld:/RCompile/CRANpkg/extralibs64/local/lib -LC:/R-31~1.3/bin/i386 -lR
 Error in inDL(x, as.logical(local), as.logical(now), ...) :
   unable to load shared object
 'C:/Users/lxh/AppData/Local/Temp/RtmporLzPl/sourcecpp_19a8798d5d84/sourceCpp_59453.dll':
   LoadLibrary failure:  The specified module could not be found‍。‍

 #
 But the default Rcpp template can compile with Rcpp without problem , the
 RcppEigen program can compile without any error also.‍


 -- 原始邮件 --
 发件人: Christian Gunning;x...@unm.edu;
 发送时间: 2015年3月11日(星期三) 上午6:44
 收件人:
 rcpp-devel@lists.r-forge.r-project.orgrcpp-devel@lists.r-forge.r-project.org;
 主题: [Rcpp-devel] ??lxh???

 lxh,

 A quick word r.e. list etiquette -- you can help others process your
 request by including in your email a short  informative title, and a
 one or two sentence description of what you're trying to accomplish.

 I'm not on windows, so all I can say is that it works for me. Have you
 verified that RcppArmadillo installed without error?

 The other thing you can try is use the following to observe the
 details of the compilation process:

 sourceCpp('armaPRI.cpp', verbose=TRUE)

 hth,
 Christian

 Date: Tue, 10 Mar 2015 21:49:18 +0800 (CST)
 From: lxh zjgs...@163.com
 To: rcpp-devel@lists.r-forge.r-project.org
 Subject: [Rcpp-devel] ??lxh???
 Message-ID: 1aef304a.18ae8.14c03f25f44.coremail.zjgs...@163.com
 Content-Type: text/plain; charset=gbk

 Hi,

 #
 Rcpp::sourceCpp('armaPRI.cpp')

 Error in inDL(x, as.logical(local), as.logical(now), ...) :
 unable to load shared object
 'C:/Users/lxh/AppData/Local/Temp/RtmpeenRl8/sourcecpp_27081dce2d4b/sourceCpp_77404.dll':
 LoadLibrary failure: The specified module could not be found.
 I get this when trying to use RcppArmadillo with my princomp computation
 program(armaPRI.cpp). I am sure that i have missed something which results
 above error message, but i have no idea about that.
 By the way, the program eigentrans.cpp which uses the RcppEigen package
 works well.

 The Rtools path and the R bin path are already added to my Enviroment
 Path:
 #

 c:\Rtools\gcc-4.6.3\bin;c:\Rtools\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\MiKTeX
 2.9\miktex\bin\;C:\Python27;C:\Python27\DLLs;C:\Python27\Scripts;C:\Program
 Files\ATI
 Technologies\ATI.ACE\Core-Static;C:\TDM-GCC-32\bin;C:\R-3.1.3\bin;D:\Program
 Files\RStudio\bin\pandoc

[Rcpp-devel] ??lxh???

2015-03-10 Thread Christian Gunning
lxh,

A quick word r.e. list etiquette -- you can help others process your
request by including in your email a short  informative title, and a
one or two sentence description of what you're trying to accomplish.

I'm not on windows, so all I can say is that it works for me. Have you
verified that RcppArmadillo installed without error?

The other thing you can try is use the following to observe the
details of the compilation process:

sourceCpp('armaPRI.cpp', verbose=TRUE)

hth,
Christian

 Date: Tue, 10 Mar 2015 21:49:18 +0800 (CST)
 From: lxh zjgs...@163.com
 To: rcpp-devel@lists.r-forge.r-project.org
 Subject: [Rcpp-devel] ??lxh???
 Message-ID: 1aef304a.18ae8.14c03f25f44.coremail.zjgs...@163.com
 Content-Type: text/plain; charset=gbk

 Hi,

 #
 Rcpp::sourceCpp('armaPRI.cpp')

 Error in inDL(x, as.logical(local), as.logical(now), ...) :
 unable to load shared object 
 'C:/Users/lxh/AppData/Local/Temp/RtmpeenRl8/sourcecpp_27081dce2d4b/sourceCpp_77404.dll':
 LoadLibrary failure: The specified module could not be found.
 I get this when trying to use RcppArmadillo with my princomp computation 
 program(armaPRI.cpp). I am sure that i have missed something which results 
 above error message, but i have no idea about that.
 By the way, the program eigentrans.cpp which uses the RcppEigen package works 
 well.

 The Rtools path and the R bin path are already added to my Enviroment Path:
 #
 c:\Rtools\gcc-4.6.3\bin;c:\Rtools\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\MiKTeX
  2.9\miktex\bin\;C:\Python27;C:\Python27\DLLs;C:\Python27\Scripts;C:\Program 
 Files\ATI 
 Technologies\ATI.ACE\Core-Static;C:\TDM-GCC-32\bin;C:\R-3.1.3\bin;D:\Program 
 Files\RStudio\bin\pandoc
 ###
 armaPRI.cpp
 ###
 // [[Rcpp::depends(RcppArmadillo)]]
 #include RcppArmadillo.h
 using namespace arma;
 using namespace Rcpp;
 // [[Rcpp::export]]
 int PRINCOMP(){
 mat A = randumat(5,4);
 mat coeff;
 mat score;
 vec latent;
 vec tsquared;
 princomp(coeff, score, latent, tsquared, A);
 Rcoutcoeffendl;
 return 0;
 }
 #

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp-devel Digest, Vol 64, Issue 16

2015-02-26 Thread Christian Gunning
I thought I'd step in and grab this one :)

In general, it's certainly a reasonable point that there is a trade-off
to be made -- user-friendliness against the potential extra copies (not
sure whether this has ever been measured -- as in counting the cases of
`clone`-less existing code-bases where this was the actual performance
bottleneck).

Short answer is yes, benefits are well documented via the list.  In
short, the relative effect size grows with the size of the object
cloned, and the number of times cloned.  As you might expect.  It's
pretty easy to cook up a trivial example to test this for yourself -
try summing a 1e3*1e3 matrix 1e4 times, for example.

That being said, as for the what to do by default advice, for anyone
finding themselves in a need to `clone` -- `std::vectordouble` seems
like the safer, better documented option.

R.e. default options, do things work as you expect if you follow
const-correctness?
http://isocpp.org/wiki/faq/const-correctness
It seems like one option is to tell the compiler what you want *not*
changed (forcing you to clone anything that should be changed).  This
is a genuine question.

To answer your implied concerns:

* Yes, that ship has sailed.  Many packages use Rcpp, and it's been
around for years.

* Rcpp is much *easier* than writing C code for R.  There's a minimum
expectation of developer experience for Rcpp users.  That minimum
level is way *lower* than alternate high-performance R/C integration
methods, but some google-fu / gmane searching is not an unreasonable
request.

* Rcpp is the work of a relatively small number of individuals working
on a mostly (all?) volunteer basis.  If you don't like the tools,
you're welcome to make something else.
http://xkcd.com/927/

* Yes, the in-R documentation of is sometimes lacking (e.g.,
?Rcpp::NumericVector).  The mailing list support, however, is
generally very responsive, and is considered congenial compared to
R-help.  In addition, there are a number of published manuscripts,
vignettes, unit-tests, and a gallery.  Again, you're welcome to help
organize this, write help manuals for R, etc.

hth,
-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Using an Rcpp module package in an R Reference Class

2014-10-14 Thread Christian Gunning
Dear all,

I have a working package that uses the Rcpp module mechanism (my
RaggedArray project, as per previous discussion), and a working pure-R
reference class (RefClass) that does computation on a list-based
ragged array.  I'm unsure on how to integrate the RaggedArray module
into the RefClass. I have a simple example working, but I'm getting
inscrutable expecting an external pointer errors every time I try
something non-trivial. Is there a canonical way to do this, or a good
example floating about?

I've looked both at direct inheritance:
## but how to initialize the base class?
wormSim - setRefClass(wormSim,
contains='RaggedArray', ## parent class
fields=c( CF=numeric)
)

and at adding a field:
##
wormSim - setRefClass(wormSim,
fields=c( CF=numeric, LL = RaggedArray)
)

On a seemingly related note, I'm having trouble figuring out the
details of exporting / exposing an Rcpp module to R via standard
tools.  I've found the following related items, but I'm still confused
about how they're related.  Are any of these S4-related rather than
RefClass related?  Any pointers/docs/examples would be appreciated.

* Rcpp: RCPP_EXPOSED_CLASS_NODECL(RaggedArray)
* Rcpp: setRcppClass(RaggedArray)
* roxygen2/NAMESPACE:  @exportClass RaggedArray

Thanks,
Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Using an Rcpp module package in an R Reference Class

2014-10-14 Thread Christian Gunning
On Tue, Oct 14, 2014 at 9:19 AM, Dr Gregory Jefferis
jeffe...@mrc-lmb.cam.ac.uk wrote:

 * Rcpp: RCPP_EXPOSED_CLASS_NODECL(RaggedArray)
 * Rcpp: setRcppClass(RaggedArray)
 * roxygen2/NAMESPACE:  @exportClass RaggedArray

 I'm not sure if the exact issue here, but you could look at this package
 that I wrote:

 https://github.com/jefferis/nabor

 and in particular

 https://github.com/jefferis/nabor/blob/master/R/WKNNClasses.R
 https://github.com/jefferis/nabor/blob/master/src/WKNN.cpp


Yeah, I found your package and used it as a prototype to fix a few
things, but I'm honestly still short on understanding.  Here's my
reading of the above 3 *s:

* I've read ?setRcppClass, and looked at the definition (e.g.
Rcpp::setRcppClass) and I'm not clear on when this is required, and
whether its RefClass or S4.

* The best explanation of the RCPP_EXPOSED_CLASS macro I found was
here: 
http://romainfrancois.blog.free.fr/index.php?post/2012/10/25/Rcpp-modules-more-flexible.
My understanding is that this only involves the C++ side, and is
totally unrelated to a pure-R reference class using an Rcpp module
object and its methods.

* The @exportClassses directive creates an exportClasses entry in
NAMESPACE.  Looking at Writing R extensions, it looks like this is
particular to S4 classses.  In fact, I can't find mention of reference
classes in Writing R extensions.  So, I'm murky on what calling
exportClasses(myRcppModule) actually does, or how it works.

Did I miss anything here?
Thanks!
Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Trouble with package unit test and sourceCpp()

2014-09-27 Thread Christian Gunning
Thanks.  I ended up using RcppParallel as my guide and finally got
everything working.

On Fri, Sep 26, 2014 at 5:27 AM, Dirk Eddelbuettel e...@debian.org wrote:

 Christian,

 On 26 September 2014 at 03:51, Christian Gunning wrote:
 | This is a bit of a late response - I finally got back to this today.
 | I should have clarified that I'm using testthat and devtools.
 [...]
 | Any thoughts?

 No as I use RUnit.

 I'd go to CRAN, look at the set of packages using Rcpp and the set of
 packages using testthat, and examine the intersection.  From the top of my
 head at least Renaud's RcppOctave uses testthat.

 Dirk

 --
 http://dirk.eddelbuettel.com | @eddelbuettel | e...@debian.org



-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Trouble with package unit test and sourceCpp()

2014-09-26 Thread Christian Gunning
Dirk,

This is a bit of a late response - I finally got back to this today.
I should have clarified that I'm using testthat and devtools.

I used the examples in RcppArmadillo to fix the path for compiling
code in tests, which is now working.  But I'm still running into what
appears to be the issue addressed here:
https://github.com/hadley/testthat/issues/144

test('RaggedArray') works fine, but R CMD check RaggedArray fails on
those same tests with the mysterious cannot open file 'startup.Rs'
error.  Output from R CMD check RaggedArray:

* checking examples ... OK
* checking for unstated dependencies in tests ... OK
* checking tests ...
  Running ‘test_all.R’
 ERROR
Running the tests in ‘tests/test_all.R’ failed.
Last 13 lines of output:
  In file(filename, r, encoding = encoding) :
cannot open file 'startup.Rs': No such file or directory
  Execution halted

  Error in sourceCpp(system.file(tests, userFun.cpp, package =
RaggedArray)) :
Error 1 occurred building shared library.
  Calls: test_package ... source_dir - lapply - FUN - eval - eval
- sourceCpp

  WARNING: The tools required to build C++ code for R were not found.
  Please install GNU development tools including a C++ compiler.
  Execution halted

Any thoughts?
-Christian

On Wed, Sep 3, 2014 at 4:23 AM, Dirk Eddelbuettel e...@debian.org wrote:

 On 2 September 2014 at 20:42, Christian Gunning wrote:
 | I'm working on a package that includes a unit test that calls
 | sourceCpp() to test a particular use-case.
 [...]
 | My question is whether there's a sane workaround, or if I should give
 | up on these tests. Alternately, is there a cleaner way for a user to
 | supply hand-written C++ functions?  Using sourceCpp() allows the user
 | to locally manage custom functions without building a package, and
 | ensures that user edits aren't overwritten by a package upgrade.

 We do that in Rcpp itself, as well as in RcppArmadillo, RcppEigen, ...
 by using RUnit.  You should be able to use any of the other fine unit test
 packages too.

 Part of the logic is farmed out to a little helper function.  From the last
 one I worked on / added a few weeks ago for RcppArmadillo, ie
 rcpparmadillo/inst/unitTests/runit.sparse.R



 .runThisTest - suppressMessages(require(Matrix))

 if (.runThisTest) {

 .setUp - RcppArmadillo:::unit_test_setup(sparse.cpp)

 #
 # tests follow below
 #
 }


 and unit_test_setup() mostly deals with trying to get the path right:



 unit_test_setup - function(file = NULL, packages = NULL) {
 function(){
 if (!is.null(packages)) {
 for (p in packages) {
 suppressMessages(require(p, character.only = TRUE))
 }
 }
 if (!is.null(file)) {
 if (exists(pathRcppArmadilloTests)) {
 sourceCpp(file.path(get(pathRcppArmadilloTests), cpp, 
 file))
 } else if (file.exists(file.path(cpp, file))) {
 sourceCpp(file.path( cpp, file))
 } else {
 sourceCpp(system.file(unitTests, cpp, file, 
 package=RcppArmadillo))
 }
 }
 }
 }


 The cpp files themselves are then in cpp/ which is inside
 inst/unitTests/cpp.

 Dirk


 --
 http://dirk.eddelbuettel.com | @eddelbuettel | e...@debian.org



-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Pass an Rcpp module object to a method belonging to another module from R?

2014-09-09 Thread Christian Gunning
 Below is a simplified example, with question marks where I'm not sure what
 to do. I've tried accepting a pointer to A, playing with using XPtrs, and a
 bunch of things which made far less sense, but so far no luck.

As an addendum to others' comments...

I've been working on a kinda-sorta similar problem: passing
user-supplied C++ worker functions to a module's method.  Not sure if
it helps, but it's a full example of passing XPtrs from C++ to R back
to a module's method, where it's called in C++:
https://code.google.com/p/unm-r-programming/source/browse/#git%2FRaggedArray

* In ./src/helpers.cpp, sapply_master(infun, cppfun=true) takes an R
function infun that returns an XPtr to a function that does something.
sapply_master pulls the XPtr, dereferences it to the C++ function, and
calls that function on a class member.
* In ./inst/tests/userFun.cpp are the user-specified worker functions,
and the associated XPtr-exporting wrapper functions that are passed to
sapply_master().

Incidentally, my plan is for this to be a gallery post in the not too
distant future.
-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Trouble with package unit test and sourceCpp()

2014-09-02 Thread Christian Gunning
Dear all,

I'm working on a package that includes a unit test that calls
sourceCpp() to test a particular use-case.  As in [1], test(.) works
swimmingly, but check() and vanilla R CMD check fail with the
ominous error cannot open file 'startup.Rs': No such file or
directory.  If I understand correctly, Dirk and Hadley agree [1] that
this is R's fault,  apparently through the nested R CMD calls [1,
2].  Indeed, sourceCpp() includes calls to both R CMD and setwd(),
while cppFunction() and evalCpp() both call sourceCpp().

I realize that calling sourceCpp() in a package isn't exactly
standard.  The tested use-case is allowing a package user to easily
write custom C++ functions via sourceCpp(userfile.cpp).  These
functions are then passed to a class method and used internally by
dereferencing and evaluating the XPtr. I've provided a working example
of userfile.cpp that a user can copy and extend. Consequently, I
would like some way to test the full process of
write-compile-pass-call.

My question is whether there's a sane workaround, or if I should give
up on these tests. Alternately, is there a cleaner way for a user to
supply hand-written C++ functions?  Using sourceCpp() allows the user
to locally manage custom functions without building a package, and
ensures that user edits aren't overwritten by a package upgrade.

I'm happy to poke, but I'm not sure where to go from here.
Thanks again,
Christian

Refs:
[1] https://github.com/hadley/testthat/issues/144
[2] https://github.com/hadley/devtools/blob/master/R/R.r
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] Rcpp::ListOf.size() returns signed int?

2014-09-01 Thread Christian Gunning
Minor implementation question -
As a learning exercise, I'm working through g++ warnings.  After
reading SO posts r.e. int vs size_t, I've set all variables that hold
or compare object size information to type std::size_t.  This fixes
compiler warnings for Vector.size(), which doxygen shows have return
type
R_len_t.  ListOf.size() appears the odd man out, returning int.  Is
there a reason ListOf.size() returns a (signed) int?

Thanks,
Christian

Ref:
ListOf.size(): 
http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1ListOf.html#a610d059eca87928f6b3ae80dec75f817

Vector.size(): 
http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1Vector.html#a8d003a52136223a30c942a75cf629b0a
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] How to detach a package completely

2014-08-30 Thread Christian Gunning
Have you tried Hadley's devtools package? It probably has the best tools
for auto-reloading packages. On occasion it will jam on me and I have to
restart R, but most times load_all(Hello, recompile=T) should do what you
want.

---Christian

Quote:
Dear everybody
I apologize whether this question has been already answered but I read the
documentation and I surfed the web without solving my issue.

From time to time, I use R to develop my own packages.
For testing purposes, I need frequently
***to detach the previous version and attach a more recent built without
leaving the R session***.

I'm able to do this with the command
detach(name = Hello, unload = TRUE, force = TRUE)
if I include in the source package a
zzz.R file
with the function
.onUnload - function(libpath = NULL)
{
  library.dynam.unload(Hello, libpath)
}
(Hello is the name of the package I used for testing)

However, if Hello links and imports Rcpp (and an import(Rcpp) directive
is included in NAMESPACE) all this stuff does not work, in the sense that
even detaching and building a new version of Hello, the previous one is
attached.
On the other side, if I quit R and I open another session, the last version
of Hello is attached successfully.
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Blog post - optimizing ragged arrays in R and Rcpp

2014-07-03 Thread Christian Gunning
Dear all,

I just posted a short article on ragged arrays in R and Rcpp (it will
also be auto-posted to R-bloggers).  I've tried to be as comprehensive
as possible in discussing the problem background, as well as providing
relevant citations.  I'm curious to hear if anyone else has faced this
problem, and if there are prior solutions that I've overlooked.

http://helmingstay.blogspot.com/2014/07/computational-speed-is-common-complaint.html

Best,
Christian Gunning
University of New Mexico

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Speed up of the data.frame creation in DataFrame.h

2014-06-08 Thread Christian Gunning
 Subject: Re: [Rcpp-devel] Speed up of the data.frame creation in
 DataFrame.h
 Message-ID: 757ef798-6bc6-4150-93cd-b5f23d901...@gmail.com
 Content-Type: text/plain; charset=windows-1252

 The fix I was proposing actually has implications much deeper than I thought. 
 I would need to investigate further and will take no action at this time.

Hello list, long time no see!

Dmitry,
Have you identified any other consequences than what Romain pointed
out?  This information would be useful for the rest of us.

Some key points that I agree with:
 * as per Dirk: this is a nice little piece of sleuthing.  Your
benchmarking shows that the effect is significant.
 * as per your comments: a key intent of Rcpp is allow the user the
freedom to acheive optimization and do their own error checking.
  * as per Romain: let's not break things.

It seems possible address all of these points, perhaps with a
dedicated function, as per your comments.  I can help with this, if
you're interested.

Key question: what is the intended behavior of this function?  E.g.,
throw an exception on length mismatch?  My vote is for a limited
function that deals with a limited number of use cases and provides
reasonable error-checking (e.g. throws exception for input outside
scope), versus a logic-heavy function that handles recycling, for
example.  Does this match your use-case?

-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Sample function(s) for inclusion in RcppArmadillo

2013-04-12 Thread Christian Gunning
Johnathan,

Thanks for formatting this, it looks great.  I've added the case of
without replacement, and a brief discussion of Walker's alias (that
depends on the SVN version of RcppArmadillo, r4296), confirmed that it
works with a local install of jekyll, and pushed it back to your
github repo. Can you deal with it from here?

I think this is long enough for a single post, and that it should get
published whenever the next version of RcppArmadillo comes out.

One minor issue with jekyll or markup (??) that someone else can
hopefully comment on:
The following R code produces a warning that contains a  sign and
leads to an error in the rendered webpage.

## R code
n.elem - 1e3
r.prob - sample(1:n.elem, n.elem, prob = runif(n.elem), replace = T)

Error:
REXML could not parse this XML/HTML:
pre class=output
Warning: Walker's alias method used: results are different from R  2.2.0
/pre


best,
Christian

On Fri, Mar 29, 2013 at 4:42 PM, Dirk Eddelbuettel e...@debian.org wrote:

 On 29 March 2013 at 18:43, Jonathan Olmsted wrote:
 | Yup. Progress was waiting on finalizing behavior of sample().
 |
 | Current status is visible here: https://github.com/olmjo/rcpp-gallery/blob/
 | gh-pages/src/2013-03-19-using-the-Rcpp-based-sample-implementation.Rmd

 Awesome :)

 Will check this later unless I forget.

 Dirk

 --
 Dirk Eddelbuettel | e...@debian.org | http://dirk.eddelbuettel.com





--
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Sample function(s) for inclusion in RcppArmadillo

2013-03-28 Thread Christian Gunning
Dirk,

See attached for minor edits related to Walker Alias method.  Based on
the timing tests from the gallery draft and discussion with Johnathan,
we decided it was a bad idea to include code that deviates from R's
behavior, and is slower than R to boot.  Thus, the C++ sample now
throws an informative error under the appropriate conditions.  I
updated the unitTests accordingly (and cleaned them up a bit).

Incidentally, there's now a stub in place for Walker Alias method
sample function, as well as an associated unitTest that's now
commented out.
-Christian


walker.throw.diff
Description: Binary data
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Sample function(s) for inclusion in RcppArmadillo

2013-03-11 Thread Christian Gunning
Dirk (and list for reference),

On Sun, Mar 10, 2013 at 6:16 PM, Dirk Eddelbuettel e...@debian.org wrote:

 Christian, Jonathan,

 On 8 March 2013 at 20:42, Christian Gunning wrote:
 | With some helpful prodding from Jonathan, I sat down with the sample
 | code today.  I moved sample.h to add-ons as per our previous
 | conversation and updated runit.sample.R accordingly.

 It looks great! Had some time to glance at it on a plance back from NYC but
 didn't yet write any testers.  R CMD check is very clean --- great
 submission.  MUST DO follow-up post on gallerty.rcpp.org !!

Not sure what you mean by testers here.

Johnathan indicated interest in working on the gallery post.

 I just moved the copyright dates to '2012 - 2013' as you had been at this,
 and removed one or two commented out lines.  Will commit soon.

Great, thanks.


 I don't like add-ons/ all that much as it doesn't show (Rcpp)Armadillo.
 How about any one of these:

 inst/include/RcppArmadilloXtra/sample.h
 inst/include/RcppArmadillo/extra/sample.h
 inst/include/RcppArmadillo/add-on/sample.h
 inst/include/RcppArmadillo/extensions/sample.h
 inst/include/RcppArmadillo/apps/sample.h
 inst/include/RcppArmadillo/applications/sample.h
 [...]

I vote for extensions.


 Also, should Jonathan get co-credit or not?  I'll let you guys work that out.

The writing here is all mine.  Johnathan prompted me to finish :)

 Lastly, the regression test takes 'too long' as CRAN limits us to ~ 60 sec
 per package.  I'll probably do what Romain had for Rcpp and regroup the tree
 or four cpp functions into a single source file that we can read / compile
 with a single sourceCpp() call.

Got it, thanks.

 | I also chased down the bug that was causing failure when probabilities
 | were included.  It was a small and significant misreading of the
 | original algorithm on my part that took me a while to spot.  Glad this
 | is done!
 |
 | I haven't kept up with the list (planning to do that this month), and
 | a lot of this conversation took place off-list, so I'm sending this
 | privately.  Obviously, share as you will.

 List is almost always better.  Even is nobody responds...

 Dirk

 | best,
 | Christian
 |
 | On Wed, Jan 30, 2013 at 7:54 AM, Dirk Eddelbuettel e...@debian.org wrote:
 | 
 |  On 30 January 2013 at 02:18, Christian Gunning wrote:
 |  | Thanks for the note.
 |  |
 |  | I too got swamped before I could really look at this (major office 
 move, I've
 |  | postponed reading list).
 |  | The short story is that I thought it would (A) *just work*, and barring 
 that
 |  | (B) I hoped it would be a quick
 |  | fix to make it *just work*.  If it doesn't *just work* (identically to 
 R), then
 |  | (C) I need to verify that the algorithms do what they say.  I'm not 
 entirely
 |  | comfortable (C), nor have I totally ruled out (B).  Anyway, I'll plan 
 to poke
 |  | at this in the next 2 or 3 weeks.
 | 
 |  Let's keep at this so that it can be in the next RcppArmadillo.  We can 
 make
 |  (at the minimum) an Rcpp Gallery post out of this, maybe even a short 
 writeup
 |  somewhere else?
 | 
 |  Dirk
 | 
 |  --
 |  Dirk Eddelbuettel | e...@debian.org | http://dirk.eddelbuettel.com
 | 
 | 
 |
 |
 |
 | --
 | A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
 | xuntyped binary data, working-sample [Click mouse-2 to save to a file]

 --
 Dirk Eddelbuettel | e...@debian.org | http://dirk.eddelbuettel.com





-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] S3 methods with cppFunction/sourceCpp

2012-12-27 Thread Christian Gunning
I just realized that cppFunction can't natively build S3 functions, since
 fun.class isn't valid C++ function name.  I'm wondering if adding and
 S3class argument (default value = FALSE, otherwise class name as
 character) to cppFunction makes sense -- all that's needed is
 appending the class name to the function name, correct?  The downside,
as I see it, is that it's not so simple for sourceCpp/attributes (at
least I don't understand them).

Obviously, this is a minor issue. Is anyone else likely to hit this?

best,
Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Sample function(s) for inclusion in RcppArmadillo

2012-12-25 Thread Christian Gunning
I'm working on writing runit tests for the previously-discussed
sample, and I just hit my competence threshold dealing with
inst/include.
As discussed, the (overloaded) sample() functions are to be called
only from user C++ code and are thus not exposed to R.
This means that the function definitions should go in inst/include, correct?

I don't really know what I'm doing here.  If someone could recommend a
good reference for namespace control, headers, and R-package specific
issues I'd be grateful.   Details follow:

I'm trying to get the following test function to use RcppArmadillo's
definition of sample, and the compiler never finds it:
require(Rcpp)
cppFunction( code='
IntegerVector sample_int_noprob( IntegerVector x, int size,
bool replace) {
RNGScope scope;
IntegerVector ret = RcppArmadillo::sample(x, size, replace);
return ret;
}',
depends='RcppArmadillo'
)

I tried placing the definition of sample in
RcppArmadillo/inst/include/sample.h.
using namespace Rcpp;
template class T
T sample(const T x, const int size, const bool replace,
NumericVector prob_ = NumericVector(0) ) {
// Templated sample -- should work on any Rcpp Vector
 ...
}

I've tried to use RcppArmadilloWrap.h as an example, using:
namespace Rcpp{
namespace RcppArmadillo{
...
}
}

best,
Christian


On Thu, Nov 15, 2012 at 5:35 AM, Dirk Eddelbuettel e...@debian.org wrote:

 On 15 November 2012 at 04:00, Christian Gunning wrote:
 | | Also, you may need to add RNGScope() if you use R's RNG.
 | |
 | |
 | |
 | | Yes, I should have mentioned that in my post.  Calling RNGScope() is 
 left
 | to
 | | the user, since multiple calls to sample() can conceivably happen 
 inside
 | a
 | | single RNGScope().
 |
 | With that, maybe best to be included as another example in 
 RcppArmadillo ?
 |
 |
 | Why?  The proposed behavior is the same as sugar's rnorm, etc.: a utility
 | function that uses R's RNG -- it's the
 | user's responsibility to properly scope the RNG.

 Fair point.

 | When time permits, I'll add Romain's comments on sugarizing sample (which I
 | *think* I understand), along with some testing code.

 Excellent plan.

 Dirk

 --
 Dirk Eddelbuettel | e...@debian.org | http://dirk.eddelbuettel.com





-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp internal benchmark tool

2012-12-09 Thread Christian Gunning
 | I haven't seen any discussion on this in a while.  Is this something
 | that warrants discussion, or something to keep in mind for later?
 | I'd prefer such a package to depend on RcppArmadillo so that my
 | implementation of sample() can be easily included.  Are there
 | downsides to this?

 I think sample() should go into Armadillo proper.

 You just need to get lucky to get both Romain and myself when our attention
 span is actually on this.  Joking aside I should make some time to put this
 in ... but not sure when I'll get to this.

Sounds fine to me -- I aim to submit a patch with sample() code +
tests before Xmas,
so I'll post it against RcppArmadillo.

Does this imply that something like an RcppExtras package is, for now
at least, a no-go from your point of view?
I have no opinion either way :)

-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp internal benchmark tool

2012-12-08 Thread Christian Gunning
 On 8 December 2012 at 15:44, Romain Francois wrote:
 | I've been using the microbenchmark package extensively and took
 | inspiration from it to implement a Timer class in Rcpp to measure
 | performance at a lower level.

Very exciting.


 That's probably quite useful. I had an older/simpler class here from
 something I had done years ago at work covering the Linux + Windows
 cases. Olaf has more basis covered so this good.

 It is on the border of creeping featuritis though ...

 | - include the Timer.h header, which is **not** automatically added in
 | Rcpp.h:

 ... but that is a fair defence against bloat.

There was some conversation about splitting off these feature requests
into a separate package (RcppExtras?) on list a while back -- obvious
candidates include sample(), the list of R functions that might be
improved in Rcpp (as per Hadley et al's comments), and perhaps this...

I haven't seen any discussion on this in a while.  Is this something
that warrants discussion, or something to keep in mind for later?
I'd prefer such a package to depend on RcppArmadillo so that my
implementation of sample() can be easily included.  Are there
downsides to this?

thanks,
Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] R.e. No matching function for call to as(double) error at compile time

2012-12-06 Thread Christian Gunning
 /* up to the above line, everything compiles.
 Now I want to get a double out from first element of test.*/

 double test0 = Rcpp::asdouble(test[0]);

Does this work?
double test0 = test[0];

In general, including a self-contained minimal example helps.
sourceRcpp() makes this trivial.

-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] How to increase the coding efficiency

2012-12-05 Thread Christian Gunning
Can you post a minimal full example?
-Christian

On Tue, Dec 4, 2012 at 8:39 PM, Honglang Wang
wanghonglang2...@gmail.com wrote:
 Yes, the main issue for my coding is the allocation of memory.  And I have
 fixed one of the biggest memory allocation issue: 4000 by 4000 diagonal
 matrix. And since I am not familiar with Rcpp and RcppArmadillo, I have no
 idea how to reuse the memory. I hope I can have some materials to learn
 this. Thanks.



 What exactly do these timings show?  A single call you your function?
 How many calls?

 Here I called my function for 100 times.


 Building on Romain's point: -- a portion of your function's runtime is
 in memory allocation
 (and you have a lot of allocations here).
 If you're calling your function thousands or millions of times, then
 it might pay to closely
 examine your memory allocation strategies and figure out what's
 temporary, for example.
 It looks like you're already using  copy_aux_mem = false in a number
 of places, but you're
 allocating a lot of objects -- of approx what size?

 For example, wouldn't this work just as well with one less allocation?
 arma::vec kk = t;
 arma::uvec q1 = arma::find(arma::abs(tp)h);
 kk.elem(q1) = ((1-arma::pow(tp.elem(q1)/h,2))/h)*0.75;
 // done with q1.  let's reuse it.
 q1 = arma::find(arma::abs(tp)=h);
 // was q2
 kk.elem(q1).zeros();

 You could potentially allocate memory for temporary working space in
 R, grab it with copy_aux_mem = false, write your temp results there,
 and reuse these objects in subsequent function calls.  It doesn't make
 sense to go to this trouble, though, if your core algorithm consumes
 the bulk of runtime.

 Have you looked on the armadillo notes r.e. inv?  Matrix inversion has
 O(n^2).  You may be aided by pencil-and-paper math here.
 http://arma.sourceforge.net/docs.html#inv

 Here my matrix for inverse is only 4 by 4, so I think it's ok.


 best,
 Christian

  Dear All,
  I have tried out the first example by using RcppArmadillo, but I am not
  sure whether the code is efficient or not. And I did the comparison of
  the
  computation time.
 
  1) R code using for loop in R: 87.22s
  2) R code using apply: 77.86s
  3) RcppArmadillo by using for loop in C++: 53.102s
  4) RcppArmadillo together with apply in R: 47.310s
 
  It is kind of not so big increase. I am wondering whether I used an
  inefficient way for the C++ coding:



 --
 A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!





-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] How to increase the coding efficiency

2012-12-04 Thread Christian Gunning
What exactly do these timings show?  A single call you your function?
How many calls?

Building on Romain's point: -- a portion of your function's runtime is
in memory allocation
(and you have a lot of allocations here).
If you're calling your function thousands or millions of times, then
it might pay to closely
examine your memory allocation strategies and figure out what's
temporary, for example.
It looks like you're already using  copy_aux_mem = false in a number
of places, but you're
allocating a lot of objects -- of approx what size?

For example, wouldn't this work just as well with one less allocation?
arma::vec kk = t;
arma::uvec q1 = arma::find(arma::abs(tp)h);
kk.elem(q1) = ((1-arma::pow(tp.elem(q1)/h,2))/h)*0.75;
// done with q1.  let's reuse it.
q1 = arma::find(arma::abs(tp)=h);
// was q2
kk.elem(q1).zeros();

You could potentially allocate memory for temporary working space in
R, grab it with copy_aux_mem = false, write your temp results there,
and reuse these objects in subsequent function calls.  It doesn't make
sense to go to this trouble, though, if your core algorithm consumes
the bulk of runtime.

Have you looked on the armadillo notes r.e. inv?  Matrix inversion has
O(n^2).  You may be aided by pencil-and-paper math here.
http://arma.sourceforge.net/docs.html#inv

best,
Christian

 Dear All,
 I have tried out the first example by using RcppArmadillo, but I am not
 sure whether the code is efficient or not. And I did the comparison of the
 computation time.

 1) R code using for loop in R: 87.22s
 2) R code using apply: 77.86s
 3) RcppArmadillo by using for loop in C++: 53.102s
 4) RcppArmadillo together with apply in R: 47.310s

 It is kind of not so big increase. I am wondering whether I used an
 inefficient way for the C++ coding:



-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Rcpp advocacy question -- build environment

2012-11-28 Thread Christian Gunning
Thanks all for the helpful comments.
Personally I've found the uniformity provided by Rstudio a great aid
in teaching environments.  I've struggled with introducing Rcpp to
folks, and I agree these developments are very exciting.

 And I say all that with the affection I personally have for Emacs + ESS :)

Since we're sharing, xterm + tmux + vim = smug:  o_0
(And I'm excited to take Rstudio vim-mode for a drive!)
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Rcpp advocacy question -- build environment

2012-11-27 Thread Christian Gunning
On Tue, Nov 27, 2012 at 3:29 AM, JJ Allaire jj.alla...@gmail.com wrote:

 RStudio has been adding support for sourceCpp recently (preview version
 here: http://www.rstudio.com/ide/download/preview). One feature particularly
 helpful for students new to C++ is that for failed compilations the GCC
 error log is parsed into a navigable list.

Thanks, that's nice to hear.  I'll keep my eyes out.

 Another thing related to the Rtools discussion above: Rtools writes it's
 location to the Windows registry and RStudio uses this to make sure that
 builds succeed even if the global path hasn't been edited. So setup for your
 students should be as straightforward as running the RStudio and Rtools
 installers. Students using other editors should either (a) make sure to edit
 the system path as suggested by Rtools; or (b) source a script that you
 provide to fixup their path correctly for the duration of sessions where
 they want to use sourceCpp.

That's good news.  I should have mentioned that we'll be enforcing
Rstudio use, so this behavior really simplifies life.
-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Rcpp advocacy question -- build environment

2012-11-26 Thread Christian Gunning
Advice for introducing students to Rcpp:

I'm TAing for a statistical programming class next semester, and I'm
talking to the instructor about including Rcpp examples -- sourceCpp()
makes this very easy to sell!

The question is build environment for folks with windows machines.
Personally, I think it's a worthwhile experience installing linux in a
VM and gaining the experience of working with a *nix machine (as I've
said before here).  Boot-from-usb is a similar option I've seen
successfully used for quick-and-easy Rinside build environment.
Personally, I'm confident in troubleshooting any problems that might
arise in these environments.

I have little experience with Rtools and I stopped following windows
years ago, so I'm a little worried about helping other folks with
build issues here.  Is it worth the trouble to push for a *nix build
environment, or is configuring R + Rcpp + Windows X now smooth enough
that I should relax and not worry?

thanks!
Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Sample function(s) for inclusion in RcppArmadillo

2012-11-14 Thread Christian Gunning
On Wed, Nov 14, 2012 at 6:14 AM, Dirk Eddelbuettel e...@debian.org wrote:


 Thank you, got both emails!  Will take a closer look -- we were busy with
 releasing Rcpp 0.10.0 which will rock :)


Sorry, I posted to list from wrong address; 0.10.0 looks great.  I found
the copious informational links at the bottom of the announcement very
helpful.

Would this make sense upstream in Armadillo? Or do you want the R RNG for
 reproducibility?


I hadn't even thought of trying to push this upstream, but yes, exact
reproduction of R's behavior was a goal.


 Also, you may need to add RNGScope() if you use R's RNG.


Yes, I should have mentioned that in my post.  Calling RNGScope() is left
to the user, since multiple calls to sample() can conceivably happen inside
a single RNGScope().

-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] problem with sample() implemented in Rcpp/RcppArmadillo

2012-11-04 Thread Christian Gunning
  Update -- I've implemented all of R's sample (with identical results)
  except for the walker alias method.  I used Armadillo for
 ProbSampleReplace
  and ProbSampleNoReplace, since there's no good STL replacement for R's
  revsort.

 Out of curiosity, what does revsort do? It must be something beyond just
 a reverse-order sort?

 Darren

 P.S. I don't have an R function of that name. Googling found it used in
 random.c but not where its defined!


(BTW, if you CC the poster, it's marginally easier to reply to.)

Today I learned that revsort is an exported function from the R API, and is
therefore in the bible (6:10):
http://cran.r-project.org/doc/manuals/R-exts.html#Utility-functions

revsort just does the following two operations in a single function call
(via scary pointer magic -- Boo!).  Also, boost lambda turns up as another
way to accomplish this:
http://arma.sourceforge.net/docs.html#sort_index
http://arma.sourceforge.net/docs.html#sort

-Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] problem with sample() implemented in Rcpp/RcppArmadillo

2012-11-03 Thread Christian Gunning
Dear all,

Code for uniform sampling is below, following the prototype from earlier
post.  Results/unit-tests (not included) are identical to R-core sample().

-Christian

template class T
T sample(const T x, const unsigned int size, const bool replace ) {
int ii, jj;
int nOrig = x.size();
T ret(size);
if ( size  nOrig  !replace) throw std::range_error( Tried to sample
more elements than in x without replacement ) ;
IntegerVector index(size);
if (replace) {
SampleReplace(index, nOrig);
} else {
SampleNoReplace(index, nOrig);
}

for (ii=0; iisize; ii++) {
jj = index[ii];
ret[ii] = x[jj];
}
return(ret);
}

void SampleReplace( IntegerVector index, unsigned int nOrig) {
int ii;
int  nSample = index.size();
for (ii = 0; ii  nSample; ii++) {
index[ii] = nOrig * unif_rand();
}
}

void SampleNoReplace( IntegerVector index, unsigned int nOrig) {
int ii, jj;
int nSample = index.size();
IntegerVector sub(nOrig);
for (ii = 0; ii  nOrig; ii++) {
sub[ii] = ii;
}

for (ii = 0; ii  nSample; ii++) {
jj = nOrig * unif_rand();
index[ii] = sub[jj];
// replace sampled element with last, decrement
sub[jj] = sub[--nOrig];
}
}
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] problem with sample() implemented in Rcpp/RcppArmadillo

2012-10-27 Thread Christian Gunning
 I am very new to c++ so I apologize in advance if this is a stupid question:

I ran into this myself when I started using Rcpp  -- it's a good
question.  The R API is extensive, but it's vanilla C and doesn't
handle vectors (and you already know how to sample() a scalar,
right?).

 For a larger analysis I am trying to implement the R function sample() in c++ 
 via RcppArmadillo.

There's a non-trivial penalty for reaching back into R for functions
that aren't exported via the API (e.g. Rcpp::Function sample =
base[sample];).  Rcpp Vectors are STL containers, and many folk
have asked the same questions wrt the STL.  There's some good
background reading here:
http://stackoverflow.com/questions/6942273/get-random-element-from-container-c-stl

Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] How to modifying the elements of a list in the global environment?

2012-10-20 Thread Christian Gunning
 What I would really do here is to create a simple struct or rather class that
 upon initialization creates the workspace and holds it.

 Doesn't fit as easily in the inline paradigm though.

Can one place object definitions in includes and then use them in the
body?  I'm rusty on inline -- I recall placing functions in includes,
but I don't recall doing this.  The inline docs are a little thin on
examples here.

-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] How to modifying the elements of a list in the global environment?

2012-10-19 Thread Christian Gunning
 ### For the Rcpp part, set aside working space in the global environment
 workspace - lapply(1:K, function(k) matrix(0.0, N, M))

 Then I try to access the matrices in the 'workspace' list and modify them, 
 but so far I have had no success. The first attemp, bolow, does not compile...

 code_f - '
 + Rcpp::NumericMatrix cpp_x(x);

If you're familiar with R and new to C++, understanding how C++
clone() works will help. For example, to use a single matrix as a
working matrix (if you write over it each iteration),  define the
working matrix (workmat) in R.   You can pass that object to the C++
function in two different ways:

Rcpp::NumericMatrix workmat(workmat_);  // modifies existing R
structure in-place, no extra copy made
Rcpp::NumericMatrix workmat( clone(workmat_) );  // allocate new
memory to make a deep copy

Assuming N  M are constant, then you can make a single matrix in R
and modify it in-place without any cost of extra copying.  If you
*want* and extra copy, you use clone().  R *always* makes a new copy
-- this is one of the big divides between R and C++,
pass-by-reference versus pass-by-value (clone).

For examples, see
http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-quickref.pdf.
-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] How to modifying the elements of a list in the global environment?

2012-10-19 Thread Christian Gunning
 Giovanni,

 Anything you pass from R into your C++ routine should be considered
 read-only. It's typically a bad idea to do in-place updates of the R
 object you passed in as an argument.

Really?  I was under the impression that the ability of in-place
modification was a conscious design decision.
Be aware that you've stepped outside of the functional programming
paradigm, yes.
But read-only?  From the C++ point of view, it's just memory.

That said, if you want safety (e.g. default R behaviour), use clone().
 Then you can modify to your heart's content.
-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Correlation in ArmadilloRcpp with missing values (nan)

2012-10-10 Thread Christian Gunning
 Maybe I am not good in coding, but even though I managed to make uvec with
 ones and zeros, I cannot use it to select rows  in given column, compiler
 complains
 error: no matching function for call to
 ?arma::Matdouble::submat(arma::uvec, int)?

Take a second look at the docs.  From
http://arma.sourceforge.net/docs.html#submat:


X( vector_of_row_indices, vector_of_column_indices )
X.submat( vector_of_row_indices, vector_of_column_indices )
...
For functions requiring one or more vector of indices, eg.
X.submat(vector_of_row_indices,vector_of_column_indices), each vector
of indices must be of type uvec.


Notice that the function that you call, submat(uvec, int), is
different than the one that actually exists, submat(uvec, uvec),

best,
-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] NA value for dates

2012-10-06 Thread Christian Gunning
+1

 I would LOVE to offer assistance, but I don't think I can do much - my C/C++
 knowledge is fairly limited.

Seems to me like you're doing pretty well so far!  As often as not,
identifying the *location* of the problem is the hardest part.

 I checked out Rcpp's src/Date.cpp . It seems all the work is done on
 Date::update_tm(), which calls gmtime_(). But where is struct tm and time_t
 defined? I guess this is the internal representation of dates in R, correct?

Have you looked at the doxygen docs?  They're machine-generated and
can be confusing on first read.  On the other hand, they're big-C
Complete.  Following your trail, see examples of time_t here:
http://dirk.eddelbuettel.com/code/rcpp/html/Date_8cpp_source.html

Also, http://www.cplusplus.com/reference/clibrary/ctime/time_t/

-Christian



-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Three-dimensional vectors example

2012-09-26 Thread Christian Gunning
On Tue, Sep 25, 2012 at 3:00 AM,
rcpp-devel-requ...@lists.r-forge.r-project.org wrote:

 Someone just asked on StackOverflow about creating 3d arrays:
 http://stackoverflow.com/questions/12569992/constructing-3d-array-in-rcpp

 The best I could come up with is below. Did I miss something better?

 Full disclosure: The last I needed this, I also needed ops on it, and used
 the arma::cube class from (Rcpp)Armadillo instead.
+Rcpp::NumericVector v(vs);// get the data
+Rcpp::Dimension d(ds);// get the dimension object
+Rcpp::NumericVector r(d); // create (empty) vector
with correct dims

That's a cool example.  I didn't realize there was such a
NumericVector constructor.
For reference, the arma example using the advanced cube constructor is
below (first example).

It looks like the NumericVector(Dimension) constructor only works for
D=3 (for D=4, I just get a vector back). I realized recently that
arma::field provides a decent way to get arrays with D3, though
copying in/out is a pain and wrap() returns a matrix of lists (with
each cell containing a matrix).  I'm impressed that wrap() can figure
this out at all!

library(inline)
## 3D, arma
##
fx - cxxfunction(signature(dat_=numeric, nr=integer,
nc=integer, ns=integer),
plugin=RcppArmadillo, body='
NumericVector dat(dat_);
arma::cube mycube(dat.begin(), asint(nr), asint(nc), asint(ns));
return wrap(mycube);
')
result - fx( 1:24, 4, 3, 2)


## 4D array.  easily generalizes to fieldcube = 5D
##
fx1 - cxxfunction(signature(dat_=numeric, dim_=integer),
plugin=RcppArmadillo, body='
NumericVector dat(dat_);
IntegerVector dim(dim_);
NumericVector::iterator it = dat.begin();

arma::fieldarma::mat myarray(dim[2], dim[3]);

for (int ii=0; iidim[2]; ii++) {
for (int jj=0; jjdim[3]; jj++) {
myarray(ii, jj) = arma::mat( it, dim[0], dim[1]);
Rf_PrintValue(wrap(myarray(ii, jj)));
it += ( dim[0] * dim[1]);
}
}
return wrap(myarray);
')
result1 - fx1( 1:120, c(5, 4, 3, 2))


-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] NumericVector Double mismatch when indexing an array

2012-09-25 Thread Christian Gunning
 Indeed, changing the sample size from 5 to 500 results in;

For completeness, I've included an iterator example, tested over a
range of sample sizes, and plotted the results with the code below.
From where I sit, it looks like the relative timings flatten out (more
or less) at 1e4.

I'm not sure the norm_rand is really an apples-to-apples comparison,
since this function call may be incrementally faster due to lack of
arguments.

Honestly, this is a testament to how well the sugar code works, if you
accept that it does in fact work :)
-Christian

library(inline)
library(Rcpp)
library(rbenchmark)
library(plyr)
library(lattice)

fun1 - cxxfunction(signature(N=integer), body = '
int NN = asint(N);
RNGScope scope;
NumericVector rn(NN);
for (int i = 0; i  NN; i++) {
rn[i] = asdouble(rnorm(1, 0.0, 1.0));
}
return rn;
', plugin = Rcpp)

fun2 - cxxfunction(signature(N=integer), body = '
int NN = asint(N);
RNGScope scope;
NumericVector rn(NN);
for (int i = 0; i  NN; i++) {
rn[i] = Rf_rnorm(0.0, 1.0);
}
return rn;
', plugin = Rcpp)

fun3 - cxxfunction(signature(N=integer), body = '
int NN = asint(N);
RNGScope scope;
NumericVector rn(NN);
for (int i = 0; i  NN; i++) {
rn[i] = norm_rand();
}
return rn;
', plugin = Rcpp)

fun4 - cxxfunction(signature(N=integer), body = '
int NN = asint(N);
RNGScope scope;
return rnorm(NN, 0.0, 1.0);
', plugin = Rcpp)


fun5 - cxxfunction(signature(N=integer), body = '
int NN = asint(N);
RNGScope scope;
NumericVector rn(NN);
std::generate( rn.begin(), rn.end(), RandomNumber);
return rn; ',
includes='
inline double RandomNumber () { return
Rf_rnorm(0.0, 1.0); }',
plugin = Rcpp)


test.N = 4
set.seed(1)
print(fun1(test.N))

set.seed(1)
print(fun2(test.N))

set.seed(1)
print(fun3(test.N))

set.seed(1)
print(fun4(test.N))

set.seed(1)
print(fun5(test.N))

results - ldply(c(10^(1:5)), function(N) {
  ret - benchmark(fun1(N), fun2(N), fun3(N), fun4(N), fun5(N),
order = relative, replications = 1e3L)
  ret$N - N
  ret
}, .progress='text')

results$test = factor(results$test, labels=c(Loop, as, Loop,
Rf_rnorm, Loop, norm_rand, Sugar, Iterator))

plot(
xyplot( relative ~ N, groups=test, auto.key=list(space='right'),
type=c('l','g', 'p'), data=results,
scales=list(x=list(log=T)))
)

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Runtime debugging tips for package/module?

2012-09-14 Thread Christian Gunning
I've successfully compiled/installed a package built with
Rcpp.package.skeleton(module=T).
The C++ codebase is larger and more complex than I'm used, and I'm now
in the testing/runtime-debugging phase.
I'm wondering what standard runtime debugging tools are available
for errors that don't cause segfaults (so the standard R -d gdb
--vanilla doesn't help identify where the error occurred).

Is sprinkling code with Rf_PrintValue calls relatively efficient?
I'm a little unclear on where this error comes from -- is this an
exception thrown by Rcpp that's propagated back up to R?  Is there a
good place to learn about Rcpp's error pathways?

model - new(Metapop, npop, initstates, transmat, poplist)
Error in new_CppObject_xp(fields$.module, fields$.pointer, ...):
  not a matrix

thanks,
Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Unit Test Question Was: pnorm/qnorm?

2012-09-13 Thread Christian Gunning
On Wed, Sep 12, 2012 at 7:59 AM,
rcpp-devel-requ...@lists.r-forge.r-project.org wrote:

 The pixie dust referred to your assertions that we used some secret tools
 or were hiding something.

 Neither one is true.  It's all there.  It's just damn hard to read. But it's
 not hidden...

I'm officially of the opinion the template code is isomorphic to magic
pixie dust:  works, works well, don't really understand it.
I've been meaning to ask, though... what's with the conspicuous lack
of comments in the codebase?  Is this just a terse coding style?
-Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Unit Test Question Was: pnorm/qnorm?

2012-09-13 Thread Christian Gunning
On Thu, Sep 13, 2012 at 9:20 AM, Dirk Eddelbuettel e...@debian.org wrote:

 I am firmly in the 'Don't do '=' for assignment, ever' camp.

 | Is there any real downside to this habit?  It came up at the BioC
 | conference developer day this year and was more or less immediately
 | dismissed.

 Just say no.

For the sake of posterity, I'd say those deserves because...
clauses.  (I have my own pros/cons list, but I'm still not totally
confident in broadcasting them.)  Curious mind inquire.

Though offtopic, I do think it's a reasonable question here for folks
trying to map/leverage their knowledge of R onto C++.  To my knowledge
there's no equivalent of the  - construct in C++, for example.
-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Exposing R through C++

2012-09-12 Thread Christian Gunning
I understand that I cannot use Visual Studio compiler to build code written in 
C++ that uses Rcpp header files. Assuming this is the case, what are the 
other options that I have to be able to code in C++ which either internally 
uses Rcpp sugar for R functionality or implements its own methods to be used 
in R environment as a package.

I suggest paying closer attention to your email subject-line; it can
have a disproportionate impact on the quality of the replies that you
receive.

If you're stuck on a windows box, you might want to set up a
development environment in a virtual machine.  There are a number of
nice free/opensource VM tools available (e.g. VirtualBox, see
http://en.wikipedia.org/wiki/Comparison_of_platform_virtual_machines).
 You could even use Amazon EC2 instance -- the lowest-tier ones are
quite cheap, with community images containing complete development
environments.

Is cygwin compiler part of the open source R install?

No.  See http://cran.r-project.org/doc/manuals/R-admin.html#Getting-the-tools
Incidentally, there's no such thing as a *non* open-source R install :)

-Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Trouble passing arguments to R functions that have been passed in (maybe)

2012-09-11 Thread Christian Gunning
On Tue, Sep 11, 2012 at 3:00 AM,
rcpp-devel-requ...@lists.r-forge.r-project.org wrote:

 It seems to be the casethat when the memory issue occurs, garbage
 collection has just been called by R, at least according to gcinfo.In
 particular, it is called when bar is called and cleans up the arguments
 that bar is about to use, thus causing a problem.

 Is there a way to ensure the safety of the arguments that are sent back
 to R?

I've gotten in the habit of being very explicit with Rcpp -- limiting
the use of nested functions, doing one step per line.  I'm don't
understand the internals enough to understand the exact
metaprogramming/template details, and I've often seen odd behavior
disappear when I unpack a long, complicated line into component lines
of code. This is similar to Dirk's comment about limiting use of
temps.

Also, have you looked at Armadillo for submatrix access?  You can
easily pull out columns/rows into NumericVectors.  Sometimes I find
the logical separation between pure C++ (arma) and chameleon SEXP/Rcpp
conceptually helpful.

Curious to hear your results,
Christian
University of New Mexico

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Filling a list with iterator, or setting names from CharacterVector/SEXP?

2012-09-07 Thread Christian Gunning
 | Can I use asstd::string() and then iterate over the CharacterVector?

 Sure, works via   Rcpp::as std::vector std::string (foo)

Perfect, thanks.  Revised example included below for reference.

 I am not sure what it is that you want but if you look e.g. at RcppExamples
 and its examples related to parameter passage in and out, you see that we can
 pick _arbitrary_ objects in and out of Rcpp::Lists by name.   Does that help?

It looks like I just answered my own question -- I'd like to get the
actual *names* of the list on the C++ side:
Rcpp::List listnames = mylist.attr(names);
Is the .attr mechanism general to any named attribute that belongs to an SEXP?

The ultimate goal is C++ error-checking of list-access names -- if the
named element is not present in the list, print the offending name and
throw an exception.  Is there an easier way to do this than checking
the supplied name (as std::string) against the vector of list names?
I admit this looks convoluted, but it's a minimal example...

using namespace Rcpp ;
class World {
public:
World(SEXP mymat_) : mymat(mymat_), myrows(0), mycols(0) {
Rcpp::List mynames = mymat.attr(dimnames);
CharacterVector rownames_ = mynames[0];
rownames = Rcpp::as std::vector std::string
(rownames_);
nrows = rownames.size();
for (int i=0; inrows; i++) {
   myrows[rownames[i]] = i;
}
rownames_list = myrows.attr(names);
}
SEXP get(std::string varname) {
if (debug) {
// check that varname is in rownames_list
}
return myrows[varname];
   }
   void put(std::string varname, int val){
if (debug) {
// check that varname is in rownames_list
}
myrows[varname] = val;
};
public:
Rcpp::List myrows, mycols;
private:
std::vectorstd::string rownames;
Rcpp::List rownames_list ;
Rcpp::NumericMatrix mymat;
Rcpp::List mynames;
int  nrows, ncols;
bool debug;
};

RCPP_MODULE(yada){
using namespace Rcpp ;
class_World( World )
.constructorSEXP()
.method( get, World::get , get a list element )
.method( put, World::put , put a list element )
;
}


## in R
mytest - function(nr=2, nc=3) {
  inmat = matrix(1:(nr*nc), nrow=nr);
  colnames(inmat) = letters[1:nc];
  rownames(inmat) = letters[1:nr];
  aa - new(World, inmat)
  ret1 - aa$get(a)
  aa$put(a, 17L)
  ret2 - aa$get(a)
  list(ret1, ret2)
}


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Filling a list with iterator, or setting names from CharacterVector/SEXP?

2012-09-01 Thread Christian Gunning
On Fri, Aug 31, 2012 at 5:50 AM, Dirk Eddelbuettel e...@debian.org wrote:

 Yes -- I needed this the other day to return what I got in C++ as a
 std::vectorstd::string vecstr. I used something like

  Rcpp::CharacterVector charvec( vecstr.begin(), vecstr.end() )

Ok, I was wondering about std::vector.  But how do I go the other way
and get a std::vectorstd::string vecstr from a CharacterVector?
Can I use asstd::string() and then iterate over the CharacterVector?


 but I later realized that Rcpp::wrap() already covered this case so it
 reduced to

 return vecstr;

 instead :)

 You should be able to to do better than your loop below as you already have a
 vector in 'rownames'. My not just transform that into a list directly as 
 below?

 Dirk


 R library(inline)
 R
 R f - cxxfunction(signature(xs=character), plugin=Rcpp, body='
 + Rcpp::CharacterVector xv(xs);
 + return Rcpp::List( xv );
 + ')
 R
 R x - c(Moe, Curly, Larry)
 R f(x)
 [[1]]
 [1] Moe

 [[2]]
 [1] Curly

 [[3]]
 [1] Larry

My use-case is access-by-name.  So in this example I want, for example:
 R f(x)
 [[Moe]]
 [1] 1

 [[Curly]]
 [1] 2

Of course, I can just hand in list(Moe=1, Curly=2), but then I still
don't know how to get the names of the list out of the list into a
CharacterVector or  std::vectorstd::string.  Does this sort of make
sense?

Thanks!
-Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Filling a list with iterator, or setting names from CharacterVector/SEXP?

2012-08-31 Thread Christian Gunning
To clarify a little, I can avoid most of this hassle by constructing
my named lists in R.  I would like to compute on the names of those
lists on the C++ end, though -- things akin to R's
which(names(mylist)=='myname') and easily looping through names.
-Christian

On Thu, Aug 30, 2012 at 9:52 PM, Christian Gunning x...@unm.edu wrote:


 using namespace Rcpp ;
 class World {
 public:
 World(SEXP my_) : my(my_) {
 mynames = my.attr(dimnames);
 CharacterVector rownames = mynames[0];
 nrows = rownames.size();
 myrows = Rcpp::List(0);
 for (int i=0; inrows; i++) {
 Rcpp::CharacterVector tmpname(rownames[i]);
 std::string thisname = asstd::string(tmpname);
 myrows[thisname] = i;
 }
 }
Rcpp::List myrows;
Rcpp::List getrows() {
return myrows;
   }

 private:
 Rcpp::NumericMatrix my;
 Rcpp::List mynames;
 int  nrows;
 };



-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] Filling a list with iterator, or setting names from CharacterVector/SEXP?

2012-08-30 Thread Christian Gunning
I'm trying to implement a class lets me access elements by name in the
actual C++ code.
I'm handing in a matrix from R, and using the colnames and rownames of
the matrix to generate a named list containing the relevant indices.
My main interest here is legible code -- I'm trying to set up
user-modifiable markov chain model specification functions in C++ that
are relatively idiot-proof and can be error-checked (so far the idiot
is just me). Initial tests indicate that the speed cost of list access
are very small compared to the actual model code.  I'm not sure if I'm
really abusing lists here, and any suggestions on other directions to
explore would be appreciated.

In any case, I finally got this working, but it's really ugly, and I
feel like there has to be an easier way to do this -- iterators?.
I looked at the doxygen docs for List instantiation and methods, and I
admit it's still Latin to me (which is a little better than Greek...)
This is built with a vanilla Rcpp.package.skeleton(modules=TRUE),
replacing the World class with the following:


using namespace Rcpp ;
class World {
public:
World(SEXP my_) : my(my_) {
mynames = my.attr(dimnames);
CharacterVector rownames = mynames[0];
nrows = rownames.size();
myrows = Rcpp::List(0);
for (int i=0; inrows; i++) {
Rcpp::CharacterVector tmpname(rownames[i]);
std::string thisname = asstd::string(tmpname);
myrows[thisname] = i;
}
}
   Rcpp::List myrows;
   Rcpp::List getrows() {
   return myrows;
  }

private:
Rcpp::NumericMatrix my;
Rcpp::List mynames;
int  nrows;
};

RCPP_MODULE(yada){
using namespace Rcpp ;
class_World( World )
// expose the default constructor
.constructorSEXP()
.method( getrows, World::getrows , test function, return
something )
;
}

In R:
require(Rcpp)
Rcpp.package.skeleton('FillList', module=T)

In shell:
replace FillList/src/rcpp_module.cpp  contents from class World to
end with the above
R CMD INSTALL FillList

In R:
inmat = matrix(1:6, nrow=2);
colnames(inmat) = letters[1:ncol(inmat)];
rownames(inmat) = letters[1:nrow(inmat)];
require(FillList)
aa = new(World, inmat)
aa$getrows()

thanks,
Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Rcpp-devel Digest, Vol 33, Issue 8

2012-07-08 Thread Christian Gunning
 On 7 July 2012 at 17:05, Joshua Wiley wrote:
 | Thank you so much!  That worked and helped me understand why it was
 | happening :)  The idea of pointers is new to me so I think I need to
 | spend more time learning about that.

There's a nice cheatsheet here that points out some gotchas and nice C++ idioms:
http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-quickref.pdf

Which is, incidentally, looking a little worse for the wear.
Dirk, do you have any idea what happened to the formatting?  Give me a
hint and I'll see if I can fix it at some point...
-xian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] can one modify array in R memory from C++ without copying it?

2011-11-02 Thread Christian Gunning
On Wed, Nov 2, 2011 at 4:00 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:


 1. in my previous post  i used exactly that same constructor you are
 talking about as you can see from the code i posted

Sorry about that, completely missed it...
Using what's below, this should work fine.

 3. i am not 100% sure but this toy test that i did seem to indicate to me
 that a copy is done regardless by NumericalMatrix. I need to see the code
 for NumericMatrix to be absolutely sure, but i cannot explain things
 otherwise

This is a little tricky, I almost missed it myself (again).
From the Quickref:
If R/C++ types match, use pointer to x.
Use a non-integer input to your function and see if that works.  Take
a look at this example:

src - '
Rcpp::NumericMatrix r_m(mem);
int nn = r_m.nrow() * r_m.ncol();
// int nn = r_m.size();
// above doesnt work with NumericMatrix, .size() is ambiguous??
for (int ii =0; ii  nn; ii++) {
r_m[ii] = r_m[ii] + r_m[ii];
}
return r_m;
'

require(inline)
require(RcppArmadillo)
myfun = cxxfunction(signature(mem='numeric'), src, plugin='Rcpp')

ll - mm - matrix((1:10)/10, nrow=2)
llint - mmint - matrix(1:10, nrow=2)
myfun(mm)
## should be false, since myfun modifies mm directly?
print(all.equal(mm, ll))
print(all.equal(mmint, llint))

hth,
-Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] can one modify array in R memory from C++ without copying it?

2011-11-01 Thread Christian Gunning
On Tue, Nov 1, 2011 at 9:11 PM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:

 .Call(modify, m)
 m
     [,1] [,2] [,3] [,4] [,5]
 [1,]    1    3    5    7    9
 [2,]    2    4    6    8   10


 It didn't segfault, but the memory in R process didn't change as you see,
 although the matrix in armadillo code doubled. Which means that
 NumericMatrix copied memory from R process and passed a pointer to
 armadillo.

3 quick points:

1:  For the NumericMatrix-arma, you can use an advanced constructor
to get the behavior that you desire.
http://arma.sourceforge.net/docs.html#Mat -- you'll want copy_aux_mem
= false.

2:  Are you actually doing matrix math?  If you're just doing simple
element-by-element arithmetic, you might get just as good performance
with a simple loop or iterator.  You might try this first to
understand the R/C++ process, and *then* move to using Armadillo :)

3:  For completeness, note that Rcpp::NumericMatrix r_m(clone(mem));
*forces* a copy, thus restoring R's no side-effects semantics.

-Christian



-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] One main needs to call a few other functions

2011-10-21 Thread Christian Gunning
On Thu, Oct 20, 2011 at 7:58 PM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:
 to me the concern exists whether the other
 function is in a package or not, how would a call be made to an outside
 compiled object code from within Rcpp.

This is a pretty confusing sentence(s).  Clearer questions tend to
elicit clearer answers :)

 My C++ skills are quite limited, after all I represent the riff-raff
 that just hurdled the new lower bar to incorporating compiled C++ code
 in R.

You might want to spend some time practicing with the low bar before
you go for the high bar :)  Pulling in external code and/or objects
can be a bit confusing before you get the basics.

You mention packages (did you mean libraries?), so I want to point out
that calling R functions from within Rcpp is quite easy, if relatively
slow (see the quickref section on Functions).

Finally, for reference, the list browser/search engine is here -- I'm
a fan of the frames and threads interface myself:
http://dir.gmane.org/gmane.comp.lang.r.rcpp

hth,
Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] R.e. Is it C++ or Rcpp problem?

2011-09-23 Thread Christian Gunning
On Fri, Sep 23, 2011 at 3:00 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:

 You don't need a makefile for the kind of minimal example you'll post to
 a mailing list, so:
  1. Slap your code in a file called tmp.cpp.
    (Don't forget header includes.)

  2. Whiz to a shell, in that directory.

  3. Dramatically type:
    g++ tmp.cpp

  4. If it compiles, rush to run it with:
    ./a.out

Interesting point.  I guess I'm not sure what constitutes your code, though.

A lot of the mailing list examples use inline, which has a nice
verbose=T option that shows the program source that includes all the
needed header defns, as well as the necessary function definition
wrappers that we often omit here.  It also shows all the necessary
switches for g++.

The issue I see is that R takes the place of main(), and g++ requires
a main() to successfully compile.  I tried a trivial example, and I
didn't have any luck compiling. Am I missing something here?

cxxfunction(signature(x='numeric'), 'NumericVector xx(x);', verbose=T,
plugin='Rcpp')

## copy Program source to file, edit for sanity
## flags below taken from cxxfunction output

$ g++ -I/usr/share/R/include
-I~/R/x86_64-pc-linux-gnu-library/2.12/Rcpp/include tmp.cpp

-xian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] arma::mat and Rcpp::NumericMatrix

2011-09-16 Thread Christian Gunning
Jeff,

A few random comments in addition to Dirk's sound advice:

1.  I recommend using bigger matrices for testing just to get a feel.
For testing loop speed, you want the proportion of loop time to be
*very high* compared to the R interpreter overhead, resolution of your
timer, etc.   Here, the extra asarma::mat and wrap() in armaSrc may
add appreciable execution time relative to the loop work -- only
testing will tell :)

2.  Another advantage of big matrices is testing the relative impact
of memory copying versus in-place modification.  Both Rcpp and
RcppArmadillo allow for both -- for the former, search the quickref
for clone for an intro.  With RcppArmadillo, in-place is a little
more involved, but look for this line:
However, if copy_aux_mem is set to false, the matrix will instead
directly use the auxiliary memory (ie. no copying). This is faster,
but can be dangerous unless you know what you're doing!
http://arma.sourceforge.net/docs.html#Mat

3.  I've modified the below to move the +op from the conditional
evaluation to the definition.  For small thetaEndIndex or simple ops,
this won't matter, but for theatEndIndex = 1e12 and something like a
vec.size() accessor, it can make a noticeable difference.  In general,
it's a good habit not to put ops in the conditional unless you really
need them.

 armaSrc - '
...
        int thetaEndIndex = asint(sthetaEndIndex) - 1;
...
        for (int i = thetaStartIndex + 1; i = thetaEndIndex; i++) {

best,
Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Re: [Rcpp-devel] Data Persistence with Rcpp

2011-09-08 Thread Christian Gunning
On Wed, Sep 7, 2011 at 3:13 PM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:
  The question absolutely pertains to using the inline functionality.

I think this is a reasonable R/C++ question -- i.e. Rcpp.  inline is
more or less orthogonal to Rcpp.  inline is a great Rcpp jump-starter.

 As each new data arrives, I want to pass it to my C++ function.

After thinking about this for a bit, this might be a reasonable use
case for an Rcpp-module.  You can instantiate a module as an R object,
it will hold state, and can be easily updated, queried, etc.  The key
weakness here is that modules can't at present be serialized via
save()/load().  So, if you can do all your processing in one R
session, you might want to take a look at this.  The code ends up
clean and powerful.  I've been headed this way myself for
computationally extensive simulations that depend on time-varying
parameters residing in R dataframes.

Incidentally, an important question to ask yourself is:  where are
your bottlenecks?  It wasn't clear to me in reading your question
*why* you need C++.  The most popular use-case of Rcpp seems to be the
huge speed advantage.  Where/why do you need speed?  This should
highlight the code that needs to get pushed into C++.  R can compete
with compiled code in plenty of cases...

-xian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

[Rcpp-devel] R.e. First foray into Rcpp and comparison of speed with R

2011-09-01 Thread Christian Gunning
 In R I was able to
 vectorize all within line computations, but in C++ I have to use explicit
 looping, right?

At a glance, I don't see any glaring speed-related flaws.  Honestly,
I'm curious to see what the R version of the Compute looks like.
Others might advise on the use of iterators...

      w(i, t) = ped(i, t+3) - pa(i, t);

This brings up a question that I've been meaning to ask the list --
Last time I checked, with NumericVectors using myvec[i] was
significantly faster than myvec(i) (due to bound and NA checking?).
Now that I think of it, I seem to remember discussion of disabling
these checks with NumericMatrix et al.  Of course, no checking is just
another way to shoot my own foot -- I'm a big fan of myvec(i) in
day-to-day use :)

best,
-xian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] R.e. First foray into Rcpp and comparison of speed with R

2011-09-01 Thread Christian Gunning
On Thu, Sep 1, 2011 at 5:13 PM, Dirk Eddelbuettel e...@debian.org wrote:
 Uh-oh. Factor 10. Wow.

Yeah, huh?  To be fair, this example is ultra-contrived.  The *only*
thing that happened was indexing.
Is it possible that compiler magic (ala loop unrolling that isn't done
for () ) accounts for any of the speedup?  I have basically no
experience with this.

 Matrix is different because we cannot do [i, j] for C legacy reasons. So both
 variants may be fast...

Yeah, but we *can* do linear access of a matrix with something like [
i+nrow*j ], which shouldn't have any bound checking (right??).  I
still don't see how linear bracket access on a matrix doesn't behave
the same as linear bracket access on vector compared to their
respective () behaviors...

-xian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e. Speed gain assistance (Wray, Christopher)

2011-08-18 Thread Christian Gunning
There's a number of things going on in your example.  Are you sure
that sample() is the bottleneck?  You might want to try breaking this
into smaller pieces and benchmarking each with rbenchmark.

On Wed, Aug 17, 2011 at 3:00 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:

 I have thought (but not tried) importing R's sample function...but I suspect 
 this may be a totally rude idea.

Pulling R functions into a C++ function isn't hard, but there's
overhead -- if i recall correctly, it's appreciably slower than the
API.

Take a look at this (unweighted) sample() function.  It's giving R a
run for it's money, and is pretty fast even for very large n, and it
looks statistically correct (not sure if I'm glossing over ugly,
machine-specific details of double-int conversion here). Does this
shed any light on your question?

best,
Christian

library(inline); library(Rcpp);
src1-'
NumericVector xx(x);
int xx_sz = xx.size()-1; // index of last xx
int nn=asint(n);
NumericVector ret(nn);
RNGScope scope;
for (int i=0; inn; i++) {
ret[i] = xx[Rf_runif(0.0,xx_sz)];
};
return(ret);
'

mysample-cxxfunction( signature(x='numeric', n=numeric), src1, plugin='Rcpp')

system.time(result - mysample(1:50, 1e7))
system.time(resultR - sample(1:50, 1e7, replace=T))


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] R.e. Speed gain assistance (Wray, Christopher)

2011-08-18 Thread Christian Gunning
 No probs - and sorry for the unclear post! Thanks

No worries. There are some important points here, some that have been
raised repeatedly.

On Thu, Aug 18, 2011 at 7:57 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:

 R (1:50)[runif(10,0,20)]

 And I was wondering if I had missed some sugar-type of construct that would 
 allow me to avoid the explicit 1e7 loop - and instead make use of some Rcpp 
 vectorised/optimised/ machinery. Christian's sugg' of allowing double-int 
 did speed things up enough, by me to chuck away the floor...

A big point here is that loops aren't bad in C++ -- the speed
penalties are much less if you're using pure C++ within them, not
making spurious function calls in them, etc.  Sugar is exactly what
the name implies -- syntactic sugar that beautifies code. It's not
secret turbo-sauce -- that's what the compiler is for.

-xian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] R.e. Speed gain assistance (Wray, Christopher)

2011-08-18 Thread Christian Gunning
On Thu, Aug 18, 2011 at 7:57 AM, Hadley Wickham had...@rice.edu wrote:
 Take a look at this (unweighted) sample() function.  It's giving R a
 run for it's money, and is pretty fast even for very large n, and it
 looks statistically correct (not sure if I'm glossing over ugly,
 machine-specific details of double-int conversion here). Does this
 shed any light on your question?
 mysample-cxxfunction( signature(x='numeric', n=numeric), src1, 
 plugin='Rcpp')

 system.time(result - mysample(1:50, 1e7))
 system.time(resultR - sample(1:50, 1e7, replace=T))

 Don't forget about sample.int:

 system.time(result - mysample(1:50, 1e7))
   user  system elapsed
  0.493   0.064   0.557
 system.time(resultR - sample(1:50, 1e7, replace=T))
   user  system elapsed
  0.872   0.089   0.962
 system.time(resultR - sample.int(1:50, 1e7, replace=T))
   user  system elapsed
  0.209   0.001   0.212

 Hadley

So, I can't figure out how to import and use sample.int into C++.  I
keep getting the following when I exchange sample.int for sample,
below.  I'm guess it's the interaction between IntegerVector and R??
Not sure it matters, but I'm surprised/confused:

cpp_exception(invalid first argument, Rcpp::eval_error)

src2-'
NumericVector xx(x);
int xx_sz = xx.size(); // index of last xx
// generate 0:(length(xx)-1)
IntegerVector index(xx_sz, 1.0); // cant use 1 here, 1.0 still required
std::partial_sum(index.begin(), index.end(), index.begin());
index = index -1;

// sample out of index
int nn=asint(n);
IntegerVector sindex(nn);
NumericVector ret(nn);
//Function sample(sample.int); // doesnt work
Function sample(sample);
RNGScope scope;
// sindex has length nn
sindex = sample(index, _[size]=nn, _[replace] = true);
for (int i=0; inn; i++) {
ret[i] = xx[ sindex[i] ];
};
return(ret);
'

mysample2-cxxfunction( signature(n=numeric, x='numeric'), src2,
plugin='Rcpp')
print(system.time(result - mysample2( 1e7, 50:1)))

I can shave a little time off by changing everything to NumericVectors
and using ret in place of sindex (and thus avoiding an extra Vector
allocation of size nn), but then I don't expect sample.int to work
anyway.

Moral: In this case, a pure C++ loop is cleaner *and* faster.  Not to
beat a dead horse or anything...
-Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Pointer troubles

2011-08-18 Thread Christian Gunning
 Comment: A concise example that uses an XPtr in a C++ function is
 still lacking.

Sorry I missed Manuel's example when I last posted.  I guess I was
thinking something like below, which is a direct analog of apply. This
concisely mirrors the semantics in RcppDE (interchangable work
function for a well-defined task).  Here, the user needs only change
inc.  Only thing is, this example seems annoyingly long for inclusion
in the quickref.  Also, I'm not sure whether using inline here is more
or less confusing to the overall idea...

Any thoughts on documentation priorities?
-xian

require(inline); require(Rcpp)

inc - '
// Define a simple function
double myFun(SEXP xs) { // sum
Rcpp::NumericVector x(xs);
double sum = std::accumulate(x.begin(), x.end(), 0.0);
return(sum);
}
'

src - '
// Define a pointer to the above function
typedef double (*funcPtr)(SEXP);
return(XPtrfuncPtr(new funcPtr(myFun)));
'

src1 - '
// Define a pointer to the above function
typedef double (*funcPtr)(SEXP);
XPtrfuncPtr myptr(infun);
// apply myptr to rows/columns of x
NumericMatrix xx(x);
int margin = asint(margin_);
int nr = xx.nrow();
int nc = xx.ncol();
if ( margin == 1 ) {
NumericVector ret(nr);
for( int i = 0; inr; i++) {
ret[i] = (*myptr)( wrap(xx(i,_)) );
};
return(ret);
};
if ( margin == 2 ) {
NumericVector ret(nc);
for( int i = 0; inc; i++) {
ret[i] = (*myptr)( wrap(xx(_,i)) );
};
return(ret);
};
'

mksum - cxxfunction(signature(), body = src, includes = inc, plugin=Rcpp)
myapply - cxxfunction(signature(x='numeric', margin_='integer', infun='XPtr'),
body = src1, includes = inc, plugin=Rcpp)

aa = matrix(1:100, nrow=5)
res1 = myapply(aa, 1, mksum() )
res1R = apply(aa, 1, sum)
res2 = myapply(aa, 2, mksum() )
res2R = apply(aa, 2, sum)

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Overloaded constructors?

2011-08-11 Thread Christian Gunning
 class A {
 public:
 A(int argument) {}
 A(std::string name) {}
 };

 Now, given such a class - is there a way to distinguish the two constructors? 
 The way I understand the code in the Rcpp module is to allow for different 
 constructors with different numbers of arguments, but overloaded constructors 
 like the above case are out of scope at the moment. Maybe I have to live with 
 it, but I think there should be a solution to it (i.e. employing singleton 
 factories of the objects).

Did you look at the documentation for Rcpp modules, as Dirk hinted at?
 If you can use modules for your needs, look at section 2.2 here
http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-modules.pdf.
 This is more or less what you're looking for, no?

 The case for methods is greatly solved for example by function pointers to 
 class members or even to function pointers to c++ functions taking as first 
 argument a pointer to the class. BTW, I discovered this very cool feature by 
 reading the code, but there is no documentation yet, right? Does the feature 
 stay in Rcpp?

The second point above (function pointers to c++ functions) should
make it into the quickref when i have some time.  I posted a bit about
this on the list last week -- i'm thinking about something like a c++
apply() function using rcpp's row/column magic as a super-simple
example.

If you can write up a simple example of the first point, i'd be happy
to copy-edit it into the quickref.

Christian


 Cheers,

 Sebastian

 Am 05.08.2011 um 18:54 schrieb Dirk Eddelbuettel:


 On 5 August 2011 at 12:06, Sebastian Weber wrote:
 | Hi!
 |
 | I recently learned how to deal with overlaoded functions when I wanna wrap
 | a class function interface with overladed things. The solution is to use
 | function pointers.

 Or 'factories' with a base class derived classes, and and and. I think there
 are many ways.

 | Now, what comes to the rescue in the case of overladed constructors? Any 
 suggestion?

 What exactly do you want?

 I think the basic word is that at a basic level we just can't.  The R API is
 after C-based and we have to play some tricks about generated names for
 functions etc.  Romain put some tricks into Rcpp modules to allow something
 close to multiple constructors for a Modules object but we can't give you
 each and every feature of C++ in Rcpp as there are some restrictions imposed
 by being in between R and C++ --- which is the space we chose to be in.

 Cheers, Dirk

 --
 Gauss once played himself in a zero-sum game and won $50.
                      -- #11 at http://www.gaussfacts.com

 --
 Sebastian Weber
 Group of Cell Communication and Control
 Freiburg Institute for Advanced Studies - FRIAS
 School of Life Sciences - LIFENET
 Albert-Ludwigs-Universit?t Freiburg
 Albertstr. 19
 79104 Freiburg
 T.: +49-761-203-97237
 Fax:+49-761-203-97334



 --

 ___
 Rcpp-devel mailing list
 Rcpp-devel@lists.r-forge.r-project.org
 https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


 End of Rcpp-devel Digest, Vol 22, Issue 16
 **




-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Short blog post on loop speed in R

2011-06-23 Thread Christian Gunning
On Sun, Jun 19, 2011 at 11:20 AM, Douglas Bates ba...@stat.wisc.edu wrote:


 As for the use of Rcpp, the STL containers and algorithms can be
 exploited to an even greater extent.  If you are willing to jump
 through the hoops of defining a struct that inherits from
 std::binary_function then you can shorten the Rcpp-based code
 considerably.

Thanks for this, by the way.  I added it to the post (which got a
shout-out from David on the Revolutions blog), along with your
comments about apply().

Strictly speaking, it's 8 vs. 6 lines of code.  I guess considerably
shorter is in the eye of the beholder :).  It's a neat template
example, in any case.

-xian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] redimension help

2011-06-08 Thread Christian Gunning
 I have developed a function that builds a series of vectors and a matrix
 of undetermined size. ?Rather than attempt dynamic objects (which I
 wouldn't know how to do anyway) I have been able to initialize with row
 dimensions that cannot be exceeded on these objects.

If this is your goal, I recommend an alternate method --
RcppArmadillo.  It offers resizing (e.g.
http://arma.sourceforge.net/docs.html#set_size
).  There are several ways to do this with Armadillo, depending on
whether the memory of the object gets preserved or not. Note that you
need to wrap() arma objects before, for example, putting them in lists
(i think) or returning them to R.  Something like this should get you
started:

require(RcppArmadillo)

src = '
mymat = arma::mat(2, 2);
//find dims of mymat, put them in vars nrow and ncol
mymat.set_size(nrow, ncol);
// do things
return wrap(mymat);
'

fun = cxxfunction('', src, plugin='RcppArmadillo')

As an aside, are you *sure* that you can't allocate after computing
the size?  I'm with Douglas in the confused camp :)
After all, much of Rcpp's magic is via templates, which make objects a
lot more dynamic than you might expect (if you're come from, for
example, a fortran background).

-Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Create an instance of a reference class for a C++ class exported as a module from within C++?

2011-06-06 Thread Christian Gunning
 At the moment the only way i see is to make an R call to new and construct 
 the object this way...

 Many of the methods for this class return other members of this class.
 Can I create a new instance of the reference class in R from within
 the module?  I'm sure it is possible, I'm just wondering if there is
 an easy way to do this without duplicating large chunks of the code in
 Rcpp/src/Module.cpp.  Can i somehow clone the SEXP representing the
 current instance then swap the external pointer to the C++ object?

I played with this a little more, and the following works fine.
Nothing striking here. The part I don't understand is, can you employ
the SEXP returned by spawn() as an instance of Bar, or are you then
stuck with the R interface to Bar?

-Christian

## in R
Rcpp.package.skeleton('testmod', module=T)

//in testmod/src/rcpp_module.cpp

#include Rcpp.h
using namespace Rcpp;
class Bar {
public:
Bar()  {}
void set(int state_) { this-state = state_; }
int get() { return state; }

SEXP spawn() {
Environment meth(package:methods);
Function Rnew = meth[new];
Function Rget(get);
SEXP NewObj( Rnew(Rget(Bar)) );
return NewObj;
}
private:
int  state;
};

## in R
require(testmod)
bb = new(Bar); bb$set(3)
cc = bb$spawn();  cc$set(4)
bb$get(); cc$get()




-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Create an instance of a reference class for a C++ class exported as a module from within C++?

2011-06-03 Thread Christian Gunning
 At the moment the only way i see is to make an R call to new and construct 
 the object this way...

 Many of the methods for this class return other members of this class.
 Can I create a new instance of the reference class in R from within
 the module?  I'm sure it is possible, I'm just wondering if there is
 an easy way to do this without duplicating large chunks of the code in
 Rcpp/src/Module.cpp.  Can i somehow clone the SEXP representing the
 current instance then swap the external pointer to the C++ object?

To elaborate a bit:

Am I off-base in thinking you can make a custom constructor for your
class that calls R's new(), being careful to avoid circularity, that
returns a blank instance to your method to be filled? Is something
like the following anywhere near this?

class MyClass {
  public:
Bar(bool x_) : {}  // for spawn
Bar() : {}

  private:
Bar spawn() {
  Environment meth(package:methods);
  Function Rnew = meth[new];
  Rcpp::XPtrMyClass NewObj( Rnew(false) );
}
};

-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e. Fwd: problem with rmultinom function

2011-06-01 Thread Christian Gunning
On Tue, May 31, 2011 at 10:55 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:
 Hi,
 I sent this message a couple of days ago, but I haven't heard anything yet.
 I think you didnt receive it, that's why I send it again.

I didn't see anything.  If you're not subscribed to the list,
submissions silently fail.  Plus, you must send from the subscribing
address.  I've made this mistake a few times...

 I have a strange problem that I spent several days trying to fix it, but
 unfortunately I wasn't able to catch it. I'm running the rcpp code for 3000
 iterations(running the same code for 3000 times) on different datasets. but
 for some datasets, in the final iterations (like 2667 th iteration) the code
 stops running and it jumps out of the R environment. and if I run the same
 code (without any changes) on the same dataset(still without any changes)
 the problem might never happen and it goes to the last iteration without any
 problem(or the problem may occur in another iteration). and the interesting
 part is that error code is different each time, I got error codes like:

 what():  invalid partial string match
 what():  'prob' is missing
 what():  unused argument(s) (environment)
 and etc...
 I'm pretty sure that problem occurs in the line of code that I am using
 rmultinom function, but I included the necessary function
 Function rmultinom = stats[rmultinom];

 to be more clear I wrote a simple function and I attached it in this email.
 in this code I didn't read any dataset, I just used some variables to define
 the size of structures that I need to get from dataset. if you run the code
 with these values for P, K, unum,qnum, the error occurs in the first 10
 iterations, but If you change the values of those parameters to smaller
 values, the error may never happen.
 I tried to used an cpp implementation for rmultinom, it works but the
 program would be as slow as R version.


 do you have any idea why this problem occur? or did anybody ever have the
 same problem or can give me some tips to fix it?

 ps: all datasets are generated through the sampe process(with a single
 simulation code)

I'm attaching a cleanup of the code using inline -- you can now just
source this in R.  I'm not sure, but I think you might be working
under some mistaken assumptions.  Hopefully the attached code is more
conceptually clear.

There were a few offhand things that I modified, e.g. maxItr wasn't
used in the attached code.  There are a number of things that I
*didn't* change for which there seem to be faster/better methods, but
I'm not sure of your purpose.  For example, can any of the in-loop
assignments (qnum, qlength) be moved to the top?

Lastly, are you *just* using rmultinom and Cwhich to roll a K or P
sided die?  If so, what about something like asint(runif(1, 0, K))?
Even if you're rolling a weighted die, it seems like there's a better
way...

Hopefully this sheds at least a bit of light on your question.
Apologies if I've misunderstood.
-Christian

## Compile/run from R using the following (assuming inline package is
installed):
source('gibbs.R.txt')
fun1(10)

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
#include SamplingCode.h


inc = '
//using namespace Rcpp;
int Cwhich(IntegerVector binVec){
  int vecsize = binVec.size();
  for ( int i =0; i  vecsize; i++)
if (binVec(i) == 1)
  return i;
  std::cout  soemthing went wrong, no value equal to one was found !  
std::endl;
  return -1;
}
'

#RcppExport SEXP doGibbs(SEXP RmaxItr){//doGibbs - function(Questions, K, P, 
gibbs.max.iter, Z.Q=NULL, Y.Q = NULL){

src = '
Environment stats(package:stats); 
Function rmultinom = stats[rmultinom];
Rcpp::RNGScope scope;
//  Rcpp::List questions(Rquestions);

unsigned int K =50;
unsigned int P = 50;
NumericVector probs1(P, 1.0/P); //added -- instead of rep
NumericVector probs2(K, 1.0/K); //added
unsigned int maxItr = Rcpp::asint(RmaxItr);
Rcpp::List ZQ;
Rcpp::List YQ;
unsigned int unum=300;

std::coutunumstd::endl;
std::coutpoint1std::endl;
for(unsigned itr=0; itrmaxItr; itr++){ //changed
std::coutitritrstd::endl;
for ( unsigned int u=0; u  unum; u++) {
Rcpp::List QZQ;
unsigned int qnum= 100;
IntegerVector tmpu(qnum); //added
//YQ.insert(u, rep(0, qnum ));  

for( unsigned int q=0; qqnum; q++){
//asRcpp::IntegerVector(YQ(u))(q) = 
Cwhich(rmultinom(1,1, probs1 ));
tmpu(q) = Cwhich(rmultinom(1,1, probs1 ));
unsigned int qlength=200;
IntegerVector tmpq(qlength); //added
//QZQ.insert(q, rep(0, qlength ));

for( unsigned int n=0; nqlength; n++){   
  

Re: [Rcpp-devel] package .onLoad multiple modules

2011-05-31 Thread Christian Gunning
On Tue, May 31, 2011 at 3:00 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:
 When FALSE it does what you want.

I can't begin to describe how long I've waited for such a function.
-x


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e.: Problems with rlnorm

2011-05-29 Thread Christian Gunning
On Sun, May 29, 2011 at 3:29 PM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:

 I reviewed the discussion at:
 http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2010-September/0
 01078.html

 This made me realize that I should go ahead and code a simple putcol
 function loop when I need to populate a column in a Matrix array.  (I
 had spent some time looking for such a defined method.)

 An array or Matrix class would be nice, but for now I seem to be able to
 find work-arounds.

Take a look at the quickref in the section Using matrices,
particularly the part about _ -- Romain has done a lot of work since
the conversation that you reference :)
Also, see previous list message from Vincent and Dirk for namespace
notes on using _ outside of inline.

 Now I am calling the r-prefixed distributions with success, but this
 same code will fail on compile if the rlnorm() function is called.
 compile error if rlnorm is called instead of rnorm:
 file3a7d3a6f.cpp:38:28: error: 'rlnorm' was not declared in this scope

It's working now in the most recent SVN version (I'm guessing
someone's already pointed this out).

Below is an example that includes by-column assignment.  Also, unless
you need to reset the seed mid-function-call, RNGScope grabs the seed
from R, so you can use a regular set.seed call.  So, the return value
of the following is identical to that of your example:

require(inline)
src - '
Rcpp::RNGScope Scope; // gets value from set.seed call in R
int NumRands = 5;
int NumTrials = 3;
Rcpp::NumericMatrix RandVals(NumRands, NumTrials*2);
RandVals(_,3)=rlnorm(NumRands,2.0,1.0);
return RandVals;
'
 fun1 - cxxfunction(signature(),
 src, plugin = Rcpp)

set.seed(20)
fun1()

-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] R CMD BATCH - segfault (was: Create and access several instances of a C++ class from R)

2011-05-23 Thread Christian Gunning
On Mon, May 23, 2011 at 3:00 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:
 Just to get that clearly: Whatever I do with a C++ class in one session will 
 be lost after quit? So, that would mean, to save my current work (done with 
 an Rcpp module class) requires me to write a representation of the c++ object 
 in R, which can be saved and which, after reload, rebuilds the last state of 
 R affairs? Guessing that, my conclusion would be to not expose the Rcpp 
 module class, rather to build an R class which rests upon the C++ stuff and 
 holds the important information. That in turn would mean almost double use of 
 memory? Or how would you recommend to work around?

If I understand correctly, when Douglas says save the worksheet he's
referring to save.image(), which by default is the equivalent of what
happens with quit(save=yes), which is also equivalent to running R
in BATCH mode without the --no-save argument.

So, Douglas's comment is that saving the entire workspace can be
unsafe no matter how much cleaning up you do.  I *think* a safe
alternate to save.image() is to use a save() command to save specific,
***R/SEXP-only*** objects that are the results of your computation.

I realize this doesn't entirely answer your question about rebuilding
your C++ objects between sessions, e.g. between quit(save='no').  But,
if you can do all of your computations is one session, you should be
able to save the (R/SEXP only) results to an .RData file ala:
save(list.of.results.with.no.reference.to.modules, file='BATCH-results.RData)

hope that clarifies things a bit,
-Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Rcpp-devel Digest, Vol 19, Issue 10

2011-05-15 Thread Christian Gunning
On Sat, May 14, 2011 at 6:46 PM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:

 There is also Davor's trick of getting the C++ function pointer---this avoids
 the 'going back to R' overhead.  But it is not really clean to call an API
 that way if the API decided to close off those access points...

Eh? Haven't seen that before -- where does it live? Let's doc it if it's sane...

-xian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e. Rcpp equivalent of sample()?

2011-05-14 Thread Christian Gunning
 In the Rcpp vignettes, I found some of the R-like functions for
 sampling from distributions (runif, rnorm, etc), but I didn't see a function
 mimicking sample(). I checked the list of unit tests and didn't see it there
 either.  Have I missed it?  Is there a C++ function I should be using to
 sample (with replacement in my particular situation) from a vector (with
 provided weights).

In the quickref (and introduction) vignette, there's an example of how
to import a function from R and use it in C++.
Honestly, I've found it easiest to just import sample() from R (in the
stats namespace).  Two things to note:

1.  Performance -- there's a penalty for going back to R, but it's per
function call. So, you can pull a vector result of sample into an
integer vector.

2.  I find it easiest to sample indices rather then elements of the
set that I want to sample, and then do indexing within C++, for
example with an STL style loop.

I'm on the road now, but I can try to fire off an example in the next day or 2.
-Christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e. Basic documentation for Rcpp (Nick Sabbe)

2011-05-13 Thread Christian Gunning
On Fri, May 13, 2011 at 7:36 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:

 If anybody wants to call me an idiot for not finding this information: go
 ahead and make your day. Then make mine and point me to the docs I need :-)

Did you find the Rcpp-quickref vignette?  It contains a list of short
and hopefully self-explanatory examples that should get you started,
including an STL-style loop.  Of course, the focus is on Rcpp itself
rather than C++, for which there are already docs aplenty.  If you
find any glaring holes in the quickref, though, let me know and I'll
try to get them spackled up.

-christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] Thread handling

2011-04-26 Thread Christian Gunning
 As is, I?m able to return an argument such as a
 SEXP value from my function, and I can have it give feedback. However, if I
 do that before the thread finishes, I don?t know if there is a way to access
 it any more after the thread finishes. Likewise, if I were to wait until the
 thread finishes, then I might as well not call a thread. So what would be
 recommended as an Rcpp suggested mechanism for alerting users in R as to
 when threaded jobs finish?
 Thanks,
 Sean

I realize this might not be the best place for this, but here are some
quick notes on user feedback that might help other (new) Rcpp users --

1. If you just want to *print* a progress report to the console, both
std::cout and Rf_PrintValue should work just fine.  The first is
normal c++ semantics.  The second takes an SEXP and sends it to R for
printing (see R extensions manual 4.4.2 for details).  No idea how
this second one behaves with threading since, as Dirk pointed out, R
is single-threaded.

2. On a related aside -- if you want long-running tasks to be
interruptable, you must specifically request such. From a
single-threaded perspective, this is easy. Maybe this could generalize
for you -- if so, I'm curious to see. From the extensions manual,
section 6.12, Allowing interrupts:

No port of R can be interrupted whilst running long computations in
compiled code, so programmers should make provision for the code to be
interrupted at suitable points by calling from C
#include R_ext/Utils.h
void R_CheckUserInterrupt(void);


My understanding is that, while R is single-threaded, your C++ code
can do whatever it wants while R is waiting for it to return, provided
there's a single point-of-return. So, #1 above isn't really a
callback, but careful use of stdout should at least give you a
progress bar...

hth,
christian

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] R.e. loadRcppModules

2011-04-12 Thread Christian Gunning
On Tue, Apr 12, 2011 at 7:06 AM, Douglas Bates ba...@stat.wisc.edu wrote:

 The documented behavior is that an external pointer is replaced by a
 null pointer when an object is serialized.

Thanks. Got it.

 I was planning to
 experiment with an object that has enough information saved as R
 objects to be able to regenerate the C++ object and an external
 pointer to the module instance.  The methods that use the object will
 check first to see if the pointer is null, in which case they will
 regenerate the module instance, otherwise go directly to invoking
 methods on the module instance.

No rush on my part -- as usual, I'm just trying to figure out how the
pieces fit together :)

Just to clarify --  does your plan include storing user-modified
fields and properties in objects?  E.g. below, modtest with the msg
set?

best,
Christian

Rcpp.package.skeleton('testpkg1', module=T)
require(testpkg1)
modtest - new(World)
show(modtest)
modtest$set('hello')

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e. loadRcppModules

2011-04-11 Thread Christian Gunning
On Mon, Apr 11, 2011 at 3:00 AM,
rcpp-devel-requ...@r-forge.wu-wien.ac.at wrote:


 This will load the declared modules, and populate them into your
 package's namespace.

 I will update the Rcpp-modules vignette accordingly.

 Suggestions, comments, improvements, what are you  ? nuts !, ... are
 always welcome.

Works great for me -- very cool.

One question that's been bothering me -- how are module-based objects
*supposed* to behave across an R session quit/save/restart cycle? I'm
seeing no persistence, and a consistent segfault.  Am I missing
something here (perhaps wrt finalizer)?  If not, I'd like to add a
note to the vignette...

Using the supplied example, I get:

Rcpp.package.skeleton('testpkg1', module=T)
require(testpkg1)
modtest - new(World)
## everything works
show(modtest)
modtest$set('hello')
modtest$greet()
q()
## Save workspace image? [y/n/c]: y
## exit, save, restart -- nothing works

# [Previously saved workspace restored]
#
# During startup - Warning message:
# Class C++Object is defined (with package slot ‘Rcpp’) but no
metadata object found to revise subclass information---not exported?
Making a copy in package ‘.GlobalEnv’

require(testpkg1)
modtest$greet()
#Error in .External(list(name = CppMethod__invoke_notvoid, address =
pointer: (nil),  :
#  NULL value passed as symbol address

show(modtest)

 *** caught segfault ***
address 0x8, cause 'memory not mapped'

Traceback:
 1: .Call(Class__name, cppclass)
 2: sprintf(C++ object %s of class '%s' %s,
externalptr_address(pointer), .Call(Class__name, cppclass),
externalptr_address(cppclass))
 3: show(modtest)
 4: show(modtest)

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
Selection: 1
aborting ...
Segmentation fault


best,
Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Problem passing Armadillo objects back to R

2011-04-06 Thread Christian Gunning
 The issue is that when calling wrap it creates an unprotected SEXP, and
 Rcpp is not responsible for these. If the programmer passes an
 unprotected SEXP to ::create, it is his responsability to protect it.

Just to clarify -- in the case of a naive user who's not protecting
objects: a single wrap as the last call in a function is one case that
will *always* work as expected, correct? And when using more than one
wrap, later ones can *potentially* but not necessarily clobber earlier
ones, yes?

thanks,
-christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] RFC -- Function for making modules ala inline

2011-03-10 Thread Christian Gunning
After naively throwing code for an Rcpp module at inline, I realized
my mistake and looked inside cxxfunction.  Attached is a
tested module-creation function that's mostly a subset of cxxfunction.  It
takes the name of the module as defined in the source file's
RCPP_MODULE(modname)  (could probably grep for this), and the name of
a *file* containing the Module code.  Just like cxxfunction, it
compiles the code and loads the library.  It then loads/attaches/retrieves the
module from the library and returns a new Module object.

This function still uses 2 private functions from inline:
inline:::addLineNumbers and inline:::compileCode.  Since this is
Rcpp-specific, it seems like it would fit best in Rcpp, except for
it's (circular) dependency on inline.  So, the key question is: does
this provide added utility and, if so, in which package should it go?

Nothing earth-shattering here, but I think this could provide a nice
addition to the rapid prototype family.

best,
Christian
--
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!


modfunction.R
Description: Binary data
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] R.e. Debugging Rcpp packages with GDB

2011-01-19 Thread Christian Gunning
Thanks all for the crash course - it works great!

I just cobbled up a simple reload function. This has been a
long-standing pet peeve of mine -- anything that makes me leave the R
shell is distracting.  I've tested it and it seems to work just fine.
Are there any non-obvious downsides here?

reload = function(pkgname, preload=TRUE) {
## load it
if (preload) {
library(pkgname, character.only = TRUE)
}
libs - dir(paste(.path.package(pkgname), '/libs', sep=''), full.names=TRUE)
for (lib in libs) {
dyn.unload(lib)
dyn.load(lib)
}
return()
}

best,
Christian

On Wed, Jan 19, 2011 at 8:01 AM, Dirk Eddelbuettel e...@debian.org wrote:

 On 19 January 2011 at 08:43, Douglas Bates wrote:
 |  | 2) Is there a simple way to include debugging symbols/keep values from
 |  | getting optimized out when building with Rcpp?
 | 
 |  You could always include -g and then strip what you don't need -- which is
 |  what Debian and Ubuntu do to give you the *-dbg packages.
 | 
 |  R sits on top of Makefile logic, and make is pretty powerful language.  
 You
 |  can (literally) do just about anything   Setting CFGLAGS / CXXFLAGS or
 |  their PKG_* variants is probably easiest.
 |
 | Or create a file $HOME/.R/Makevars and define CXXFLAGS and CFLAGS in
 | there.  I have the following contents
 |
 | CFLAGS= -g -pipe -std=gnu99 -Wall -pedantic
 | CFLAGS= -g -O3 -pipe -std=gnu99 -Wall -pedantic
 | CXXFLAGS= -g -pipe -Wall -pedantic
 | CXXFLAGS= -g -pipe -std=c++0x -Wall -pedantic
 | CXXFLAGS= -g -O3 -pipe -Wall -pedantic
 | CXXFLAGS= -g -O3 -pipe -std=c++0x -Wall -pedantic
 |
 | and comment out the trailing lines if I want to suppress the c++0x
 | standard or the optimization when using the debugger.

 Seconded.

 That is actually what I do, including the better-than-awesome ccache:

 edd@max:~$ cat .R/Makevars
 # edd 03 Mar 2009

 ## for C code
 CFLAGS=-g -O3 -Wall -pipe -pedantic -std=gnu99
 #CFLAGS=-O3 -g0 -Wall -pipe -std=gnu99
 ## for C++ code
 CXXFLAGS= -g -O3 -Wall -pipe -pedantic -Wno-variadic-macros
 #CXXFLAGS= -g0 -O3 -Wall -pipe -Wno-variadic-macros
 #CXXFLAGS= -O3 -g0 -Wall -pipe
 ## for Fortran code
 #FFLAGS=-g -O3 -Wall -pipe
 FFLAGS=-O3 -g0 -Wall -pipe
 ## for Fortran 95 code
 #FCFLAGS=-g -O3 -Wall -pipe
 FCFLAGS=-O3 -g0 -Wall -pipe

 CC=ccache gcc
 CXX=ccache g++
 FC=ccache gfortran
 F77=ccache gfortran
 MAKE=make -j4
 edd@max:~$


 The -Wno-variadic-macros was once needed when Romain was a tad more
 aggressive in trying new C++0x features.

 The 'make -j4' also takes care of parallel builds.

 Dirk

 --
 Dirk Eddelbuettel | e...@debian.org | http://dirk.eddelbuettel.com




-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e. Debugging Rcpp packages with GDB

2011-01-18 Thread Christian Gunning
On Tue, Jan 18, 2011 at 2:46 PM,
rcpp-devel-requ...@lists.r-forge.r-project.org wrote:

 Can people share any tricks they use to debug Rcpp packages? For example, can 
 I print variables in a format that's a bit more high-level, like something 
 that I would get if I sent them to cout?


It's not very sophisticated, but I find that much of the time adding
Rf_PrintValue(xx) calls to code gives me as much info as I need.  If
it's a non-SEXP object like int, then Rf_PrintValue(wrap(my_int)).

 If that's not entirely obvious from my question, I am not a GDB expert. :-) 
 Basically, my workflow is: attach to the R process, set a breakpoint at 
 the function entry point, single-step and print variable values. I have 
 used watches and conditional breakpoints in GUI debuggers, but not (yet) in 
 gdb. Are there any Rcpp-specific gotchas to using those features with GDB?

I have 2 related simple questions after reading through Chapters 1
and 4 of Writing R Extensions:

My build/test chain is:

R CMD INSTALL mypackage
R --vanilla --debugger gdb
run
require(mypackage)
test in R
quit()
edit code
R CMD INSTALL mypackage
run
require(mypackage) ## reload package with edits
lather, rinse, repeat

1)  Is there a best way to reload the shared library after
rebuilding it? dyn.unload() and dyn.load()?

2) Is there a simple way to include debugging symbols/keep values from
getting optimized out when building with Rcpp?

Thanks,
Christian


 Thanks,

 Davor



-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] R.e. continuing attempts with throw/catch problem

2011-01-14 Thread Christian Gunning
On Sat, Jan 8, 2011 at 11:57 AM,
rcpp-devel-requ...@lists.r-forge.r-project.org wrote:


  [previously sent to Dirk but here in case anyone else is interested,
 and for archival purposes]

  Things are feeling alarmingly non-deterministic, but that may be
 because I've been sloppy.  I've been working mostly with a stock R
 2.12.1 install (Ubuntu 10.10), but have also tried R-devel and a
 custom-compiled R 2.12.1 (at various times configured --with-blas,
 --with-lapack OR --without-blas, --without-lapack: as I understand it I
 should stick with the --with variant and use Dirk's tools to manipulate
 which libraries are actually used?)

  This script ought to work anywhere, as long as lme4a is installed (I'm
 using ...-60, which is a fresh install from r-forge), gcbd is installed
 (CRAN), and you have network access ...

  Note that lme4a does **not** seem to work with Rcpp 0.9.0.2 (fresh
 R-forge install), but does (except for this particular problem) with
 Rcpp 0.9.0 (fresh CRAN install).

 library(gcbd)  ## utilities for messing with BLAS/ATLAS etc.
 tryscript - function() {
 source(url(http://www.math.mcmaster.ca/bolker/R/misc/throw.R;)) }
 ## make sure no accelerated packages are present
 purgeAtlas()
 purgeAtlas39()
 purgeGoto()
 purgeMKL()
 tryscript()
 installAtlas() ## restore Atlas ...

  Is there anyone out there *besides me* for whom this crashes at
 tryscript()?  It seems to happen whether I purgeAtlas() or not.  Is it
 necessary

FWIW, I just tried this and the script successfully issues an error in
all permutations of Atlas state using a stock R 2.12.0 on Ubuntu
Jaunty (do you suspect that R 2.12.1 an integral part of the
question?).  Note that I *just* installed newest R-forge versions of
Rcpp (0.9.0.2), Matrix (0.999375-47), MatrixModels (0.2-1), and lme4a
(0.999375-60).

Note that I don't have gotoblas2, revolution-mkl
r-revolution-revobase, etc. in my apt repositories, so purgeMKL()
purgeGoto() aren't meaningful for me.

-Christian


-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] Patch to RcppDE vignette -- Refs

2011-01-05 Thread Christian Gunning
Attached is a small diff to the RcppDE vignette.  I added 2 well-cited
primary lit papers that are helpful (and internet available)
introductions to DE.  While I was at it, I ran the doc through the
spell-checker :).

-Christian
Index: RcppDE.Rnw
===
--- RcppDE.Rnw  (revision 2835)
+++ RcppDE.Rnw  (working copy)
@@ -89,12 +89,17 @@
 \pkg{DEoptim}
 
\citep{MullenArdiaEtAl:2009:DEoptim,ArdiaBoudtCarlEtAl:2010:DEoptim,CRAN:DEoptim}
 provides differential evolution optimisation for the \proglang{R} language
-and statistical environement.  Differential optimisation is one of several
-evolutionary computing approaches; genetic algorithns and simulated annealing
-are two other ones.  Differential optimisation is reasonably close to genetic
+and statistical environment.  Differential evolution 
+\citep{StornPrice:1997:Differential} is one of several
+evolutionary computing approaches to the global optimisation of arbitrary 
+objective functions; genetic algorithms and simulated annealing
+are two others.  Differential evolution is reasonably close to genetic
 algorithms but differs in one key aspect: parameter values are encoded as
-floating point values (rather than sequences of binary digits) which makes it
-particular suitable for real-valued optimisation problems.
+floating point values (rather than sequences of binary digits), which makes it
+particular suitable for real-valued optimisation problems. The relative
+performance of differential evolution compared to other global optimisation
+algorithms, as well as optimal parametrization, is reviewed in 
+\citet{StornPrice:1997:Differential} and 
\citet{VesterstromThomsen:2004:Comparative}.
 
 \pkg{DEoptim} is based on an implementation by Storn
 \citep{PriceStornLampinen:2006:DE}. It was originally implemented as an
@@ -133,7 +138,7 @@
   covers other aspects such as the automatic type conversion offered by
   \pkg{Rcpp} as well as the automatic memory management: by replacing
   allocation and freeing of heap-based dynamic memory, a consistent source of
-  programmer error would be elimnated---plus we are not trying `short and
+  programmer error would be eliminated---plus we are not trying `short and
   incomprehensible' in the APL-sense but aim for possible improvements on
   \textsl{both} the length and the ease of comprehension without trading one
   off against the other;
@@ -149,10 +154,10 @@
 \end{itemize}
 
 This paper is organised as follows. The next sections describes the structure
-of \pkg{DEoptim} which \pkg{RcppDE} shadows closesly. The following two
+of \pkg{DEoptim} which \pkg{RcppDE} shadows closely. The following two
 section compare differences at the \proglang{R} and \proglang{C++} level,
-respectively. Next, changes in auxiliarry files are discussed before we
-review changes in perfomance. A summary concludes. The appendix contains a
+respectively. Next, changes in auxiliary files are discussed before we
+review changes in performance. A summary concludes. The appendix contains a
 list of figures contrasting the two implementations.
 
 \section[DEoptim structure]{\pkg{DEoptim} structure}
@@ -205,7 +210,7 @@
 routine) and \verb|permute()| (which is a helper function used to shuffle
 indices).
 
-The evalution function has been replaced by a base class and two virtual
+The evaluation function has been replaced by a base class and two virtual
 classes. These can now make use of objective functions written in
 \proglang{R} (as in \pkg{DEoptim}) as well as ones written in
 \proglang{C++}. Using compiled objective functions can lead to substantial
@@ -279,12 +284,12 @@
   types corresponding to base typed \verb|int|, \verb|double| etc. Also of
   note is how one matrix object (\texttt{initialpom} for seeding a first
   population of parameter values) is initialized directly from a parameter.
-\item Paremeter lookup is by a string value but done using the \pkg{Rcpp} 
lookup
+\item Parameter lookup is by a string value but done using the \pkg{Rcpp} 
lookup
   of elements in the \verb|list| type (which corresponds to the \proglang{R}
   list passed in) rather than via a (functionally similar but ad-hoc) function
   \verb|getListElement| that hence is not longer needed in \pkg{RcppDE}.
 \item Here as in later code examples, care was taken to ensure that variable
-  names and types correpond closely between both variants.
+  names and types correspond closely between both variants.
 \end{enumerate}
 
 \paragraph{Part 2: Middle of \texttt{DEoptim()}} The second part,
@@ -300,7 +305,7 @@
 \begin{enumerate}
 \item Matrix objects are created in \proglang{C} by first allocating a vector
   of pointers to pointers, which is followed by a loop in which each each
-  column is allocated as vector of approrpriate length.
+  column is allocated as vector of appropriate length.
 \item In \proglang{C++}, allocating a matrix is a single statement. Memory is
   managed by reference counting and is 

Re: [Rcpp-devel] Regression in conversion from NumericVector to ComplexVector?

2010-12-22 Thread Christian Gunning
 test1 = cxxfunction(signature(vec='complex'), '
             ComplexVector x(vec) ;
                 int nn = x.size();
                 for( int i=0; inn; i++) {
                     x[i].r = x[i].r*2 ;
                     x[i].i = x[i].i*2 ;
                 }
                 return x ;
 ', plugin='Rcpp')

 aa1 =  (0:9)*(1+1i)
 aa2 =  (0:9)*(1+1i)
 all.equal(aa1,aa2)  ## true
 bb = test1(aa1)
 all.equal(aa1,aa2)  ## false


Good deal. Is the above behaivor a bug?

-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


Re: [Rcpp-devel] Rcpp speed

2010-12-21 Thread Christian Gunning
Two points -

I see inconsistent timings (~10-20% variance between runs) even at
replications = 1e3.  Things seem to smooth out around replications =
5e3.  Romain's use of 1e4 throughout is a good idea.

Also,  += is sugarized and gives a nice example here - Rcpp wins by a
small margin in at least 1 case:

require(Rcpp)
require(inline)

testfun_R  - function(x,y) x+y

code - '
NumericVector xx(x);
NumericVector yy(y);
NumericVector zz = xx + yy;
return( zz );
'

code1 - '
IntegerVector xx(x);
IntegerVector yy(y);
yy += xx ;
return( yy );
'

testfun_Rcpp - cxxfunction(signature(x=integer, y=integer),
   body = code, plugin=Rcpp)

testfun1_Rcpp - cxxfunction(signature(x=integer, y=integer),
   body = code1, plugin=Rcpp)
testfun_R  - function(x,y) x+y

nreps=5e3
nn - as.numeric(1:1e2)
ii - 1L:1e2L

test1 = benchmark(replications = nreps,
   R = testfun_R(nn,nn),
   Rcpp = testfun_Rcpp(nn, nn),
   Rcpp1 = testfun1_Rcpp(nn, nn),
   Ri = testfun_R(ii,ii),
   Rcppi = testfun_Rcpp(ii, ii),
   Rcpp1i = testfun1_Rcpp(ii, ii)
)

nn - as.numeric(1:1e5)
ii - 1L:1e5L
test2 = benchmark(replications = nreps,
   R = testfun_R(nn,nn),
   Rcpp = testfun_Rcpp(nn, nn),
   Rcpp1 = testfun1_Rcpp(nn, nn),
   Ri = testfun_R(ii,ii),
   Rcppi = testfun_Rcpp(ii, ii),
   Rcpp1i = testfun1_Rcpp(ii, ii)
)

 test1; test2
test replications elapsed  relative user.self sys.self user.child sys.child
1  R 5000   0.043  1.303030 0.0440.000  0 0
2   Rcpp 5000   1.714 51.939394 1.7000.016  0 0
3  Rcpp1 5000   1.711 51.848485 1.6240.080  0 0
6 Rcpp1i 5000   1.689 51.181818 1.6640.024  0 0
5  Rcppi 5000   1.719 52.090909 1.7080.012  0 0
4 Ri 5000   0.033  1.00 0.0320.000  0 0
test replications elapsed relative user.self sys.self user.child sys.child
1  R 5000   2.842 1.334899 1.4401.396  0 0
2   Rcpp 5000  10.371 4.871301 8.9491.404  0 0
3  Rcpp1 5000   8.298 3.897605 8.2320.048  0 0
6 Rcpp1i 5000   2.129 1.00 2.1080.012  0 0
5  Rcppi 5000  16.212 7.61484311.5854.513  0 0
4 Ri 5000   3.067 1.440582 2.2080.852  0 0


best,
Christian





On Tue, Dec 21, 2010 at 8:31 AM,
rcpp-devel-requ...@lists.r-forge.r-project.org wrote:
 For completeness, below is the full script.  I also changed funRcpp to use
 IntegerVector.

 Dirk


 require(inline)
 funRcpp - cxxfunction(signature(x=integer, y=integer),
                       body = 'IntegerVector xx(x);
                               IntegerVector yy(y);
                               IntegerVector zz = xx + yy;
                               return( zz );',
                       plugin=Rcpp)
 x - 1L:3L
 y - 10L * x

 funR - function(x, y) {
    z - x + y
    return(z)
 }

 stopifnot(identical(funR(x, y), funRcpp(x, y)))

 library(rbenchmark)
 x - 1L:10L
 benchmark(replications = 1,
          R = x + x, Rfun = funR(x, x), Rcpp = funRcpp(x, x))

 x - 1L:1000L
 benchmark(replications=1000, R = x + x, Rfun = funR(x, x), Rcpp = funRcpp(x, 
 x))

 x - 1L:100L
 benchmark(replications=100, R = x + x, Rfun = funR(x, x), Rcpp = funRcpp(x, 
 x))





-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


[Rcpp-devel] Regression in conversion from NumericVector to ComplexVector?

2010-12-17 Thread Christian Gunning
I just tried to rebuild a package that built successfully as of
~August.  With new Rcpp, it fails on assigning a NumericVector to a
ComplexVector.  The gist seems to be as follows:

test1 = cxxfunction(, '
ComplexVector tmpc(10);
NumericVector tmpd(10, 2.0);
tmpc = tmpc + tmpd;
return(tmpc);
 ', plugin='Rcpp')

file50eaa187.cpp:32: error: no match for ‘operator+’ in ‘tmpc + tmpd’
/home/xian/R/x86_64-pc-linux-gnu-library/2.8/Rcpp/include/Rcpp/sugar/operators/plus.h:262:
note: candidates are: Rcpp::sugar::Plus_Vector_PrimitiveRTYPE, NA, T
operator+(typename Rcpp::traits::storage_typeRTYPE::type, const
Rcpp::VectorBaseRTYPE, NA, VECTOR) [with int RTYPE = 14, bool NA =
true, T = Rcpp::Vector14]

test2 = cxxfunction(, '
NumericVector tmpd(10, 2.0);
ComplexVector tmpc = tmpd;
return(tmpc);
 ', plugin='Rcpp')


file5b2fd8b.cpp:31: error: conversion from ‘Rcpp::NumericVector’ to
non-scalar type ‘Rcpp::ComplexVector’ requested

test3 = cxxfunction(, '
ComplexVector tmpc(10, 0.0);
return(tmpc);
 ', plugin='Rcpp')

  Compilation ERROR, function(s)/method(s) not created!
/home/xian/R/x86_64-pc-linux-gnu-library/2.8/Rcpp/include/Rcpp/internal/caster.h:
In function ‘TO Rcpp::internal::caster(FROM) [with FROM = double, TO =
Rcomplex]’:

Workaround:

test2works = cxxfunction(, '
NumericVector tmpd(10, 2.0);
int nn = tmpd.size();
ComplexVector tmpc(nn);
Rcomplex rc;
rc.r = rc.i = 0;
for (int i = 0; inn; i++ ) {
  rc.r = tmpd[i];
  tmpc[i] = rc  ;
}
return(tmpc);
 ', plugin='Rcpp')


A bit of background - an excerpt of the code that orginaly worked was:

ComplexVector CwtScale(ComplexVector FreqSignal, double centralFreq,
int moments, double scale, int signalSize, pwavefun waveletFun,
ComplexVector *FreqWavelet )
{
  *FreqWavelet = waveletFun(centralFreq, moments, scale, signalSize);
   ...
}

waveletFun returns a NumericVector, but *FreqWavelet is multiplied by
the ComplexVector FreqSignal.  So, either test1 or test2 would work
here. Does a working double-R caster (test3) fix test2?  I can update
unit tests accordingly.

thanks,
Christian
___
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


  1   2   >