cern.jet.random.engine.RandomEngine Java Examples

The following examples show how to use cern.jet.random.engine.RandomEngine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DynamicBin1D.java    From jAudioGIT with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Uniformly samples (chooses) <tt>n</tt> random elements <i>with or without replacement</i> from the contained elements and adds them to the given buffer.
 * If the buffer is connected to a bin, the effect is that the chosen elements are added to the bin connected to the buffer.
 * Also see {@link #buffered(int) buffered}.
 *
 * @param n the number of elements to choose.
 * @param withReplacement <tt>true</tt> samples with replacement, otherwise samples without replacement.
 * @param randomGenerator a random number generator. Set this parameter to <tt>null</tt> to use a default random number generator seeded with the current time.
 * @param buffer the buffer to which chosen elements will be added.
 * @throws IllegalArgumentException if <tt>!withReplacement && n > size()</tt>.
 * @see cern.jet.random.sampling
 */
public synchronized void sample(int n, boolean withReplacement, RandomEngine randomGenerator, cern.colt.buffer.DoubleBuffer buffer) {
	if (randomGenerator==null) randomGenerator = cern.jet.random.Uniform.makeDefaultGenerator();
	buffer.clear();
	
	if (!withReplacement) { // without
		if (n>size()) throw new IllegalArgumentException("n must be less than or equal to size()");
		cern.jet.random.sampling.RandomSamplingAssistant sampler = new cern.jet.random.sampling.RandomSamplingAssistant(n,size(),randomGenerator);
		for (int i=n; --i >= 0; ) {
			if (sampler.sampleNextElement()) buffer.add(this.elements.getQuick(i));
		}
	}
	else { // with
		cern.jet.random.Uniform uniform = new cern.jet.random.Uniform(randomGenerator);
		int s = size();
		for (int i=n; --i >= 0; ) {
			buffer.add(this.elements.getQuick(uniform.nextIntFromTo(0,s-1)));
		}
	buffer.flush();
	}
}
 
Example #2
Source File: Statistic.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
Constructs and returns a sampling view with a size of <tt>round(matrix.size() * fraction)</tt>.
Samples "without replacement" from the uniform distribution.
@param matrix any matrix.
@param rowFraction the percentage of rows to be included in the view.
@param columnFraction the percentage of columns to be included in the view.
@param randomGenerator a uniform random number generator; set this parameter to <tt>null</tt> to use a default generator seeded with the current time.
@return the sampling view.
@throws IllegalArgumentException if <tt>! (0 <= rowFraction <= 1 && 0 <= columnFraction <= 1)</tt>.
@see cern.jet.random.sampling.RandomSampler
*/
public static DoubleMatrix1D viewSample(DoubleMatrix1D matrix, double fraction, RandomEngine randomGenerator) {
	// check preconditions and allow for a little tolerance
	double epsilon = 1e-09;
	if (fraction < 0 - epsilon || fraction > 1 + epsilon) throw new IllegalArgumentException();
	if (fraction < 0) fraction = 0;
	if (fraction > 1) fraction = 1;

	// random generator seeded with current time
	if (randomGenerator==null) randomGenerator = new cern.jet.random.engine.MersenneTwister((int) System.currentTimeMillis());

	int ncols = (int) Math.round(matrix.size() * fraction);
	int max = ncols;
	long[] selected = new long[max]; // sampler works on long's, not int's

	// sample 
	int n = ncols;
	int N = matrix.size();
	cern.jet.random.sampling.RandomSampler.sample(n,N,n,0,selected,0,randomGenerator);
	int[] selectedCols = new int[n];
	for (int i=0; i<n; i++) selectedCols[i] = (int) selected[i];

	return matrix.viewSelection(selectedCols);
}
 
Example #3
Source File: TestStochasticTopper.java    From streaminer with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeometricDistribution()
{
    RandomEngine re = RandomEngine.makeDefault();

    for (int i = 0; i < NUM_ITERATIONS; i++)
    {
        int z = Distributions.nextGeometric(0.25, re);
        vs.add(z);
    }

    List<CountEntry<Integer>> top = vs.peek(5);
    System.out.println("Geometric:");
    for (CountEntry<Integer> e : top)
    {
        System.out.println(e);
    }

    CountEntry<Integer> tippyTop = top.get(0);
    assertTrue(tippyTop.getItem() < 3);
}
 
Example #4
Source File: Distributions.java    From jAudioGIT with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns a zipfian distributed random number with the given skew.
 * <p>
 * Algorithm from page 551 of:
 * Devroye, Luc (1986) `Non-uniform random variate generation',
 * Springer-Verlag: Berlin.   ISBN 3-540-96305-7 (also 0-387-96305-7)
 *
 * @param z the skew of the distribution (must be &gt;1.0).
 * @returns a zipfian distributed number in the closed interval <tt>[1,Integer.MAX_VALUE]</tt>.
 */
public static int nextZipfInt(double z, RandomEngine randomGenerator) {	 
	/* Algorithm from page 551 of:
	 * Devroye, Luc (1986) `Non-uniform random variate generation',
	 * Springer-Verlag: Berlin.   ISBN 3-540-96305-7 (also 0-387-96305-7)
	 */
	final double b = Math.pow(2.0,z-1.0);
  	final double constant = -1.0/(z-1.0); 

  	int result=0;
	for (;;) {
		double u = randomGenerator.raw();
		double v = randomGenerator.raw();
		result = (int) (Math.floor(Math.pow(u,constant))); 
		double t = Math.pow(1.0 + 1.0/result, z-1.0);
		if (v*result*(t-1.0)/(b-1.0) <= t/b) break; 
	}
	return result;
}
 
Example #5
Source File: Distributions.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a random number from the standard Triangular distribution in (-1,1).
 * <p>
 * <b>Implementation:</b> Inversion method.
 * This is a port of <tt>tra.c</tt> from the <A HREF="http://www.cis.tu-graz.ac.at/stat/stadl/random.html">C-RAND / WIN-RAND</A> library.
 * <p>
 */
public static double nextTriangular(RandomEngine randomGenerator) {
/******************************************************************
 *                                                                *
 *     Triangular Distribution - Inversion: x = +-(1-sqrt(u))     *
 *                                                                *
 ******************************************************************
 *                                                                *
 * FUNCTION :   - tra samples a random number from the            *
 *                standard Triangular distribution in (-1,1)      *
 * SUBPROGRAM : - drand(seed) ... (0,1)-Uniform generator with    *
 *                unsigned long integer *seed.                    *
 *                                                                *
 ******************************************************************/

	double u;
	u=randomGenerator.raw();
	if (u<=0.5) return(Math.sqrt(2.0*u)-1.0);                      /* -1 <= x <= 0 */
	else return(1.0-Math.sqrt(2.0*(1.0-u)));                 /*  0 <= x <= 1 */
}
 
Example #6
Source File: Distributions.java    From jAudioGIT with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns a random number from the standard Triangular distribution in (-1,1).
 * <p>
 * <b>Implementation:</b> Inversion method.
 * This is a port of <tt>tra.c</tt> from the <A HREF="http://www.cis.tu-graz.ac.at/stat/stadl/random.html">C-RAND / WIN-RAND</A> library.
 * <p>
 */
public static double nextTriangular(RandomEngine randomGenerator) {
/******************************************************************
 *                                                                *
 *     Triangular Distribution - Inversion: x = +-(1-sqrt(u))     *
 *                                                                *
 ******************************************************************
 *                                                                *
 * FUNCTION :   - tra samples a random number from the            *
 *                standard Triangular distribution in (-1,1)      *
 * SUBPROGRAM : - drand(seed) ... (0,1)-Uniform generator with    *
 *                unsigned long integer *seed.                    *
 *                                                                *
 ******************************************************************/

	double u;
	u=randomGenerator.raw();
	if (u<=0.5) return(Math.sqrt(2.0*u)-1.0);                      /* -1 <= x <= 0 */
	else return(1.0-Math.sqrt(2.0*(1.0-u)));                 /*  0 <= x <= 1 */
}
 
Example #7
Source File: TestConcurrentStreamSummary.java    From streaminer with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeometricDistribution() {
    ConcurrentStreamSummary<Integer> vs = new ConcurrentStreamSummary<Integer>(10);
    RandomEngine re = RandomEngine.makeDefault();

    for (int i = 0; i < NUM_ITERATIONS; i++) {
        int z = Distributions.nextGeometric(0.25, re);
        vs.add(z);
    }

    List<CountEntry<Integer>> top = vs.peek(5);
    System.out.println("Geometric:");
    for (CountEntry<Integer> e : top) {
        System.out.println(e.getItem() + "\t" + e.getFrequency());
    }

    CountEntry<Integer> tippyTop = top.get(0);
    assertEquals(0, (int) tippyTop.getItem());
    System.out.println(vs);
}
 
Example #8
Source File: RandomSampler.java    From jAudioGIT with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Efficiently computes a sorted random set of <tt>count</tt> elements from the interval <tt>[low,low+N-1]</tt>.
 * Since we are talking about a random set, no element will occur more than once.
 *
 * <p>Running time is <tt>O(count)</tt>, on average. Space requirements are zero.
 *
 * <p>Numbers are filled into the specified array starting at index <tt>fromIndex</tt> to the right.
 * The array is returned sorted ascending in the range filled with numbers.
 *
 * <p><b>Random number generation:</b> By default uses <tt>MersenneTwister</tt>, a very strong random number generator, much better than <tt>java.util.Random</tt>.
 * You can also use other strong random number generators of Paul Houle's RngPack package.
 * For example, <tt>Ranecu</tt>, <tt>Ranmar</tt> and <tt>Ranlux</tt> are strong well analyzed research grade pseudo-random number generators with known periods.
 *
 * @param n the total number of elements to choose (must be <tt>n &gt;= 0</tt> and <tt>n &lt;= N</tt>).
 * @param N the interval to choose random numbers from is <tt>[low,low+N-1]</tt>.
 * @param count the number of elements to be filled into <tt>values</tt> by this call (must be &gt;= 0 and &lt;=<tt>n</tt>). Normally, you will set <tt>count=n</tt>.
 * @param low the interval to choose random numbers from is <tt>[low,low+N-1]</tt>. Hint: If <tt>low==0</tt>, then draws random numbers from the interval <tt>[0,N-1]</tt>.
 * @param values the array into which the random numbers are to be filled; must have a length <tt>&gt;= count+fromIndex</tt>.
 * @param fromIndex the first index within <tt>values</tt> to be filled with numbers (inclusive).
 * @param randomGenerator a random number generator. Set this parameter to <tt>null</tt> 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 = cern.jet.random.AbstractDistribution.makeDefaultGenerator();

	if (count==N) { // rare case treated quickly
		long val = low;
		int limit= fromIndex+count;
		for (int i=fromIndex; i<limit; ) values[i++] = val++;
		return;
	} 

	if (n<N*0.95) { // || Math.min(count,N-n)>maxTmpMemoryAllowed) {
		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);
	}
	
	
}
 
Example #9
Source File: Benchmark.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prints the first <tt>size</tt> random numbers generated by the distribution.
 */
public static void demo1() {
// Gamma distribution

// define distribution parameters
double mean = 5;
double variance = 1.5;
double alpha = mean*mean / variance; 
double lambda = 1 / (variance / mean); 

// for tests and debugging use a random engine with CONSTANT seed --> deterministic and reproducible results
cern.jet.random.engine.RandomEngine engine = new cern.jet.random.engine.MersenneTwister(); 

// your favourite distribution goes here
cern.jet.random.AbstractDistribution dist = new cern.jet.random.Gamma(alpha,lambda,engine);

// collect random numbers and print statistics
int size = 100000;
cern.colt.list.DoubleArrayList numbers = new cern.colt.list.DoubleArrayList(size);
for (int i=0; i < size; i++) numbers.add(dist.nextDouble());

//FIXME:  Should this test exist without hep.aida
//hep.aida.bin.DynamicBin1D bin = new hep.aida.bin.DynamicBin1D();
//bin.addAllOf(numbers);
//System.out.println(bin);
}
 
Example #10
Source File: TimerSample.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    Timer timer = Timer.builder("timer")
            .publishPercentileHistogram()
            .publishPercentiles(0.5, 0.95, 0.99)
            .serviceLevelObjectives(Duration.ofMillis(275), Duration.ofMillis(300), Duration.ofMillis(500))
            .distributionStatisticExpiry(Duration.ofSeconds(10))
            .distributionStatisticBufferLength(3)
            .register(registry);

    AtomicLong totalCount = new AtomicLong();
    AtomicLong totalTime = new AtomicLong();
    FunctionTimer.builder("ftimer", totalCount, t -> totalCount.get(), t -> totalTime.get(), TimeUnit.MILLISECONDS)
            .register(registry);

    RandomEngine r = new MersenneTwister64(0);
    Normal incomingRequests = new Normal(0, 1, r);
    Normal duration = new Normal(250, 50, r);

    AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
    Flux.interval(Duration.ofSeconds(1))
            .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
            .subscribe();

    // the potential for an "incoming request" every 10 ms
    Flux.interval(Duration.ofMillis(10))
            .doOnEach(d -> {
                if (incomingRequests.nextDouble() + 0.4 > 0) {
                    // pretend the request took some amount of time, such that the time is
                    // distributed normally with a mean of 250ms
                    int latency = latencyForThisSecond.get();
                    timer.record(latency, TimeUnit.MILLISECONDS);
                    totalTime.addAndGet(latency);
                    totalCount.incrementAndGet();
                }
            })
            .blockLast();
}
 
Example #11
Source File: RandomSamplingAssistant.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructs a random sampler that samples <tt>n</tt> random elements from an input sequence of <tt>N</tt> elements.
 *
 * @param n the total number of elements to choose (must be &gt;= 0).
 * @param N number of elements to choose from (must be &gt;= n).
 * @param randomGenerator a random number generator. Set this parameter to <tt>null</tt> to use the default random number generator.
 */
public RandomSamplingAssistant(long n, long N, RandomEngine randomGenerator) {
	this.n = n;
	this.sampler = new RandomSampler(n, N, 0, randomGenerator);
	this.buffer = new long[(int)Math.min(n,MAX_BUFFER_SIZE)];
	if (n>0) this.buffer[0] = -1; // start with the right offset
	
	fetchNextBlock();
}
 
Example #12
Source File: RandomSampler.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes a sorted random set of <tt>count</tt> elements from the interval <tt>[low,low+N-1]</tt>.
 * Since we are talking about a random set, no element will occur more than once.
 *
 * <p>Running time is <tt>O(N)</tt>, on average. Space requirements are zero.
 *
 * <p>Numbers are filled into the specified array starting at index <tt>fromIndex</tt> 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 &gt;= 0).
 * @param N the interval to choose random numbers from is <tt>[low,low+N-1]</tt>.
 * @param count the number of elements to be filled into <tt>values</tt> by this call (must be &gt;= 0 and &lt;=<tt>n</tt>). Normally, you will set <tt>count=n</tt>.
 * @param low the interval to choose random numbers from is <tt>[low,low+N-1]</tt>. Hint: If <tt>low==0</tt>, then draws random numbers from the interval <tt>[0,N-1]</tt>.
 * @param values the array into which the random numbers are to be filled; must have a length <tt>&gt;= count+fromIndex</tt>.
 * @param fromIndex the first index within <tt>values</tt> 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.raw();
		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.raw());
		chosen += S+1;
		values[fromIndex]=chosen;
	}
}
 
Example #13
Source File: Distributions.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns a discrete geometric distributed random number; <A HREF="http://www.statsoft.com/textbook/glosf.html#Geometric Distribution">Definition</A>.
 * <p>
 * <tt>p(k) = p * (1-p)^k</tt> for <tt> k &gt;= 0</tt>.
 * <p>
 * <b>Implementation:</b> Inversion method.
 * This is a port of <tt>geo.c</tt> from the <A HREF="http://www.cis.tu-graz.ac.at/stat/stadl/random.html">C-RAND / WIN-RAND</A> library.
 * @param p must satisfy <tt>0 &lt; p &lt; 1</tt>.
 * <p>
 */
public static int nextGeometric(double p, RandomEngine randomGenerator) {
/******************************************************************
 *                                                                *
 *              Geometric Distribution - Inversion                *
 *                                                                *
 ******************************************************************
 *                                                                *
 * On generating random numbers of a discrete distribution by     *
 * Inversion normally sequential search is necessary, but in the  *
 * case of the Geometric distribution a direct transformation is  *
 * possible because of the special parallel to the continuous     *
 * Exponential distribution Exp(t):                               *
 *    X - Exp(t): G(x)=1-exp(-tx)                                 *
 *        Geo(p): pk=G(k+1)-G(k)=exp(-tk)*(1-exp(-t))             *
 *                p=1-exp(-t)                                     *
 * A random number of the Geometric distribution Geo(p) is        *
 * obtained by k=(long int)x, where x is from Exp(t) with         *
 * parameter t=-log(1-p).                                         *
 *                                                                *
 ******************************************************************
 *                                                                *
 * FUNCTION:    - geo samples a random number from the Geometric  *
 *                distribution with parameter 0<p<1.              *
 * SUBPROGRAMS: - drand(seed) ... (0,1)-Uniform generator with    *
 *                unsigned long integer *seed.                    *
 *                                                                *
 ******************************************************************/
	double u = randomGenerator.raw();
	return (int)(Math.log(u)/Math.log(1.0-p));
}
 
Example #14
Source File: RandomSampler.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a random sampler that computes and delivers sorted random sets in blocks.
 * A set block can be retrieved with method <tt>nextBlock</tt>.
 * Successive calls to method <tt>nextBlock</tt> will deliver as many random numbers as required.
 *
 * @param n the total number of elements to choose (must be <tt>n &gt;= 0</tt> and <tt>n &lt;= N</tt>).
 * @param N the interval to choose random numbers from is <tt>[low,low+N-1]</tt>.
 * @param low the interval to choose random numbers from is <tt>[low,low+N-1]</tt>. Hint: If <tt>low==0</tt>, then random numbers will be drawn from the interval <tt>[0,N-1]</tt>.
 * @param randomGenerator a random number generator. Set this parameter to <tt>null</tt> 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 = cern.jet.random.AbstractDistribution.makeDefaultGenerator();
	this.my_RandomGenerator=randomGenerator;
}
 
Example #15
Source File: RandomSampler.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructs a random sampler that computes and delivers sorted random sets in blocks.
 * A set block can be retrieved with method <tt>nextBlock</tt>.
 * Successive calls to method <tt>nextBlock</tt> will deliver as many random numbers as required.
 *
 * @param n the total number of elements to choose (must be <tt>n &gt;= 0</tt> and <tt>n &lt;= N</tt>).
 * @param N the interval to choose random numbers from is <tt>[low,low+N-1]</tt>.
 * @param low the interval to choose random numbers from is <tt>[low,low+N-1]</tt>. Hint: If <tt>low==0</tt>, then random numbers will be drawn from the interval <tt>[0,N-1]</tt>.
 * @param randomGenerator a random number generator. Set this parameter to <tt>null</tt> 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 = cern.jet.random.AbstractDistribution.makeDefaultGenerator();
	this.my_RandomGenerator=randomGenerator;
}
 
Example #16
Source File: Distributions.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a random number from the Burr II, VII, VIII, X Distributions.
 * <p>
 * <b>Implementation:</b> Inversion method.
 * This is a port of <tt>burr1.c</tt> from the <A HREF="http://www.cis.tu-graz.ac.at/stat/stadl/random.html">C-RAND / WIN-RAND</A> library.
 * C-RAND's implementation, in turn, is based upon
 * <p>
 * L. Devroye (1986): Non-Uniform Random Variate Generation, Springer Verlag, New York.                                      
 * <p>
 * @param r must be &gt; 0.
 * @param nr the number of the burr distribution (e.g. 2,7,8,10).
 */
public static double nextBurr1(double r, int nr, RandomEngine randomGenerator) {
/******************************************************************
 *                                                                *
 *        Burr II, VII, VIII, X Distributions - Inversion         *
 *                                                                *
 ******************************************************************
 *                                                                *
 * FUNCTION :   - burr1 samples a random number from one of the   *
 *                Burr II, VII, VIII, X distributions with        *
 *                parameter  r > 0 , where the no. of the         *
 *                distribution is indicated by a pointer          *
 *                variable.                                       *
 * REFERENCE :  - L. Devroye (1986): Non-Uniform Random Variate   *
 *                Generation, Springer Verlag, New York.          *
 * SUBPROGRAM : - drand(seed) ... (0,1)-uniform generator with    *
 *                unsigned long integer *seed.                    *
 *                                                                *
 ******************************************************************/

	double y;
	y=Math.exp(Math.log(randomGenerator.raw())/r);                                /* y=u^(1/r) */
	switch (nr) {
		// BURR II   
		case 2  : return(-Math.log(1/y-1)); 

		// BURR VII 
		case 7  : return(Math.log(2*y/(2-2*y))/2);

		// BURR VIII 
		case 8  : return(Math.log(Math.tan(y*Math.PI/2.0)));

		// BURR X    
		case 10 : return(Math.sqrt(-Math.log(1-y)));
	}
	return 0;
}
 
Example #17
Source File: FunctionTimerSample.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();

    Timer timer = Timer.builder("timer")
        .publishPercentiles(0.5, 0.95)
        .register(registry);

    Object placeholder = new Object();
    AtomicLong totalTimeNanos = new AtomicLong(0);
    AtomicLong totalCount = new AtomicLong(0);

    FunctionTimer.builder("ftimer", placeholder, p -> totalCount.get(), p -> totalTimeNanos.get(), TimeUnit.NANOSECONDS)
        .register(registry);

    RandomEngine r = new MersenneTwister64(0);
    Normal incomingRequests = new Normal(0, 1, r);
    Normal duration = new Normal(250, 50, r);

    AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
    Flux.interval(Duration.ofSeconds(1))
        .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
        .subscribe();

    // the potential for an "incoming request" every 10 ms
    Flux.interval(Duration.ofMillis(10))
        .doOnEach(d -> {
            if (incomingRequests.nextDouble() + 0.4 > 0) {
                // pretend the request took some amount of time, such that the time is
                // distributed normally with a mean of 250ms
                timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS);
                totalCount.incrementAndGet();
                totalTimeNanos.addAndGet((long) TimeUtils.millisToUnit(latencyForThisSecond.get(), TimeUnit.NANOSECONDS));
            }
        })
        .blockLast();
}
 
Example #18
Source File: TimerMaximumThroughputSample.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
        MeterRegistry registry = SampleConfig.myMonitoringSystem();
        Timer timer = Timer.builder("timer")
                .publishPercentileHistogram()
//                .publishPercentiles(0.5, 0.95, 0.99)
                .serviceLevelObjectives(Duration.ofMillis(275), Duration.ofMillis(300), Duration.ofMillis(500))
                .distributionStatisticExpiry(Duration.ofSeconds(10))
                .distributionStatisticBufferLength(3)
                .register(registry);

        RandomEngine r = new MersenneTwister64(0);
        Normal duration = new Normal(250, 50, r);

        AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
        Flux.interval(Duration.ofSeconds(1))
                .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
                .subscribe();

        Stream<Integer> infiniteStream = Stream.iterate(0, i -> (i + 1) % 1000);
        Flux.fromStream(infiniteStream)
                .parallel(4)
                .runOn(Schedulers.parallel())
                .doOnEach(d -> timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS))
                .subscribe();

        Flux.never().blockLast();
    }
 
Example #19
Source File: LongTaskTimerSample.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    LongTaskTimer timer = registry.more().longTaskTimer("longTaskTimer");

    RandomEngine r = new MersenneTwister64(0);
    Normal incomingRequests = new Normal(0, 1, r);
    Normal duration = new Normal(30, 50, r);

    AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
    Flux.interval(Duration.ofSeconds(1))
            .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
            .subscribe();

    final Map<LongTaskTimer.Sample, CountDownLatch> tasks = new ConcurrentHashMap<>();

    // the potential for an "incoming request" every 10 ms
    Flux.interval(Duration.ofSeconds(1))
            .doOnEach(d -> {
                if (incomingRequests.nextDouble() + 0.4 > 0 && tasks.isEmpty()) {
                    int taskDur;
                    while ((taskDur = duration.nextInt()) < 0);
                    synchronized (tasks) {
                        tasks.put(timer.start(), new CountDownLatch(taskDur));
                    }
                }

                synchronized (tasks) {
                    for (Map.Entry<LongTaskTimer.Sample, CountDownLatch> e : tasks.entrySet()) {
                        e.getValue().countDown();
                        if (e.getValue().getCount() == 0) {
                            e.getKey().stop();
                            tasks.remove(e.getKey());
                        }
                    }
                }
            })
            .blockLast();
}
 
Example #20
Source File: GaugeSample.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    AtomicLong n = new AtomicLong();
    registry.gauge("gauge", Tags.of("k", "v"), n);
    registry.gauge("gauge", Tags.of("k", "v1"), n, n2 -> n2.get() - 1);

    RandomEngine r = new MersenneTwister64(0);
    Normal dist = new Normal(0, 10, r);

    Flux.interval(Duration.ofSeconds(5))
            .doOnEach(d -> n.set(Math.abs(dist.nextInt())))
            .blockLast();
}
 
Example #21
Source File: ChiSquare.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Sets the uniform random number generated shared by all <b>static</b> methods.
 * @param randomGenerator the new uniform random number generator to be shared.
 */
private static void xstaticSetRandomGenerator(RandomEngine randomGenerator) {
	synchronized (shared) {
		shared.setRandomGenerator(randomGenerator);
	}
}
 
Example #22
Source File: Uniform.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Sets the uniform random number generation engine shared by all <b>static</b> methods.
 * @param randomGenerator the new uniform random number generation engine to be shared.
 */
public static void staticSetRandomEngine(RandomEngine randomGenerator) {
	synchronized (shared) {
		shared.setRandomGenerator(randomGenerator);
	}
}
 
Example #23
Source File: PoissonSlow.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns a random number from the distribution; bypasses the internal state.
 */
private int nextInt(double theMean) {
	/* 
	 * Adapted from "Numerical Recipes in C".
	 */
  	double xm = theMean;
  	double g = this.cached_g;

	if (xm == -1.0 ) return 0; // not defined
	if (xm < SWITCH_MEAN ) {
		int poisson = -1;
		double product = 1;
		do {
			poisson++;
			product *= randomGenerator.raw();
		} while ( product >= g );
		// bug in CLHEP 1.4.0: was "} while ( product > g );"
		return poisson;
	}
	else if (xm < MEAN_MAX ) {
		double t;
		double em;
	  	double sq = this.cached_sq;
	  	double alxm = this.cached_alxm;

		RandomEngine rand = this.randomGenerator;
		do { 
			double y;
			do {
				y = Math.tan(Math.PI*rand.raw());
				em = sq*y + xm;
			} while (em < 0.0);
			em = (double) (int)(em); // faster than em = Math.floor(em); (em>=0.0)
			t = 0.9*(1.0 + y*y)* Math.exp(em*alxm - logGamma(em + 1.0) - g);
		} while (rand.raw() > t);
		return (int) em;
	}
	else { // mean is too large
		return (int) xm;
	}
}
 
Example #24
Source File: VonMises.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Sets the uniform random number generated shared by all <b>static</b> methods.
 * @param randomGenerator the new uniform random number generator to be shared.
 */
private static void xstaticSetRandomGenerator(RandomEngine randomGenerator) {
	synchronized (shared) {
		shared.setRandomGenerator(randomGenerator);
	}
}
 
Example #25
Source File: RandomSampler.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Efficiently computes a sorted random set of <tt>count</tt> elements from the interval <tt>[low,low+N-1]</tt>.
 * Since we are talking about a random set, no element will occur more than once.
 *
 * <p>Running time is <tt>O(count)</tt>, on average. Space requirements are zero.
 *
 * <p>Numbers are filled into the specified array starting at index <tt>fromIndex</tt> 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 &gt;= 0).
 * @param N the interval to choose random numbers from is <tt>[low,low+N-1]</tt>.
 * @param count the number of elements to be filled into <tt>values</tt> by this call (must be &gt;= 0 and &lt;=<tt>n</tt>). Normally, you will set <tt>count=n</tt>.
 * @param low the interval to choose random numbers from is <tt>[low,low+N-1]</tt>. Hint: If <tt>low==0</tt>, then draws random numbers from the interval <tt>[0,N-1]</tt>.
 * @param values the array into which the random numbers are to be filled; must have a length <tt>&gt;= count+fromIndex</tt>.
 * @param fromIndex the first index within <tt>values</tt> 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.raw())*ninv);
	qu1 = -n + 1 + N; qu1real = -nreal + 1.0 + Nreal;
	threshold = -negalphainv * n;
	
	while (n>1 && count>0 && threshold<N) {
		nmin1inv = 1.0/(-1.0 + nreal);
		for (;;) {
			for (;;) { // step D2: generate U and X
				X = Nreal * (-Vprime + 1.0); S = (long) X;
				if (S<qu1) break;
				Vprime = Math.exp(Math.log(randomGenerator.raw())*ninv);
			}
			U = randomGenerator.raw(); negSreal = -S;
			
			//step D3: Accept?
			y1 = Math.exp(Math.log(U*Nreal/qu1real) * nmin1inv);
			Vprime = y1*(-X/Nreal + 1.0) * (qu1real/(negSreal + qu1real));
			if (Vprime <= 1.0) break; //break inner loop

			//step D4: Accept?
			y2 = 1.0; top = -1.0 + Nreal;
			if (n-1>S) {
				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.raw())*nmin1inv);
				break; //break inner loop
			}
			Vprime = Math.exp(Math.log(randomGenerator.raw())*ninv);
		} //end for

		//step D5: select the (S+1)st record !
		chosen += S+1;
		values[fromIndex++] = chosen;
		/*
		// invert
		for (int iter=0; iter<S && count > 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;
		}
	}
}
 
Example #26
Source File: RandomSamplingAssistant.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns the used random generator.
 */
public RandomEngine getRandomGenerator() {
	return this.sampler.my_RandomGenerator;
}
 
Example #27
Source File: Logarithmic.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructs a Logarithmic distribution.
 */
public Logarithmic(double p, RandomEngine randomGenerator) {
	setRandomGenerator(randomGenerator);
	setState(p);
}
 
Example #28
Source File: Normal.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Constructs a normal (gauss) distribution.
 * Example: mean=0.0, standardDeviation=1.0.
 */
public Normal(double mean, double standardDeviation, RandomEngine randomGenerator) {
	setRandomGenerator(randomGenerator);
	setState(mean,standardDeviation);
}
 
Example #29
Source File: Hyperbolic.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Sets the uniform random number generated shared by all <b>static</b> methods.
 * @param randomGenerator the new uniform random number generator to be shared.
 */
private static void xstaticSetRandomGenerator(RandomEngine randomGenerator) {
	synchronized (shared) {
		shared.setRandomGenerator(randomGenerator);
	}
}
 
Example #30
Source File: Poisson.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Sets the uniform random number generated shared by all <b>static</b> methods.
 * @param randomGenerator the new uniform random number generator to be shared.
 */
private static void xstaticSetRandomGenerator(RandomEngine randomGenerator) {
	synchronized (shared) {
		shared.setRandomGenerator(randomGenerator);
	}
}