Skip to main content

code review - Performance on Binomial Deviate is slow


I hope I won't get spanked for reposting. This is related to a previous question discussed here: Performance on Multinomial Deviate is slow.


but this version is simpler because it is a binomial rather than multinomial which is my justification for the new question.


I've kluged together a real solution for this problem that someone might find useful. I'm hoping someone will improve on the readability and/or performance. The performance is acceptable but still a bit slow compared to C. I think there might be another factor of 2 or 3 speedup to be had. My question is: does anyone have suggestions that will improve on my solution?


The problem is that I need a bunch of deviates where the parameters of the distribution are different for each deviate. Here is the simple way to do it which is unacceptably slow.


Nboxes = 8000;

p = RandomReal[{0, .01}, Nboxes];
rt = RandomInteger[{0, 10}, Nboxes];
rp = RandomInteger[{0, 10}, Nboxes];
probs = 1 - p rp;
out = MapThread[
RandomVariate[BinomialDistribution[#1, #2]] &, {rt, probs}]; // Timing

The timing result was over 4.7 seconds on my laptop. I create one below that is about 25 times faster.


Now to generate a binomial deviate with parameters n and p you generate n uniform deviates on (0,1) and count how many are < p. The total number of uniform deviates needed then is Total[rt]. Those can be generated in a small fraction of a second. The following code implements a binomial deviate generator and runs in a total of under 0.2 seconds. The deviates are stored in "counts". If anyone can improve on this code for performance, readability, etc, I'm all ears. First I generate all the uniform deviates I need. Then I "box" those up according to what rt is and count the number of deviates in each partition that are less than that boxes p value.


unitdeviates = RandomReal[1, Total[rt]]; // Timing

nt = ConstantArray[0, Nboxes + 1];
Table[nt[[i]] = nt[[i - 1]] + rt[[i - 1]], {i, 2, Length[rt] + 1}]; // Timing

counts = ConstantArray[0, Nboxes];
Do[counts[[nboxes]] = Count[unitdeviates[[nt[[nboxes]] + 1 ;;
nt[[nboxes + 1]]]], _?(# < probs[[nboxes]] &)], {nboxes, 1,Nboxes}] // Timing

Here I show that the mean and variance of the two sets of deviates are consistent


N[Mean[out]]
N[Mean[counts]]

N[Variance[out]]
N[Variance[counts]]

Answer



The main thing that I am trying to show is that you can use Accumulate and that almost all these functions are compilable. I hope it also shows when to use Table rather than Do, to avoid making unnecessary ConstantArrays. I personally find the use of Table in your code confusing. Of course it is nice to localise variables from time to time, which is also done in this code. All in all it is pretty boring code and maybe it looks a lot like what you have written in C, but I hope you learn something anyway.


In the code below, there is quite a lot of code to define a single function. There are multiple ways to avoid this, for example calling other CompiledFunctions inside the CompiledFunction. Another way is to inline definitions, which can also be done in multiple ways. For simplicity, I have just dumped everything in one definition.


cfu =
Compile[{{nBoxes, _Integer, 0}},
Block[
{unifs, rt, min, max, acc, count, p, rp, probs}
,

rt = RandomInteger[{0, 10}, nBoxes];

acc = Accumulate[rt];

unifs = RandomReal[1., acc[[-1]]];

p = RandomReal[{0., .01}, nBoxes];
rp = RandomInteger[{0, 10}, nBoxes];
probs = 1 - p rp;


min = 1;

Table[
max = acc[[nb]];

count = 0;
Do[
If[
unifs[[j]] < probs[[nb]]
,

count++
]
,
{j, min, max}
];

min = max + 1;
count
,
{nb, 1, nBoxes}

]

]
,
CompilationTarget -> "C"
]

Let's also make definitions to compare this with your code


yourInit :=
(

Nboxes = 8000;
p = RandomReal[{0, .01}, Nboxes];
rt = RandomInteger[{0, 10}, Nboxes];
rp = RandomInteger[{0, 10}, Nboxes];
probs = 1 - p rp;
)

yours1 :=
(
yourInit;

out = MapThread[
RandomVariate[BinomialDistribution[#1, #2]] &, {rt, probs}];
);

yours2 :=
(
yourInit;
unitdeviates = RandomReal[1, Total[rt]];
nt = ConstantArray[0, Nboxes + 1];
Table[nt[[i]] = nt[[i - 1]] + rt[[i - 1]], {i, 2, Length[rt] + 1}];


counts = ConstantArray[0, Nboxes];
Do[counts[[nboxes]] =
Count[unitdeviates[[nt[[nboxes]] + 1 ;;
nt[[nboxes + 1]]]], _?(# < probs[[nboxes]] &)], {nboxes, 1,
Nboxes}]
)

We then have


yours1 // Timing // First

Mean[out] // N
Variance[out] // N


3.770396  
4.85013
9.70163

yours2 // Timing // First
Mean[counts] // N

Variance[counts] // N


0.132868  
4.8515
9.53689

(res = cfu[8000]) // Timing // First
Mean@res // N
Variance@res // N



0.002822  
4.87888
9.66966

So the speedup is similar to your own C code. Using LibraryLink we should be able to do a little bit better.


Comments

Popular posts from this blog

plotting - How to draw lines between specified dots on ListPlot?

I would like to create a plot where I have unconnected dots and some connected. So far, I have figured out how to draw the dots. My code is the following: ListPlot[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4,13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full] I have thought using ListLinePlot command, but I don't know how to specify to the command to draw only selected lines between the dots. Do have any suggestions/hints on how to do that? Thank you. Answer One possibility would be to use Epilog with Line : ListPlot[ {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4, 13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full, Epilog -> { Line[ ...

equation solving - Invert and fit implicitly defined curve

I need to fit an implicitly defined curve. I thought I could get some data out of Solve , and then using FindFit . Therefore, I would like to find the relation the parametric curve defined by $F(x,y)=0$: Solve[-(1/2) + 1/2 (0.41202 BesselK[0, 0.1 Sqrt[x^2 + y^2]] + (0.101483 x BesselK[1, 0.1 Sqrt[x^2 + y^2]])/Sqrt[x^2 + y^2]) == 0, y] But I can't get an output: Solve was unable to solve the system with inexact coefficients or the system obtained by direct rationalization of inexact numbers present in the system. Since many of the methods used by Solve require exact input, providing Solve with an exact version of the system may help. >> Edit: In particular, I would like to fit the data coming from the curve with the expression of another curve, and not with a function $f(x)$. In particular, since this clearly looks like a cardioid , I would like it to fit to something like it. What other strategies could I try?

dynamic - How can I make a clickable ArrayPlot that returns input?

I would like to create a dynamic ArrayPlot so that the rectangles, when clicked, provide the input. Can I use ArrayPlot for this? Or is there something else I should have to use? Answer ArrayPlot is much more than just a simple array like Grid : it represents a ranged 2D dataset, and its visualization can be finetuned by options like DataReversed and DataRange . These features make it quite complicated to reproduce the same layout and order with Grid . Here I offer AnnotatedArrayPlot which comes in handy when your dataset is more than just a flat 2D array. The dynamic interface allows highlighting individual cells and possibly interacting with them. AnnotatedArrayPlot works the same way as ArrayPlot and accepts the same options plus Enabled , HighlightCoordinates , HighlightStyle and HighlightElementFunction . data = {{Missing["HasSomeMoreData"], GrayLevel[ 1], {RGBColor[0, 1, 1], RGBColor[0, 0, 1], GrayLevel[1]}, RGBColor[0, 1, 0]}, {GrayLevel[0], GrayLevel...