PostgreSQL Source Code  git master
sampling.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * sampling.c
4  * Relation block sampling routines.
5  *
6  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/utils/misc/sampling.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include <math.h>
19 
20 #include "utils/sampling.h"
21 
22 
23 /*
24  * BlockSampler_Init -- prepare for random sampling of blocknumbers
25  *
26  * BlockSampler provides algorithm for block level sampling of a relation
27  * as discussed on pgsql-hackers 2004-04-02 (subject "Large DB")
28  * It selects a random sample of samplesize blocks out of
29  * the nblocks blocks in the table. If the table has less than
30  * samplesize blocks, all blocks are selected.
31  *
32  * Since we know the total number of blocks in advance, we can use the
33  * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
34  * algorithm.
35  *
36  * Returns the number of blocks that BlockSampler_Next will return.
37  */
39 BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize,
40  long randseed)
41 {
42  bs->N = nblocks; /* measured table size */
43 
44  /*
45  * If we decide to reduce samplesize for tables that have less or not much
46  * more than samplesize blocks, here is the place to do it.
47  */
48  bs->n = samplesize;
49  bs->t = 0; /* blocks scanned so far */
50  bs->m = 0; /* blocks selected so far */
51 
52  sampler_random_init_state(randseed, bs->randstate);
53 
54  return Min(bs->n, bs->N);
55 }
56 
57 bool
59 {
60  return (bs->t < bs->N) && (bs->m < bs->n);
61 }
62 
65 {
66  BlockNumber K = bs->N - bs->t; /* remaining blocks */
67  int k = bs->n - bs->m; /* blocks still to sample */
68  double p; /* probability to skip block */
69  double V; /* random */
70 
71  Assert(BlockSampler_HasMore(bs)); /* hence K > 0 and k > 0 */
72 
73  if ((BlockNumber) k >= K)
74  {
75  /* need all the rest */
76  bs->m++;
77  return bs->t++;
78  }
79 
80  /*----------
81  * It is not obvious that this code matches Knuth's Algorithm S.
82  * Knuth says to skip the current block with probability 1 - k/K.
83  * If we are to skip, we should advance t (hence decrease K), and
84  * repeat the same probabilistic test for the next block. The naive
85  * implementation thus requires a sampler_random_fract() call for each
86  * block number. But we can reduce this to one sampler_random_fract()
87  * call per selected block, by noting that each time the while-test
88  * succeeds, we can reinterpret V as a uniform random number in the range
89  * 0 to p. Therefore, instead of choosing a new V, we just adjust p to be
90  * the appropriate fraction of its former value, and our next loop
91  * makes the appropriate probabilistic test.
92  *
93  * We have initially K > k > 0. If the loop reduces K to equal k,
94  * the next while-test must fail since p will become exactly zero
95  * (we assume there will not be roundoff error in the division).
96  * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
97  * to be doubly sure about roundoff error.) Therefore K cannot become
98  * less than k, which means that we cannot fail to select enough blocks.
99  *----------
100  */
102  p = 1.0 - (double) k / (double) K;
103  while (V < p)
104  {
105  /* skip */
106  bs->t++;
107  K--; /* keep K == N - t */
108 
109  /* adjust p to be new cutoff point in reduced range */
110  p *= 1.0 - (double) k / (double) K;
111  }
112 
113  /* select */
114  bs->m++;
115  return bs->t++;
116 }
117 
118 /*
119  * These two routines embody Algorithm Z from "Random sampling with a
120  * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
121  * (Mar. 1985), Pages 37-57. Vitter describes his algorithm in terms
122  * of the count S of records to skip before processing another record.
123  * It is computed primarily based on t, the number of records already read.
124  * The only extra state needed between calls is W, a random state variable.
125  *
126  * reservoir_init_selection_state computes the initial W value.
127  *
128  * Given that we've already read t records (t >= n), reservoir_get_next_S
129  * determines the number of records to skip before the next record is
130  * processed.
131  */
132 void
134 {
135  /*
136  * Reservoir sampling is not used anywhere where it would need to return
137  * repeatable results so we can initialize it randomly.
138  */
140 
141  /* Initial value of W (for use when Algorithm Z is first applied) */
142  rs->W = exp(-log(sampler_random_fract(rs->randstate)) / n);
143 }
144 
145 double
147 {
148  double S;
149 
150  /* The magic constant here is T from Vitter's paper */
151  if (t <= (22.0 * n))
152  {
153  /* Process records using Algorithm X until t is large enough */
154  double V,
155  quot;
156 
157  V = sampler_random_fract(rs->randstate); /* Generate V */
158  S = 0;
159  t += 1;
160  /* Note: "num" in Vitter's code is always equal to t - n */
161  quot = (t - (double) n) / t;
162  /* Find min S satisfying (4.1) */
163  while (quot > V)
164  {
165  S += 1;
166  t += 1;
167  quot *= (t - (double) n) / t;
168  }
169  }
170  else
171  {
172  /* Now apply Algorithm Z */
173  double W = rs->W;
174  double term = t - (double) n + 1;
175 
176  for (;;)
177  {
178  double numer,
179  numer_lim,
180  denom;
181  double U,
182  X,
183  lhs,
184  rhs,
185  y,
186  tmp;
187 
188  /* Generate U and X */
190  X = t * (W - 1.0);
191  S = floor(X); /* S is tentatively set to floor(X) */
192  /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
193  tmp = (t + 1) / term;
194  lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
195  rhs = (((t + X) / (term + S)) * term) / t;
196  if (lhs <= rhs)
197  {
198  W = rhs / lhs;
199  break;
200  }
201  /* Test if U <= f(S)/cg(X) */
202  y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
203  if ((double) n < S)
204  {
205  denom = t;
206  numer_lim = term + S;
207  }
208  else
209  {
210  denom = t - (double) n + S;
211  numer_lim = t + 1;
212  }
213  for (numer = t + S; numer >= numer_lim; numer -= 1)
214  {
215  y *= numer / denom;
216  denom -= 1;
217  }
218  W = exp(-log(sampler_random_fract(rs->randstate)) / n); /* Generate W in advance */
219  if (exp(log(y) / n) <= (t + X) / t)
220  break;
221  }
222  rs->W = W;
223  }
224  return S;
225 }
226 
227 
228 /*----------
229  * Random number generator used by sampling
230  *----------
231  */
232 void
234 {
235  randstate[0] = 0x330e; /* same as pg_erand48, but could be anything */
236  randstate[1] = (unsigned short) seed;
237  randstate[2] = (unsigned short) (seed >> 16);
238 }
239 
240 /* Select a random value R uniformly distributed in (0 - 1) */
241 double
243 {
244  double res;
245 
246  /* pg_erand48 returns a value in [0.0 - 1.0), so we must reject 0 */
247  do
248  {
249  res = pg_erand48(randstate);
250  } while (res == 0.0);
251  return res;
252 }
253 
254 
255 /*
256  * Backwards-compatible API for block sampling
257  *
258  * This code is now deprecated, but since it's still in use by many FDWs,
259  * we should keep it for awhile at least. The functionality is the same as
260  * sampler_random_fract/reservoir_init_selection_state/reservoir_get_next_S,
261  * except that a common random state is used across all callers.
262  */
264 
265 double
267 {
268  /* initialize if first time through */
269  if (oldrs.randstate[0] == 0)
271 
272  /* and compute a random fraction */
273  return sampler_random_fract(oldrs.randstate);
274 }
275 
276 double
278 {
279  /* initialize if first time through */
280  if (oldrs.randstate[0] == 0)
282 
283  /* Initial value of W (for use when Algorithm Z is first applied) */
284  return exp(-log(sampler_random_fract(oldrs.randstate)) / n);
285 }
286 
287 double
288 anl_get_next_S(double t, int n, double *stateptr)
289 {
290  double result;
291 
292  oldrs.W = *stateptr;
293  result = reservoir_get_next_S(&oldrs, t, n);
294  *stateptr = oldrs.W;
295  return result;
296 }
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:58
void sampler_random_init_state(long seed, SamplerRandomState randstate)
Definition: sampling.c:233
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:64
long random(void)
Definition: random.c:22
#define Min(x, y)
Definition: c.h:910
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:242
uint32 BlockNumber
Definition: block.h:31
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:133
unsigned short SamplerRandomState[3]
Definition: sampling.h:20
static ReservoirStateData oldrs
Definition: sampling.c:263
BlockNumber t
Definition: sampling.h:33
#define W(n)
Definition: sha1.c:60
#define S(n, x)
Definition: sha1.c:55
BlockNumber BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, long randseed)
Definition: sampling.c:39
double anl_random_fract(void)
Definition: sampling.c:266
double pg_erand48(unsigned short xseed[3])
Definition: erand48.c:88
#define K(t)
Definition: sha1.c:48
#define Assert(condition)
Definition: c.h:728
BlockNumber N
Definition: sampling.h:31
double anl_get_next_S(double t, int n, double *stateptr)
Definition: sampling.c:288
double anl_init_selection_state(int n)
Definition: sampling.c:277
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:146
SamplerRandomState randstate
Definition: sampling.h:35