org.randomness
Class Pseudorandomness

java.lang.Object
  extended by org.randomness.Randomness
      extended by org.randomness.Pseudorandomness
All Implemented Interfaces:
Closeable, Serializable, Channel, ReadableByteChannel, ScatteringByteChannel

public abstract class Pseudorandomness
extends Randomness
implements Serializable

This class specifies Pseudorandom Number Generator (PRNG) techniques for the compute bits deterministically using an underlying algorithm that, given the same initial state, always produces the same outputs.

A PRNG mechanism uses an algorithm that produces a sequence of pseudorandom bits from an initial internal state that is determined by a seed that is determined from the entropy input. The seed used to instantiate the PRNG must contain sufficient entropy to provide an assurance of randomness. Once the seed is provided and the initial internal state is determined, the PRNG is said to be instantiated. The generate function generates pseudorandom bits upon request, using the current internal state, and generates a new internal state for the next request. Because of the deterministic nature of the process, a PRNG is said to produce pseudorandom bits, rather than random bits. Given the same seed inputs, algorithm always produces the same outputs.

PRNG states

The PRNG operate in following states:

PRNG mechanisms

The PRNG mechanisms have four separate functions:

Thread-local PRNG

The thread-local PRNG can be isolated in the current thread; any attempt to access PRNG functions from another thread will throw ConcurrentModificationException. The pre-implemented PRNG instances can be obtained in thread-local mode via both PRNG.current() or current(PRNG) factory-methods. For example:
 Pseudorandomness mt = Pseudorandomness.current(PRNG.MERSENNE_TWISTER);
 

The thread-local PRNG has following properties:

Shared PRNG

If PRNG is not thread-local it automatically become shared across multiple threads. The shared Pseudorandomness are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. Only one operation that involves the PRNG's working state may be in progress at any given time; attempts to initiate a second such operation while the first is still in progress will block until the first operation completes. Other operations may proceed concurrently; whether they in fact do so is dependent upon the underlying implementation and is therefore unspecified. The pre-implemented shared PRNG instances created via both shared(PRNG) or PRNG.shared() factory-methods.
 Pseudorandomness mt = Pseudorandomness.shared(PRNG.MERSENNE_TWISTER);
 

The shared PRNG has following properties:

Author:
Anton Kabysh - Code, Specification
See Also:

Wikipedia - Pseudorandomness,
Wikipedia - Pseudorandom number generator,
Wikipedia - List of random number generators,
Randomness Extractor, Serialized Form

Constructor Summary
protected Pseudorandomness()
          Initializes a new instance of this class.
static Pseudorandomness current(PRNG prng)
          Creates a unique Pseudo-random Number Generator isolated to the current thread (thread-local).
static Pseudorandomness shared(PRNG prng)
          Creates shared Pseudorandomness using specified pre-implemented PRNG algorithm.
 
PRNG Functions Summary
abstract  void reset()
          The instantiate function creates the initial working state from initial internal state using the instantiate algorithm.
abstract  int read(ByteBuffer buffer)
          The generate function is used to generate the requested pseudorandom bits after instantiation or reseeding using the generate algorithm.
abstract  Pseudorandomness reseed(ByteBuffer seed)
          The reseed function acquires a seedlen bytes to create new internal state.
 Pseudorandomness reseed()
          Creates new initial internal state using reseed function obtaining seedlen bytes from entropy input.
 Pseudorandomness reseed(byte[] seed)
          Reseed's this PRNG creating new internal state from the specified seed bytes.
protected  byte[] getEntropyInput(int minEntropy)
          A entropy function is used to obtain entropy input.
abstract  void close()
          The uninstantiate function closes this PRNG and zeroizes its internal state.
 
Additional Operations Summary
 Random asRandom()
          Represents this PRNG as java.util.Random.
 Pseudorandomness copy()
          Returns a deep copy of this pseudorandomness with identical producing output (optional operation).
 boolean equals(Object obj)
          Tells whether or not this Pseudorandomness is equal to another object (consistent with hashCode) (optional operation).
 int hashCode()
          Returns the hash code value for this generator (consistent with equals) (optional operation).
abstract  boolean isOpen()
          Tells whether or not this PRNG is open to generate pseudorandom bytes.
 int minlen()
          Minlen it is the minimum block of bytes essentially produced per one iteration of generate function (optional operation).
 Pseudorandomness next()
          TODO PROVISIONAL API, WORK IN PROGRESS: Reinitializes the PRNG to the beginning of its next substream (optional operation).
protected abstract  int seedlen()
          Return's initial seed length used by underlying PRNG algorithm in bytes.
 void shuffle(List<?> list)
          Randomly permute the specified list using this PRNG.
 String toString()
          Returns the name of the algorithm implemented by this PRNG (optional operation).
 
Read Method Summary
abstract  int read(DoubleBuffer doubleBuffer)
          Transfers a sequence of generated double's from this PRNG into the given buffer.
abstract  int read(FloatBuffer floatBuffer)
          Transfers a sequence of generated pseudorandom float's from this PRNG into the given buffer.
abstract  int read(IntBuffer intBuffer)
          Transfers a sequence of generated pseudorandom int's from this PRNG into the given buffer.
abstract  int read(LongBuffer longBuffer)
          Transfers a sequence of generated long's from this PRNG into the given buffer.
abstract  int tryRead(ByteBuffer buffer)
          Attempts to read from this PRNG into the given buffer, starting at the given file position if generate function is not owned by other thread.
 
Generation Method Summary
 double nextDouble(double from, double to)
          Returns a uniformly distributed random floating point number in the open interval (from,to) (excluding from and to).
 float nextFloat(float from, float to)
          Returns a uniformly distributed random floating point number in the open interval (from,to) (excluding from and to).
 double nextGaussian()
          Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
 double nextGaussian(double mu, double sigma)
          Returns the next pseudorandom, Gaussian ("normally") distributed double value with the given mean, mu and the given standard deviation, sigma.
 int nextInt(int from, int to)
          Returns a uniformly distributed random number in the closed interval [from,to] (including from and to).
 long nextLong(long from, long to)
          Returns a uniformly distributed random number in the closed interval [from,to] (including from and to).
 double random()
          Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
   
Methods inherited from class org.randomness.Randomness
bind, map, mixing, newBuffer, nextBoolean, nextByte, nextChar, nextCharASCII, nextDouble, nextFloat, nextHexString, nextInt, nextInt, nextLong, nextLong, nextProbability, nextShort, read, read, read, readFuture, readSink, reversed, shuffle
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Pseudorandomness

protected Pseudorandomness()
Initializes a new instance of this class.

Method Detail

shared

public static final Pseudorandomness shared(PRNG prng)
Creates shared Pseudorandomness using specified pre-implemented PRNG algorithm.

Parameters:
prng - a specified PRNG algorithm
Returns:
the new PRNG shared instance.
See Also:
PRNG.shared()

current

public static final Pseudorandomness current(PRNG prng)
Creates a unique Pseudo-random Number Generator isolated to the current thread (thread-local). Any attempt to use this instance from another thread will throw ConcurrentModificationException.

Thread-local PRNG initializes when this method is first called; any further call will return the same instance for the same thread.

Parameters:
prng - a specified PRNG algorithm
Returns:
the thread local instance of specified PRNG
See Also:
PRNG.current()

reset

public abstract void reset()
The instantiate function creates the initial working state from initial internal state using the instantiate algorithm. A PRBG shall be instantiated prior to the generation of random bits.

The instantiate function:

  1. Checks the validity of the input parameters,
  2. Determines any PRNG mechanism specific parameters (if required).
  3. Obtains seedlen bytes of entropy from entropy function,
  4. Determines the initial internal state using the instantiate algorithm.

A subsequent call of instantiate function reset's PRNG working state to it's initial internal state so that subsequent reads re-generate the same bytes.

 Pseudorandomness gen = ...
 gen.read(buffer);
 
 ...
 buffer.clear();
 gen.reset(); // restore to initial state;
 gen.read(buffer) // will generate the same pseudorandom sequence
 
This method may be invoked at any time. If another thread has already initiated a generate operation upon this PRNG, then an invocation of this method will block until the first operation is complete.

Specified by:
reset in class Randomness
Throws:
NonReadableChannelException - if entropy source is closed.

reseed

public abstract Pseudorandomness reseed(ByteBuffer seed)
The reseed function acquires a seedlen bytes to create new internal state. The entropy input required to seed or reseed a PRNG shall be obtained either directly or indirectly from an entropy source.

The reseed function:

  1. Checks the validity of the input parameters,
  2. Converts seed bytes to specified seed, and
  3. Remember new initial internal state from the seed (discard previous, if present).
  4. Using the instantiate algorithm determine the new working state.

The seed buffer should have no less than seedlen remaining bytes to read. In other words seed.remaining() >= seedlen or exception will be thrown.

This method may be invoked at any time. If another thread has already initiated a generate operation upon this PRNG, then an invocation of this method will block until the first operation is complete.

Parameters:
seed - a seed bytes which determine new working state using instantiate algorithm.
Returns:
this
Throws:
NullPointerException - if seed is null
IllegalArgumentException - if seed bytes in ByteBuffer can't be converted into internal state. In other words seed contains no enough bytes to be converted into internal state.
See Also:
Seed sizes of pre-implemented PRNG's,
{@link PRNG#DEFAULT_ENTROPY_INPUT}

reseed

public final Pseudorandomness reseed(byte[] seed)
Reseed's this PRNG creating new internal state from the specified seed bytes.

Otherwise this method behaves exactly as specified in the reseed function.

Parameters:
seed - the seed bytes
Returns:
this
Throws:
IllegalArgumentException - if seed bytes length is less than seedlen value.

reseed

public final Pseudorandomness reseed()
Creates new initial internal state using reseed function obtaining seedlen bytes from entropy input.

Discard's a previous initial internal state, if present, and set's the new one.

This method may be invoked at any time. If another thread has already initiated a generate operation upon this PRNG, then an invocation of this method will block until the first operation is complete.

Returns:
this PRNG with new initial internal state.
Throws:
NonReadableChannelException - if entropyInput is closed.

read

public abstract int read(ByteBuffer buffer)
The generate function is used to generate the requested pseudorandom bits after instantiation or reseeding using the generate algorithm.

In other words, transfers a sequence generated bytes from this PRNG into the given buffer. An attempt is made to generate up to r bytes from PRNG, where r is the number of bytes remaining in the buffer, that is, buffer.remaining(), at the moment this method is invoked.

This method may be invoked at any time. If another thread has already initiated a generate operation upon this PRNG, then an invocation of this method will block until the first operation is complete.

The generate function:

  1. Checks the validity of the current state.
  2. For every generate iteration:
    • Generates the minlen bytes using the generate algorithm.
    • Updates the working state.
    • Transfers generated minlen bytes into buffer.
    • If generator is closed - stop generation function and return total generated bytes.
  3. Returns the requested pseudorandom bytes to the consuming application.

Specified by:
read in interface ReadableByteChannel
Specified by:
read in class Randomness
Parameters:
buffer - The buffer into which random bytes are to be transferred
Returns:
The number of bytes generated, possibly zero.
Throws:
NullPointerException - if buffer is null.

read

public abstract int read(IntBuffer intBuffer)
Transfers a sequence of generated pseudorandom int's from this PRNG into the given buffer.

In other words, transfers a sequence generated integers from this PRNG into the given buffer. An attempt is made to generate up to r bytes from PRNG, where r is the number of integers remaining in the buffer, that is, buffer.remaining(), at the moment this method is invoked.

Otherwise this method behaves exactly as specified in the generate function.

Parameters:
intBuffer - The buffer into which random integers are to be transferred
Returns:
The number of int's read, possibly zero.

read

public abstract int read(FloatBuffer floatBuffer)
Transfers a sequence of generated pseudorandom float's from this PRNG into the given buffer.

In other words, transfers a sequence generated floating point values from this PRNG into the given buffer. An attempt is made to generate up to r bytes from PRNG, where r is the number of integers remaining in the buffer, that is, buffer.remaining(), at the moment this method is invoked.

This method behaves exactly as specified in the generate function.

Parameters:
floatBuffer - The buffer into which random floating point values are to be transferred
Returns:
The number of float's read, possibly zero.

read

public abstract int read(LongBuffer longBuffer)
Transfers a sequence of generated long's from this PRNG into the given buffer.

In other words, transfers a sequence generated integers from this PRNG into the given buffer. An attempt is made to generate up to r bytes from PRNG, where r is the number of integers remaining in the buffer, that is, buffer.remaining(), at the moment this method is invoked.

This method behaves exactly as specified in the generate function.

Parameters:
longBuffer - The buffer into which random long values are to be transferred.
Returns:
The number of long's read, possibly zero.

read

public abstract int read(DoubleBuffer doubleBuffer)
Transfers a sequence of generated double's from this PRNG into the given buffer.

In other words, transfers a sequence generated floating point double's from this PRNG into the given buffer. An attempt is made to generate up to r bytes from PRNG, where r is the number of integers remaining in the buffer, that is, buffer.remaining(), at the moment this method is invoked.

This method behaves exactly as specified in the generate function.

Parameters:
doubleBuffer - The buffer into which random double's are to be transferred
Returns:
The number of double's read, possibly zero.

tryRead

public abstract int tryRead(ByteBuffer buffer)
Attempts to read from this PRNG into the given buffer, starting at the given file position if generate function is not owned by other thread.

For thread-local PRNG this method behaves exactly as specified in the generate function.

Specified by:
tryRead in class Randomness
Parameters:
buffer - The buffer into which random bytes are to be transferred.
Returns:
The number of bytes read from PRNG, possibly zero, or -1 if the PRNG has already blocked on other thread.

copy

public Pseudorandomness copy()
Returns a deep copy of this pseudorandomness with identical producing output (optional operation).

This metod shoud be overriden in subclasses, or UnsupportedOperationException will be thrown. The returned copy and original PRNG should be consistent at equals(Object) (be equal) and hashCode() (has the same hash code) methods.

This metod is overriden and implemented in all PRNG boundled implementations.

Returns:
the deep copy of this Pseudorandomness equal to original
Throws:
UnsupportedOperationException - if not overriden
NonReadableChannelException - if channel is closed (no state to copy)

isOpen

public abstract boolean isOpen()
Tells whether or not this PRNG is open to generate pseudorandom bytes.

If PRNG is closed, any further attempt to invoke generate operations upon it will cause a NonReadableChannelException to be thrown.

Specified by:
isOpen in interface Channel
Specified by:
isOpen in class Randomness
Returns:
false if PRNG is not instantiated yet or closed, true otherwise.

close

public abstract void close()
The uninstantiate function closes this PRNG and zeroizes its internal state. If PRNG is closed, any further attempt to invoke generate operations upon it will cause a NonReadableChannelException to be thrown. The closing status can be checked at run-time via isOpen() method. Opposite to instantiate function.

The close method eliminate all PRNG internal state, so any further operations dealing with PRNG internal state will throws NonReadableChannelException. For example, PRNG can't be copied, generate any pseudorandom output, not equals to itself, but still has a hash code.

Asynchronous Closability


If PRNG is blocked on an generate function , then another thread may invoke (asynchronously) the PRNG's close method. This will stop generate function without throwing any exceptions after generating next cycle of pseudorandom bytes The generate function lock is released, and close status is set and can be checked prior to next generation process.

This method may be invoked at any time. Interrupting a PRNG that is not generate random bytes need not have any effect. If this PRNG is already closed then invoking this method has no effect.

Specified by:
close in interface Closeable
Specified by:
close in interface Channel
Specified by:
close in class Randomness

minlen

public int minlen()
Minlen it is the minimum block of bytes essentially produced per one iteration of generate function (optional operation).

This method should be overriden to provide additional information about PRNG for most essential generation process.

If method is not overriden, it returns defautl value, equal to 4 bytes (minimum from all minlens of all PRNG implementations).

Specified by:
minlen in class Randomness
Returns:
amount of bytes generated on each iteration of generate function

seedlen

protected abstract int seedlen()
Return's initial seed length used by underlying PRNG algorithm in bytes.

Returns:
the seed length

getEntropyInput

protected byte[] getEntropyInput(int minEntropy)
A entropy function is used to obtain entropy input.

Returns the input to a PRNG mechanism of a string of bits that contains entropy; that is, the entropy input is digitized and has been assessed prior to use as input.

Entropy is obtained from an entropy source. The entropy input required to seed or reseed a PRNG shall be obtained either directly or indirectly from an entropy source.

Note that an implementation may choose to define this functionality differently. The default entropy input is specified by PRNG.DEFAULT_ENTROPY_INPUT variable. The user may specify external seeds at reseed(ByteBuffer) function.

Parameters:
minEntropy - number bytes of entropy.
Returns:
a byte array containing min_entropy bytes of entropy.

hashCode

public int hashCode()
Returns the hash code value for this generator (consistent with equals) (optional operation).

This method should be overridden is subclasses to correspond complete Pseudorandomness specifications.

Contract
For two Pseudorandomness, equal with each other, invocation of this method must return the same hash code value. In other words, if two Pseudorandomness has same algorithm and internal state producing the same output, they must have same hash code.

Because hash codes of Pseudorandomness are state-dependent, it is inadvisable to use Pseudorandomness as keys in hash maps or similar data structures.

If PRNG is closed, than system hash code for PRNG object should be returned.

Overrides:
hashCode in class Object
Returns:
The current hash code of this Pseudorandomness.
Throws:
UnsupportedOperationException - if not overriden

equals

public boolean equals(Object obj)
Tells whether or not this Pseudorandomness is equal to another object (consistent with hashCode) (optional operation).

This method should be overridden is subclasses to correspond complete Pseudorandomness specifications.

Contract
The two Pseudorandomness are equal if and only if they has same algorithm and internal state such, any next produced output is identical. Implementation of this method should be consistent wiht the hashCode() and toString() methods.

If PRNG is closed they has no internal state, so rand.equal(rand) returns false.

Overrides:
equals in class Object
Returns:
true if two Pseudorandomness are identical, false otherwise.
Throws:
UnsupportedOperationException - if not overriden

nextGaussian

public final double nextGaussian()
Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

Returns:
the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence

nextGaussian

public final double nextGaussian(double mu,
                                 double sigma)
Returns the next pseudorandom, Gaussian ("normally") distributed double value with the given mean, mu and the given standard deviation, sigma.

Parameters:
mu - the mean of the distribution
sigma - the standard deviation of the distribution
Returns:
the random Normal value
Throws:
IllegalArgumentException - if sigma <= 0.

random

public final double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

Returns:
a pseudorandom double greater than or equal to 0.0 and less than 1.0.

nextInt

public final int nextInt(int from,
                         int to)
Returns a uniformly distributed random number in the closed interval [from,to] (including from and to).

Parameters:
from - low border of interval (included)
to - hight border of interval (included)
Returns:
next generated uniformly distributed random number in interval [from,to].
Throws:
IllegalArgumentException - if from >= to.

nextDouble

public final double nextDouble(double from,
                               double to)
Returns a uniformly distributed random floating point number in the open interval (from,to) (excluding from and to).

Parameters:
from - low border of interval (excluded)
to - hight border of interval (excluded)
Returns:
next generated uniformly distributed random floating point in interval [from,to].
Throws:
IllegalArgumentException - if from >= to.

nextFloat

public final float nextFloat(float from,
                             float to)
Returns a uniformly distributed random floating point number in the open interval (from,to) (excluding from and to).

Parameters:
from - low border of interval (excluded)
to - hight border of interval (excluded)
Returns:
next generated uniformly distributed random floating point in interval [from,to].
Throws:
IllegalArgumentException - if from >= to.

nextLong

public final long nextLong(long from,
                           long to)
Returns a uniformly distributed random number in the closed interval [from,to] (including from and to).

Parameters:
from - low border of interval (included)
to - hight border of interval (included)
Returns:
next generated uniformly distributed random number in interval [from,to].
Throws:
IllegalArgumentException - if from >= to.

shuffle

public final void shuffle(List<?> list)
Randomly permute the specified list using this PRNG. All permutations occur with equal likelihood assuming that the source of randomness is fair.
 Pseudorandomness rand = ...
 rand.shuffle(Arrays.asList(200,300,212,111,6,2332));
 
This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.

This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place.

Parameters:
list - the list to be shuffled.
Throws:
UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation.
See Also:
Collections#shuffle(List);

asRandom

public final Random asRandom()
Represents this PRNG as java.util.Random.

This method convert this PRNG into java.util.Random instance, to be used instead it in java legacy code. For example:

BigInteger big = new BigInteger(128, Randomness.from(TRNG.NATIVE).asRandom());

Note: Calling of Random.setSeed(long) has the same semantis as reseed(ByteBuffer) with byte buffer containing 8 bytes from long seed value.

The view is typically part of the RBG itself (created only once) and every call return this instance.

Overrides:
asRandom in class Randomness
Returns:
view as java.util.Random over this PRNG.
See Also:
Cryptorandomness.asRandom()

toString

public String toString()
Returns the name of the algorithm implemented by this PRNG (optional operation).

This method should be overridden to provide additional information about PRNG.

The PRNG implementations toString() value, consistent with PRNG.valueOf(String) and vice-versa.

Specified by:
toString in class Randomness
Returns:
the name of the algorithm, or UNKNOWN if the algorithm name cannot be determined (default value).

nextLong1

public long nextLong1()

next

public Pseudorandomness next()
TODO PROVISIONAL API, WORK IN PROGRESS: Reinitializes the PRNG to the beginning of its next substream (optional operation).

Returns:
next substream