/*
* Roby Joehanes
*
* Copyright 2007 Roby Joehanes
* This file is distributed under the GNU General Public License version 3.0.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package jdistlib.rng;
/**
* Space and time efficiently computes a sorted Simple Random Sample Without Replacement (SRSWOR), that is, a sorted set of n random numbers from an interval of N numbers;
* Example: Computing n=3 random numbers from the interval [1,50] may yield the sorted random set (7,13,47).
* Since we are talking about a set (sampling without replacement), no element will occur more than once.
* Each number from the N numbers has the same probability to be included in the n chosen numbers.
*
* Problem: This class solves problems including the following:
* Suppose we have a file containing 10^12 objects.
* We would like to take a truly random subset of 10^6 objects and do something with it,
* for example, compute the sum over some instance field, or whatever.
* How do we choose the subset? In particular, how do we avoid multiple equal elements? How do we do this quick and without consuming excessive memory? How do we avoid slowly jumping back and forth within the file?
*
*
Sorted Simple Random Sample Without Replacement (SRSWOR):
* What are the exact semantics of this class? What is a SRSWOR? In which sense exactly is a returned set "random"?
* It is random in the sense, that each number from the N numbers has the same probability to be included in the n chosen numbers.
* For those who think in implementations rather than abstract interfaces:
* Suppose, we have an empty list.
* We pick a random number between 1 and 10^12 and add it to the list only if it was not already picked before, i.e. if it is not already contained in the list.
* We then do the same thing again and again until we have eventually collected 10^6 distinct numbers.
* Now we sort the set ascending and return it.
*
It is exactly in this sense that this class returns "random" sets.
* Note, however, that the implementation of this class uses a technique orders of magnitudes better (both in time and space) than the one outlined above.
*
* Performance: Space requirements are zero. Running time is O(n) on average, O(N) in the worst case.
*
Performance (200Mhz Pentium Pro, JDK 1.2, NT)
*
*
*
* n
* N
* Speed [seconds]
*
*
* 103
* 1.2*103
* 0.0014
*
*
* 103
* 107
* 0.006
*
*
* 105
* 107
* 0.7
*
*
* 9.0*106
* 107
* 8.5
*
*
* 9.9*106
* 107
* 2.0 (samples more than 95%)
*
*
* 104
* 1012
* 0.07
*
*
* 107
* 1012
* 60
*
*
*
*
* Scalability: This random sampler is designed to be scalable. In iterator style, it is able to compute and deliver sorted random sets stepwise in units called blocks.
* Example: Computing n=9 random numbers from the interval [1,50] in 3 blocks may yield the blocks (7,13,14), (27,37,42), (45,46,49).
* (The maximum of a block is guaranteed to be less than the minimum of its successor block. Every block is sorted ascending. No element will ever occur twice, both within a block and among blocks.)
* A block can be computed and retrieved with method nextBlock.
* Successive calls to method nextBlock will deliver as many random numbers as required.
*
*
Computing and retrieving samples in blocks is useful if you need very many random numbers that cannot be stored in main memory at the same time.
* For example, if you want to compute 10^10 such numbers you can do this by computing them in blocks of, say, 500 elements each.
* You then need only space to keep one block of 500 elements (i.e. 4 KB).
* When you are finished processing the first 500 elements you call nextBlock to fill the next 500 elements into the block, process them, and so on.
* If you have the time and need, by using such blocks you can compute random sets up to n=10^19 random numbers.
*
*
If you do not need the block feature, you can also directly call
* the static methods of this class without needing to construct a RandomSampler instance first.
*
*
Random number generation: By default uses MersenneTwister, a very strong random number generator, much better than java.util.Random.
* You can also use other strong random number generators of Paul Houle's RngPack package.
* For example, Ranecu, Ranmar and Ranlux are strong well analyzed research grade pseudo-random number generators with known periods.
*
*
Implementation: after J.S. Vitter, An Efficient Algorithm for Sequential Random Sampling,
* ACM Transactions on Mathematical Software, Vol 13, 1987.
* Paper available here.
*
* @author wolfgang.hoschek@cern.ch
* @version 1.1 05/26/99
*/
public class RandomSampler {
//public class RandomSampler extends Object implements java.io.Serializable {
long my_n;
long my_N;
long my_low;
RandomEngine my_RandomGenerator;
//static long negalphainv; // just to determine once and for all the best value for negalphainv
/**
* Constructs a random sampler that computes and delivers sorted random sets in blocks.
* A set block can be retrieved with method nextBlock.
* Successive calls to method nextBlock will deliver as many random numbers as required.
*
* @param n the total number of elements to choose (must be n >= 0 and n <= N).
* @param N the interval to choose random numbers from is [low,low+N-1].
* @param low the interval to choose random numbers from is [low,low+N-1]. Hint: If low==0, then random numbers will be drawn from the interval [0,N-1].
* @param randomGenerator a random number generator. Set this parameter to null to use the default random number generator.
*/
public RandomSampler(long n, long N, long low, RandomEngine randomGenerator) {
if (n<0) throw new IllegalArgumentException("n must be >= 0");
if (n>N) throw new IllegalArgumentException("n must by <= N");
this.my_n=n;
this.my_N=N;
this.my_low=low;
if (randomGenerator==null) randomGenerator = new MersenneTwister();
this.my_RandomGenerator=randomGenerator;
}
/**
* Computes the next count random numbers of the sorted random set specified on instance construction
* and fills them into values, starting at index fromIndex.
*
*
Numbers are filled into the specified array starting at index fromIndex to the right.
* The array is returned sorted ascending in the range filled with numbers.
*
* @param count the number of elements to be filled into values by this call (must be >= 0).
* @param values the array into which the random numbers are to be filled; must have a length >= count+fromIndex.
* @param fromIndex the first index within values to be filled with numbers (inclusive).
*/
public void nextBlock(int count, long[] values, int fromIndex) {
if (count > my_n) throw new IllegalArgumentException("Random sample exhausted.");
if (count < 0) throw new IllegalArgumentException("Negative count.");
if (count==0) return; //nothing to do
sample(my_n,my_N,count,my_low,values,fromIndex,my_RandomGenerator);
long lastSample=values[fromIndex+count-1];
my_n -= count;
my_N = my_N - lastSample - 1 + my_low ;
my_low = lastSample+1;
}
/**
* Efficiently computes a sorted random set of count elements from the interval [low,low+N-1].
* Since we are talking about a random set, no element will occur more than once.
*
*
Running time is O(count), on average. Space requirements are zero.
*
*
Numbers are filled into the specified array starting at index fromIndex to the right.
* The array is returned sorted ascending in the range filled with numbers.
*
* @param n the total number of elements to choose (must be >= 0).
* @param N the interval to choose random numbers from is [low,low+N-1].
* @param count the number of elements to be filled into values by this call (must be >= 0 and <=n). Normally, you will set count=n.
* @param low the interval to choose random numbers from is [low,low+N-1]. Hint: If low==0, then draws random numbers from the interval [0,N-1].
* @param values the array into which the random numbers are to be filled; must have a length >= count+fromIndex.
* @param fromIndex the first index within values to be filled with numbers (inclusive).
* @param randomGenerator a random number generator.
*/
protected static void rejectMethodD(long n, long N, int count, long low, long[] values, int fromIndex, RandomEngine randomGenerator) {
/* This algorithm is applicable if a large percentage (90%..100%) of N shall be sampled.
In such cases it is more efficient than sampleMethodA() and sampleMethodD().
The idea is that it is more efficient to express
sample(n,N,count) in terms of reject(N-n,N,count)
and then invert the result.
For example, sampling 99% turns into sampling 1% plus inversion.
This algorithm is the same as method sampleMethodD(...) with the exception that sampled elements are rejected, and not sampled elements included in the result set.
*/
n = N-n; // IMPORTANT !!!
double nreal, Nreal, ninv, nmin1inv, U, X, Vprime, y1, y2, top, bottom, negSreal, qu1real;
long qu1, t, limit;
//long threshold;
long S;
long chosen = -1+low;
//long negalphainv = -13; //tuning paramter, determines when to switch from method D to method A. Dependent on programming language, platform, etc.
nreal = n; ninv = 1.0/nreal; Nreal = N;
Vprime = Math.exp(Math.log(randomGenerator.nextDouble())*ninv);
qu1 = -n + 1 + N; qu1real = -nreal + 1.0 + Nreal;
//threshold = -negalphainv * n;
while (n>1 && count>0) { //&& thresholdS) {
bottom = -nreal + Nreal; limit = -S+N;
}
else {
bottom = -1.0 + negSreal + Nreal; limit=qu1;
}
for (t=N-1; t>=limit; t--) {
y2 = (y2*top)/bottom;
top--;
bottom--;
}
if (Nreal/(-X+Nreal) >= y1*Math.exp(Math.log(y2)*nmin1inv)) {
// accept !
Vprime = Math.exp(Math.log(randomGenerator.nextDouble())*nmin1inv);
break; //break inner loop
}
Vprime = Math.exp(Math.log(randomGenerator.nextDouble())*ninv);
} //end for
//step D5: reject the (S+1)st record !
int iter = count; //int iter = (int) (Math.min(S,count));
if (S= 0 ;) values[fromIndex++] = ++chosen;
chosen++;
N -= S+1; Nreal=negSreal+(-1.0+Nreal);
n--; nreal--; ninv = nmin1inv;
qu1 = -S+qu1; qu1real = negSreal+qu1real;
//threshold += negalphainv;
} //end while
if (count>0) { //special case n==1
//reject the (S+1)st record !
S = (long) (N*Vprime);
int iter = count; //int iter = (int) (Math.min(S,count));
if (S= 0 ;) values[fromIndex++] = ++chosen;
chosen++;
// fill the rest
for (; --count >= 0; ) values[fromIndex++] = ++chosen;
}
}
/**
* Efficiently computes a sorted random set of count elements from the interval [low,low+N-1].
* Since we are talking about a random set, no element will occur more than once.
*
* Running time is O(count), on average. Space requirements are zero.
*
*
Numbers are filled into the specified array starting at index fromIndex to the right.
* The array is returned sorted ascending in the range filled with numbers.
*
*
Random number generation: By default uses MersenneTwister, a very strong random number generator, much better than java.util.Random.
* You can also use other strong random number generators of Paul Houle's RngPack package.
* For example, Ranecu, Ranmar and Ranlux are strong well analyzed research grade pseudo-random number generators with known periods.
*
* @param n the total number of elements to choose (must be n >= 0 and n <= N).
* @param N the interval to choose random numbers from is [low,low+N-1].
* @param count the number of elements to be filled into values by this call (must be >= 0 and <=n). Normally, you will set count=n.
* @param low the interval to choose random numbers from is [low,low+N-1]. Hint: If low==0, then draws random numbers from the interval [0,N-1].
* @param values the array into which the random numbers are to be filled; must have a length >= count+fromIndex.
* @param fromIndex the first index within values to be filled with numbers (inclusive).
* @param randomGenerator a random number generator. Set this parameter to null to use the default random number generator.
*/
public static void sample(long n, long N, int count, long low, long[] values, int fromIndex, RandomEngine randomGenerator) {
if (n<=0 || count<=0) return;
if (count>n) throw new IllegalArgumentException("count must not be greater than n");
if (randomGenerator==null) randomGenerator = new MersenneTwister();
if (count==N) { // rare case treated quickly
long val = low;
int limit= fromIndex+count;
for (int i=fromIndex; imaxTmpMemoryAllowed) {
sampleMethodD(n,N,count,low,values,fromIndex,randomGenerator);
}
else { // More than 95% of all numbers shall be sampled.
rejectMethodD(n,N,count,low,values,fromIndex,randomGenerator);
}
}
/**
* Computes a sorted random set of count elements from the interval [low,low+N-1].
* Since we are talking about a random set, no element will occur more than once.
*
* Running time is O(N), on average. Space requirements are zero.
*
*
Numbers are filled into the specified array starting at index fromIndex to the right.
* The array is returned sorted ascending in the range filled with numbers.
*
* @param n the total number of elements to choose (must be >= 0).
* @param N the interval to choose random numbers from is [low,low+N-1].
* @param count the number of elements to be filled into values by this call (must be >= 0 and <=n). Normally, you will set count=n.
* @param low the interval to choose random numbers from is [low,low+N-1]. Hint: If low==0, then draws random numbers from the interval [0,N-1].
* @param values the array into which the random numbers are to be filled; must have a length >= count+fromIndex.
* @param fromIndex the first index within values to be filled with numbers (inclusive).
* @param randomGenerator a random number generator.
*/
protected static void sampleMethodA(long n, long N, int count, long low, long[] values, int fromIndex, RandomEngine randomGenerator) {
double V, quot, Nreal, top;
long S;
long chosen = -1+low;
top = N-n;
Nreal = N;
while (n>=2 && count>0) {
V = randomGenerator.nextDouble();
S = 0;
quot = top/Nreal;
while (quot > V) {
S++;
top--;
Nreal--;
quot = (quot*top)/Nreal;
}
chosen += S+1;
values[fromIndex++]=chosen;
count--;
Nreal--;
n--;
}
if (count>0) {
// special case n==1
S = (long) (Math.round(Nreal) * randomGenerator.nextDouble());
chosen += S+1;
values[fromIndex]=chosen;
}
}
/**
* Efficiently computes a sorted random set of count elements from the interval [low,low+N-1].
* Since we are talking about a random set, no element will occur more than once.
*
*
Running time is O(count), on average. Space requirements are zero.
*
*
Numbers are filled into the specified array starting at index fromIndex to the right.
* The array is returned sorted ascending in the range filled with numbers.
*
* @param n the total number of elements to choose (must be >= 0).
* @param N the interval to choose random numbers from is [low,low+N-1].
* @param count the number of elements to be filled into values by this call (must be >= 0 and <=n). Normally, you will set count=n.
* @param low the interval to choose random numbers from is [low,low+N-1]. Hint: If low==0, then draws random numbers from the interval [0,N-1].
* @param values the array into which the random numbers are to be filled; must have a length >= count+fromIndex.
* @param fromIndex the first index within values to be filled with numbers (inclusive).
* @param randomGenerator a random number generator.
*/
protected static void sampleMethodD(long n, long N, int count, long low, long[] values, int fromIndex, RandomEngine randomGenerator) {
double nreal, Nreal, ninv, nmin1inv, U, X, Vprime, y1, y2, top, bottom, negSreal, qu1real;
long qu1, threshold, t, limit;
long S;
long chosen = -1+low;
long negalphainv = -13; //tuning paramter, determines when to switch from method D to method A. Dependent on programming language, platform, etc.
nreal = n; ninv = 1.0/nreal; Nreal = N;
Vprime = Math.exp(Math.log(randomGenerator.nextDouble())*ninv);
qu1 = -n + 1 + N; qu1real = -nreal + 1.0 + Nreal;
threshold = -negalphainv * n;
while (n>1 && count>0 && thresholdS) {
bottom = -nreal + Nreal; limit = -S+N;
}
else {
bottom = -1.0 + negSreal + Nreal; limit=qu1;
}
for (t=N-1; t>=limit; t--) {
y2 = (y2*top)/bottom;
top--;
bottom--;
}
if (Nreal/(-X+Nreal) >= y1*Math.exp(Math.log(y2)*nmin1inv)) {
// accept !
Vprime = Math.exp(Math.log(randomGenerator.nextDouble())*nmin1inv);
break; //break inner loop
}
Vprime = Math.exp(Math.log(randomGenerator.nextDouble())*ninv);
} //end for
//step D5: select the (S+1)st record !
chosen += S+1;
values[fromIndex++] = chosen;
/*
// invert
for (int iter=0; iter 0; iter++) {
values[fromIndex++] = ++chosen;
count--;
}
chosen++;
*/
count--;
N -= S+1; Nreal=negSreal+(-1.0+Nreal);
n--; nreal--; ninv = nmin1inv;
qu1 = -S+qu1; qu1real = negSreal+qu1real;
threshold += negalphainv;
} //end while
if (count>0) {
if (n>1) { //faster to use method A to finish the sampling
sampleMethodA(n,N,count,chosen+1,values,fromIndex,randomGenerator);
}
else {
//special case n==1
S = (long) (N*Vprime);
chosen += S+1;
values[fromIndex++] = chosen;
}
}
}
}
Ads help maintain this website.