pomp
Inference for partially observed Markov processes
All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
resample.c
Go to the documentation of this file.
1// -*- C++ -*-
2
3#include <Rdefines.h>
4#include "internal.h"
5
6SEXP systematic_resampling(SEXP weights, SEXP np);
7void nosort_resamp(int nw, double *w, int np, int *p, int offset);
8
9SEXP systematic_resampling (SEXP weights, SEXP np)
10{
11 int m, n;
12 SEXP perm;
13
14 m = *(INTEGER(AS_INTEGER(np)));
15 n = LENGTH(weights);
16 PROTECT(perm = NEW_INTEGER(m));
17 PROTECT(weights = AS_NUMERIC(weights));
18 GetRNGstate();
19 nosort_resamp(n,REAL(weights),m,INTEGER(perm),1);
20 PutRNGstate();
21 UNPROTECT(2);
22 return(perm);
23}
24
25void nosort_resamp (int nw, double *w, int np, int *p, int offset)
26{
27 int i, j;
28 double du, u;
29
30 for (j = 1; j < nw; j++) w[j] += w[j-1];
31
32 if (w[nw-1] <= 0.0)
33 err("in 'systematic_resampling': non-positive sum of weights");
34
35 du = w[nw-1] / ((double) np);
36 u = -du*unif_rand();
37
38 for (i = 0, j = 0; j < np; j++) {
39 u += du;
40 // In the following line, the second test is needed to correct
41 // the infamous Bug of St. Patrick, 2017-03-17.
42 while ((u > w[i]) && (i < nw-1)) i++;
43 p[j] = i;
44 }
45 if (offset) // add offset if needed
46 for (j = 0; j < np; j++) p[j] += offset;
47
48}
#define err(...)
Definition pomp.h:21
void nosort_resamp(int nw, double *w, int np, int *p, int offset)
Definition resample.c:25
SEXP systematic_resampling(SEXP weights, SEXP np)
Definition resample.c:9