From ccberry @ending from uc@d@edu  Thu May 31 19:09:04 2018
From: ccberry @ending from uc@d@edu (Berry, Charles)
Date: Thu, 31 May 2018 17:09:04 +0000
Subject: [Rd] 
 Understanding the sequence of events when calling the R dpois
 function
In-Reply-To: <655E5620-4258-4EF7-BD65-ECAB12A748AB@ki.se>
References: <655E5620-4258-4EF7-BD65-ECAB12A748AB@ki.se>
Message-ID: <8474A4D9-4F38-4270-82DC-747B7C47BE3D@ucsd.edu>



> On May 31, 2018, at 8:25 AM, Jason Serviss <jason.serviss at ki.se> wrote:
> 
> Hello all,
> 
> I am trying to get a better understanding of the underlying code for the stats::dpois function in R and, specifically, what happens under the hood when it is called. I finally managed to track down the C course at: https://github.com/wch/r-source/blob/trunk/src/nmath/dpois.c. It would seem that the dpois C function is taking a double for each of the x and lambda arguments so I am a bit confused why I can provide a vector and matrix to dpois in R, e.g.
> 
> dpois(1:5, matrix(runif(2*5, 1, 10), nrow = 5)))
> 
> and get a matrix back with the results. Due to this, I was expecting to see a loop, or similar, in the underlying C source but? to no avail. So I have to conclude that either a) there is a step between when I call dpois in R and the C code getting executed that loops over the inputs or b) that there is a construct in the C code (my proficiency here is limited) that is called per input. Any help in enlightening me on what code is responsible for iterating over the multiple inputs (or if someone is feeling energetic, the exact stepwise code that is executed when calling dpois) would be greatly appreciated!!

Have a look at arithmetic.c. The math2 function handles calling dpois in a vectorized fashion.  

You need to trace how it is that the compiler knows to use dpois.c in constructing `C_dpois' which is what the R function dpois is calling.

If you know how to grep the sources for dpois, that will get you started. You will need to look over a bunch of #define's and a few C utilities to see how it all fits together. 

If you dig in and find the `do { ... } while(0)' construct confusing you might look at

https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for

HTH,

Chuck


[Rd] Understanding the sequence of events when calling the R dpois function
Berry, Charles