org.apache.commons.math3.random.RandomGenerator Java Examples

The following examples show how to use org.apache.commons.math3.random.RandomGenerator. 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: Cardumen_00229_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example #2
Source File: 1_DiscreteDistribution.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example #3
Source File: MinibatchSliceSampler.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Creates a new sampler for a bounded univariate random variable, given a random number generator, a list of data,
 * a continuous, univariate, unimodal, unnormalized log probability density function
 * (assumed to be a posterior and specified by a prior and a likelihood),
 * hard limits on the random variable, a step width, a minibatch size, and a minibatch approximation threshold.
 * @param rng                       random number generator, never {@code null}
 * @param data                      list of data, never {@code null}
 * @param logPrior                  log prior component of continuous, univariate, unimodal log posterior (up to additive constant), never {@code null}
 * @param logLikelihood             log likelihood component of continuous, univariate, unimodal log posterior (up to additive constant), never {@code null}
 * @param xMin                      minimum allowed value of the random variable
 * @param xMax                      maximum allowed value of the random variable
 * @param width                     step width for slice expansion
 * @param minibatchSize             minibatch size
 * @param approxThreshold           threshold for approximation used in {@link MinibatchSliceSampler#isGreaterThanSliceHeight};
 *                                  approximation is exact when this threshold is zero
 */
public MinibatchSliceSampler(final RandomGenerator rng,
                             final List<DATA> data,
                             final Function<Double, Double> logPrior,
                             final BiFunction<DATA, Double, Double> logLikelihood,
                             final double xMin,
                             final double xMax,
                             final double width,
                             final int minibatchSize,
                             final double approxThreshold) {
    super(rng, xMin, xMax, width);
    Utils.nonNull(data);
    Utils.nonNull(logPrior);
    Utils.nonNull(logLikelihood);
    Utils.validateArg(minibatchSize > 1, "Minibatch size must be greater than 1.");
    ParamUtils.isPositiveOrZero(approxThreshold, "Minibatch approximation threshold must be non-negative.");
    this.data = Collections.unmodifiableList(new ArrayList<>(data));
    this.logPrior = logPrior;
    this.logLikelihood = logLikelihood;
    this.minibatchSize = minibatchSize;
    this.approxThreshold = approxThreshold;
    numDataPoints = data.size();
}
 
Example #4
Source File: Arja_00158_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example #5
Source File: UniformCrossoverTests.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
@Test
public void UniformCrossover_BelowCrossoverRate_ShouldReturnParent0() {
    RandomGenerator rng = new TestRandomGenerator(null, new double[] {1.0});

    double[][] parents = new double[2][];
    parents[0] = new double[] {1.0, 1.0, 1.0};
    parents[1] = new double[] {2.0, 2.0, 2.0};
    TestParentSelection parentSelection = new TestParentSelection(parents);

    UniformCrossover sut = new UniformCrossover.Builder().parentSelection(parentSelection).randomGenerator(rng)
                    .crossoverRate(0.0).build();

    CrossoverResult result = sut.crossover();

    Assert.assertFalse(result.isModified());
    Assert.assertSame(parents[0], result.getGenes());
}
 
Example #6
Source File: WeibullDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a Weibull distribution.
 *
 * @param rng Random number generator.
 * @param alpha Shape parameter.
 * @param beta Scale parameter.
 * @param inverseCumAccuracy Maximum absolute error in inverse
 * cumulative probability estimates
 * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
 * @throws NotStrictlyPositiveException if {@code alpha <= 0} or {@code beta <= 0}.
 * @since 3.1
 */
public WeibullDistribution(RandomGenerator rng,
                           double alpha,
                           double beta,
                           double inverseCumAccuracy)
    throws NotStrictlyPositiveException {
    super(rng);

    if (alpha <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE,
                                               alpha);
    }
    if (beta <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SCALE,
                                               beta);
    }
    scale = beta;
    shape = alpha;
    solverAbsoluteAccuracy = inverseCumAccuracy;
}
 
Example #7
Source File: JGenProg2017_0059_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param lambda Population size.
 * @param inputSigma Initial search volume; sigma of offspring objective variables.
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 */
public CMAESOptimizer(int lambda, double[] inputSigma,
                      int maxIterations, double stopFitness,
                      boolean isActiveCMA, int diagonalOnly, int checkFeasableCount,
                      RandomGenerator random, boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.lambda = lambda;
    this.inputSigma = inputSigma == null ? null : (double[]) inputSigma.clone();
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #8
Source File: Arja_00181_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param lambda Population size.
 * @param inputSigma Initial search volume; sigma of offspring objective variables.
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 */
public CMAESOptimizer(int lambda, double[] inputSigma,
                      int maxIterations, double stopFitness,
                      boolean isActiveCMA, int diagonalOnly, int checkFeasableCount,
                      RandomGenerator random, boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.lambda = lambda;
    this.inputSigma = inputSigma == null ? null : (double[]) inputSigma.clone();
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #9
Source File: Arja_00177_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param lambda Population size.
 * @param inputSigma Initial search volume; sigma of offspring objective variables.
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 */
public CMAESOptimizer(int lambda, double[] inputSigma,
                      int maxIterations, double stopFitness,
                      boolean isActiveCMA, int diagonalOnly, int checkFeasableCount,
                      RandomGenerator random, boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.lambda = lambda;
    this.inputSigma = inputSigma == null ? null : (double[]) inputSigma.clone();
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #10
Source File: ParetoDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a Pareto distribution.
 *
 * @param rng Random number generator.
 * @param scale Scale parameter of this distribution.
 * @param shape Shape parameter of this distribution.
 * @param inverseCumAccuracy Inverse cumulative probability accuracy.
 * @throws NotStrictlyPositiveException if {@code scale <= 0} or {@code shape <= 0}.
 */
public ParetoDistribution(RandomGenerator rng,
                          double scale,
                          double shape,
                          double inverseCumAccuracy)
    throws NotStrictlyPositiveException {
    super(rng);

    if (scale <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SCALE, scale);
    }

    if (shape <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE, shape);
    }

    this.scale = scale;
    this.shape = shape;
    this.solverAbsoluteAccuracy = inverseCumAccuracy;
}
 
Example #11
Source File: ZipfDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a Zipf distribution.
 *
 * @param rng Random number generator.
 * @param numberOfElements Number of elements.
 * @param exponent Exponent.
 * @exception NotStrictlyPositiveException if {@code numberOfElements <= 0}
 * or {@code exponent <= 0}.
 * @since 3.1
 */
public ZipfDistribution(RandomGenerator rng,
                        int numberOfElements,
                        double exponent)
    throws NotStrictlyPositiveException {
    super(rng);

    if (numberOfElements <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.DIMENSION,
                                               numberOfElements);
    }
    if (exponent <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.EXPONENT,
                                               exponent);
    }

    this.numberOfElements = numberOfElements;
    this.exponent = exponent;
}
 
Example #12
Source File: EnumeratedIntegerDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param singletons array of random variable values.
 * @param probabilities array of probabilities.
 * @throws DimensionMismatchException if
 * {@code singletons.length != probabilities.length}
 * @throws NotPositiveException if any of the probabilities are negative.
 * @throws NotFiniteNumberException if any of the probabilities are infinite.
 * @throws NotANumberException if any of the probabilities are NaN.
 * @throws MathArithmeticException all of the probabilities are 0.
 */
public EnumeratedIntegerDistribution(final RandomGenerator rng,
                                   final int[] singletons, final double[] probabilities)
    throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
            NotFiniteNumberException, NotANumberException {
    super(rng);
    if (singletons.length != probabilities.length) {
        throw new DimensionMismatchException(probabilities.length, singletons.length);
    }

    final List<Pair<Integer, Double>> samples = new ArrayList<Pair<Integer, Double>>(singletons.length);

    for (int i = 0; i < singletons.length; i++) {
        samples.add(new Pair<Integer, Double>(singletons[i], probabilities[i]));
    }

    innerDistribution = new EnumeratedDistribution<Integer>(rng, samples);
}
 
Example #13
Source File: BinomialDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a binomial distribution.
 *
 * @param rng Random number generator.
 * @param trials Number of trials.
 * @param p Probability of success.
 * @throws NotPositiveException if {@code trials < 0}.
 * @throws OutOfRangeException if {@code p < 0} or {@code p > 1}.
 * @since 3.1
 */
public BinomialDistribution(RandomGenerator rng,
                            int trials,
                            double p) {
    super(rng);

    if (trials < 0) {
        throw new NotPositiveException(LocalizedFormats.NUMBER_OF_TRIALS,
                                       trials);
    }
    if (p < 0 || p > 1) {
        throw new OutOfRangeException(p, 0, 1);
    }

    probabilityOfSuccess = p;
    numberOfTrials = trials;
}
 
Example #14
Source File: JGenProg2017_00111_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param lambda Population size.
 * @param inputSigma Initial search volume; sigma of offspring objective variables.
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 */
public CMAESOptimizer(int lambda, double[] inputSigma,
                      int maxIterations, double stopFitness,
                      boolean isActiveCMA, int diagonalOnly, int checkFeasableCount,
                      RandomGenerator random, boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.lambda = lambda;
    this.inputSigma = inputSigma == null ? null : (double[]) inputSigma.clone();
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #15
Source File: jKali_0024_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param lambda Population size.
 * @param inputSigma Initial search volume; sigma of offspring objective variables.
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 */
public CMAESOptimizer(int lambda, double[] inputSigma,
                      int maxIterations, double stopFitness,
                      boolean isActiveCMA, int diagonalOnly, int checkFeasableCount,
                      RandomGenerator random, boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.lambda = lambda;
    this.inputSigma = inputSigma == null ? null : (double[]) inputSigma.clone();
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #16
Source File: Cardumen_00272_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example #17
Source File: PoissonDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new Poisson distribution with specified mean, convergence
 * criterion and maximum number of iterations.
 *
 * @param rng Random number generator.
 * @param p Poisson mean.
 * @param epsilon Convergence criterion for cumulative probabilities.
 * @param maxIterations the maximum number of iterations for cumulative
 * probabilities.
 * @throws NotStrictlyPositiveException if {@code p <= 0}.
 * @since 3.1
 */
public PoissonDistribution(RandomGenerator rng,
                           double p,
                           double epsilon,
                           int maxIterations)
throws NotStrictlyPositiveException {
    super(rng);

    if (p <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.MEAN, p);
    }
    mean = p;
    this.epsilon = epsilon;
    this.maxIterations = maxIterations;

    // Use the same RNG instance as the parent class.
    normal = new NormalDistribution(rng, p, FastMath.sqrt(p),
                                    NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    exponential = new ExponentialDistribution(rng, 1,
                                              ExponentialDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
}
 
Example #18
Source File: Math_6_CMAESOptimizer_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 *
 * @since 3.1
 */
public CMAESOptimizer(int maxIterations,
                      double stopFitness,
                      boolean isActiveCMA,
                      int diagonalOnly,
                      int checkFeasableCount,
                      RandomGenerator random,
                      boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #19
Source File: CMAESOptimizer_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param lambda Population size.
 * @param inputSigma Initial search volume; sigma of offspring objective variables.
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 */
public CMAESOptimizer(int lambda, double[] inputSigma,
                      int maxIterations, double stopFitness,
                      boolean isActiveCMA, int diagonalOnly, int checkFeasableCount,
                      RandomGenerator random, boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.lambda = lambda;
    this.inputSigma = inputSigma == null ? null : (double[]) inputSigma.clone();
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #20
Source File: Cardumen_00179_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example #21
Source File: RandomCirclePointGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param x Abscissa of the circle center.
 * @param y Ordinate of the circle center.
 * @param radius Radius of the circle.
 * @param xSigma Error on the x-coordinate of the circumference points.
 * @param ySigma Error on the y-coordinate of the circumference points.
 * @param seed RNG seed.
 */
public RandomCirclePointGenerator(double x,
                                  double y,
                                  double radius,
                                  double xSigma,
                                  double ySigma,
                                  long seed) {
    final RandomGenerator rng = new Well44497b(seed);
    this.radius = radius;
    cX = new NormalDistribution(rng, x, xSigma,
                                NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    cY = new NormalDistribution(rng, y, ySigma,
                                NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    tP = new UniformRealDistribution(rng, 0, MathUtils.TWO_PI,
                                     UniformRealDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
}
 
Example #22
Source File: RandomCirclePointGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param x Abscissa of the circle center.
 * @param y Ordinate of the circle center.
 * @param radius Radius of the circle.
 * @param xSigma Error on the x-coordinate of the circumference points.
 * @param ySigma Error on the y-coordinate of the circumference points.
 * @param seed RNG seed.
 */
public RandomCirclePointGenerator(double x,
                                  double y,
                                  double radius,
                                  double xSigma,
                                  double ySigma,
                                  long seed) {
    final RandomGenerator rng = new Well44497b(seed);
    this.radius = radius;
    cX = new NormalDistribution(rng, x, xSigma,
                                NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    cY = new NormalDistribution(rng, y, ySigma,
                                NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    tP = new UniformRealDistribution(rng, 0, MathUtils.TWO_PI,
                                     UniformRealDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
}
 
Example #23
Source File: AdaptiveMetropolisSampler.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Generate multiple samples from the probability density function.
 * @param numSamples    number of samples to generate
 * @param numBurnIn    number of samples to discard
 * @return              samples drawn from the probability density function
 */
public List<Double> sample(final RandomGenerator rng, final Function<Double, Double> logPDF, final int numSamples, final int numBurnIn) {
    Utils.nonNull(rng);
    Utils.nonNull(logPDF);
    ParamUtils.isPositive(numSamples, "Number of samples must be positive.");
    ParamUtils.isPositiveOrZero(numBurnIn, "Number of burn-in samples must be non-negative.");
    Utils.validateArg(numBurnIn < numSamples, "Number of samples must be greater than number of burn-in samples.");
    final List<Double> samples = new ArrayList<>(numSamples);
    for (int i = 0; i < numSamples; i++) {
        xCurrent = sample(rng, logPDF);
        if (i > numBurnIn) {
            samples.add(xCurrent);
        }
    }
    return samples;
}
 
Example #24
Source File: UnivariateMultiStartOptimizer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a multi-start optimizer from a single-start optimizer.
 *
 * @param optimizer Single-start optimizer to wrap.
 * @param starts Number of starts to perform. If {@code starts == 1},
 * the {@code optimize} methods will return the same solution as
 * {@code optimizer} would.
 * @param generator Random generator to use for restarts.
 * @throws NullArgumentException if {@code optimizer} or {@code generator}
 * is {@code null}.
 * @throws NotStrictlyPositiveException if {@code starts < 1}.
 */
public UnivariateMultiStartOptimizer(final BaseUnivariateOptimizer<FUNC> optimizer,
                                         final int starts,
                                         final RandomGenerator generator) {
    if (optimizer == null ||
            generator == null) {
            throw new NullArgumentException();
    }
    if (starts < 1) {
        throw new NotStrictlyPositiveException(starts);
    }

    this.optimizer = optimizer;
    this.starts = starts;
    this.generator = generator;
}
 
Example #25
Source File: Cardumen_00211_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param lambda Population size.
 * @param inputSigma Initial search volume; sigma of offspring objective variables.
 * @param maxIterations Maximal number of iterations.
 * @param stopFitness Whether to stop if objective function value is smaller than
 * {@code stopFitness}.
 * @param isActiveCMA Chooses the covariance matrix update method.
 * @param diagonalOnly Number of initial iterations, where the covariance matrix
 * remains diagonal.
 * @param checkFeasableCount Determines how often new random objective variables are
 * generated in case they are out of bounds.
 * @param random Random generator.
 * @param generateStatistics Whether statistic data is collected.
 * @param checker Convergence checker.
 */
public CMAESOptimizer(int lambda, double[] inputSigma,
                      int maxIterations, double stopFitness,
                      boolean isActiveCMA, int diagonalOnly, int checkFeasableCount,
                      RandomGenerator random, boolean generateStatistics,
                      ConvergenceChecker<PointValuePair> checker) {
    super(checker);
    this.lambda = lambda;
    this.inputSigma = inputSigma == null ? null : (double[]) inputSigma.clone();
    this.maxIterations = maxIterations;
    this.stopFitness = stopFitness;
    this.isActiveCMA = isActiveCMA;
    this.diagonalOnly = diagonalOnly;
    this.checkFeasableCount = checkFeasableCount;
    this.random = random;
    this.generateStatistics = generateStatistics;
}
 
Example #26
Source File: Arja_00144_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example #27
Source File: WeibullDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a Weibull distribution.
 *
 * @param rng Random number generator.
 * @param alpha Shape parameter.
 * @param beta Scale parameter.
 * @param inverseCumAccuracy Maximum absolute error in inverse
 * cumulative probability estimates
 * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
 * @throws NotStrictlyPositiveException if {@code alpha <= 0} or
 * {@code beta <= 0}.
 * @since 3.1
 */
public WeibullDistribution(RandomGenerator rng,
                           double alpha,
                           double beta,
                           double inverseCumAccuracy)
    throws NotStrictlyPositiveException {
    super(rng);

    if (alpha <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE,
                                               alpha);
    }
    if (beta <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SCALE,
                                               beta);
    }
    scale = beta;
    shape = alpha;
    solverAbsoluteAccuracy = inverseCumAccuracy;
}
 
Example #28
Source File: PascalDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Pascal distribution with the given number of successes and
 * probability of success.
 *
 * @param rng Random number generator.
 * @param r Number of successes.
 * @param p Probability of success.
 * @throws NotStrictlyPositiveException if the number of successes is not positive
 * @throws OutOfRangeException if the probability of success is not in the
 * range {@code [0, 1]}.
 * @since 3.1
 */
public PascalDistribution(RandomGenerator rng,
                          int r,
                          double p)
    throws NotStrictlyPositiveException, OutOfRangeException {
    super(rng);

    if (r <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SUCCESSES,
                                               r);
    }
    if (p < 0 || p > 1) {
        throw new OutOfRangeException(p, 0, 1);
    }

    numberOfSuccesses = r;
    probabilityOfSuccess = p;
}
 
Example #29
Source File: WeibullDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a Weibull distribution.
 *
 * @param rng Random number generator.
 * @param alpha Shape parameter.
 * @param beta Scale parameter.
 * @param inverseCumAccuracy Maximum absolute error in inverse
 * cumulative probability estimates
 * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
 * @throws NotStrictlyPositiveException if {@code alpha <= 0} or
 * {@code beta <= 0}.
 * @since 3.1
 */
public WeibullDistribution(RandomGenerator rng,
                           double alpha,
                           double beta,
                           double inverseCumAccuracy)
    throws NotStrictlyPositiveException {
    super(rng);

    if (alpha <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE,
                                               alpha);
    }
    if (beta <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.SCALE,
                                               beta);
    }
    scale = beta;
    shape = alpha;
    solverAbsoluteAccuracy = inverseCumAccuracy;
}
 
Example #30
Source File: SphereGeneratorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRandom() {
    final RandomGenerator random = new Well1024a(0xd015982e9f31ee04l);
    final UnitSphereRandomVectorGenerator sr = new UnitSphereRandomVectorGenerator(3, random);
    for (int i = 0; i < 100; ++i) {
        double d = 25 * random.nextDouble();
        double refRadius = 10 * random.nextDouble();
        Vector3D refCenter = new Vector3D(d, new Vector3D(sr.nextVector()));
        List<Vector3D> support = new ArrayList<Vector3D>();
        for (int j = 0; j < 5; ++j) {
            support.add(new Vector3D(1.0, refCenter, refRadius, new Vector3D(sr.nextVector())));
        }
        EnclosingBall<Euclidean3D, Vector3D> sphere = new SphereGenerator().ballOnSupport(support);
        Assert.assertEquals(0.0, refCenter.distance(sphere.getCenter()), 4e-7 * refRadius);
        Assert.assertEquals(refRadius, sphere.getRadius(), 1e-7 * refRadius);
    }
    
}