List of usage examples for org.apache.commons.math3.distribution UniformIntegerDistribution UniformIntegerDistribution
public UniformIntegerDistribution(RandomGenerator rng, int lower, int upper) throws NumberIsTooLargeException
From source file:com.metawiring.load.generators.LineExtractGenerator.java
public LineExtractGenerator(String filename) { this.filename = filename; loadLines(this.filename); itemDistribution = new UniformIntegerDistribution(rng, 0, lines.size() - 2); }
From source file:com.metawiring.load.generators.LoremExtractGenerator.java
@Override public String get() { if (loremIpsumImage == null) { synchronized (LoremExtractGenerator.class) { if (loremIpsumImage == null) { CharBuffer image = loadLoremIpsum(); loremIpsumImage = image; }//from w ww . ja v a2s . co m sizeDistribution = new UniformIntegerDistribution(rng, minsize, maxsize); positionDistribution = new UniformIntegerDistribution(rng, 1, loremIpsumImage.limit() - maxsize); } } int offset = positionDistribution.sample(); int length = sizeDistribution.sample(); String sub = null; try { sub = loremIpsumImage.subSequence(offset, offset + length).toString(); } catch (Exception e) { throw new RuntimeException(e); } return sub; }
From source file:com.metawiring.load.generators.ExtractGenerator.java
@Override public String get() { if (fileDataImage == null) { synchronized (ExtractGenerator.class) { if (fileDataImage == null) { CharBuffer image = loadFileData(); fileDataImage = image;/*from w ww . j a v a2 s .c om*/ } } } if (sizeDistribution == null) { sizeDistribution = new UniformIntegerDistribution(rng, minsize, maxsize); positionDistribution = new UniformIntegerDistribution(rng, 1, fileDataImage.limit() - maxsize); } int offset = positionDistribution.sample(); int length = sizeDistribution.sample(); String sub = null; try { sub = fileDataImage.subSequence(offset, offset + length).toString(); } catch (Exception e) { throw new RuntimeException(e); } return sub; }
From source file:edu.oregonstate.eecs.mcplan.domains.fuelworld.MoveAction.java
public final AbstractIntegerDistribution getFuelConsumption(final FuelWorldState s) { return new UniformIntegerDistribution(s.rng, 1, s.fuel_consumption); }
From source file:com.vsthost.rnd.jdeoptim.evolution.strategies.Strategy3.java
@Override public void regenerate(Population population, Problem problem, Objective objective) { // Setup a uniform integer distribution for candidate element selection: UniformIntegerDistribution elementSampling = new UniformIntegerDistribution(this.randomGenerator, 0, population.getDimension() - 1); // Get the best member of the population: final double[] bestMember = population.getBestMember(); // Define the new population data and scores as we don't want to override old one within the loop: final double[][] newPopData = new double[population.getSize()][]; final double[] newPopScores = new double[population.getSize()]; final boolean[] newPopFlags = new boolean[population.getSize()]; // Iterate over the current population: for (int c = 0; c < population.getSize(); c++) { // Are we going to adjust CR and F? if (this.c > 0) { // Yes. We will not adjust the CR first: this.cr = new NormalDistribution(this.randomGenerator, this.meanCR, 0.1).sample(); // Check and reset CR: this.cr = this.cr > 1 ? 1 : (this.cr < 0 ? 0 : this.cr); // OK, now we will adjust F: do {/* w w w . ja v a 2s . c o m*/ // Get the new F: this.f = new CauchyDistribution(this.randomGenerator, this.meanF, 0.1).sample(); // Check and reset F if required: this.f = this.f > 1 ? 1 : this.f; } while (this.f <= 0.0); } // Get the candidate as the base of the next candidate (a.k.a. trial): final double[] trial = population.getMemberCopy(c); // Get the score of the candidate: final double oldScore = population.getScore(c); // Get two random candidate indices: final int[] randomCandidates = Utils.pickRandom(Utils.sequence(population.getSize()), 2, new int[] { c }, this.randomGenerator); // Get the index of element of candidate to start with: int j = elementSampling.sample(); // Set the counter for preventing overflowing dimension: int k = 0; // Iterate and set elements: do { // Get the jitter: final double jitter = (probability.sample() * this.jitterFactor) + this.f; // Get the respective element of the best candidate: final double bestest = bestMember[j]; // Get the random candidate elements: final double random1 = population.getMember(randomCandidates[0])[j]; final double random2 = population.getMember(randomCandidates[1])[j]; // Override trial: trial[j] = bestest + jitter * (random1 - random2); // Move to the next element: j = (j + 1) % population.getDimension(); // Increment k: k++; } while (probability.sample() < this.cr && k < population.getDimension()); // We have an interim trial. We will now truncate: for (int i = 0; i < trial.length; i++) { // Are we truncating? if (precision == 0) { continue; } // OK, truncate: trial[i] = DMatrixUtils.roundDoubleToClosest(trial[i], this.precision); } // Apply limits in case that we have violated: for (int i = 0; i < trial.length; i++) { // Check lower limit: if (trial[i] < problem.getLower()[i]) { if (this.bounceBack) { trial[i] = problem.getLower()[i] + probability.sample() * (problem.getUpper()[i] - problem.getLower()[i]); } else { trial[i] = problem.getLower()[i]; } } // Check upper limit: if (trial[i] > problem.getUpper()[i]) { if (this.bounceBack) { trial[i] = problem.getUpper()[i] - probability.sample() * (problem.getUpper()[i] - problem.getLower()[i]); } else { trial[i] = problem.getUpper()[i]; } } } // We will now check if we have a // better candidate. If yes, we will replace the old member with the trial, // if not we will just skip. Compute the score: final double newScore = objective.apply(trial); // Check the new score against the old one and act accordingly: if (newScore < oldScore) { // Yes, our trial is a better candidate. Replace: newPopData[c] = trial; newPopScores[c] = newScore; newPopFlags[c] = true; // We will now re-adjust for CR and F. this.goodCR += this.cr / ++this.goodNPCount; this.goodF += this.f; this.goodF2 += Math.pow(this.f, 2); } else { newPopFlags[c] = false; } } // Re-compute mean CR and F if required: if (this.c > 0 && this.goodF != 0) { this.meanCR = (1 - this.c) * this.meanCR + this.c * this.goodCR; this.meanF = (1 - this.c) * this.meanF + this.c * this.goodF2 / this.goodF; } // Now, override the population: for (int i = 0; i < population.getSize(); i++) { if (newPopFlags[i]) { population.setMember(i, newPopData[i], newPopScores[i]); } } }
From source file:com.github.rinde.rinsim.util.StochasticSuppliers.java
/** * Creates a {@link StochasticSupplier} that produces uniformly distributed * {@link Integer}s./*from w ww . jav a 2 s .co m*/ * @param lower The (inclusive) lower bound of the uniform distribution. * @param upper The (inclusive) upper bound of the uniform distribution. * @return The supplier. */ public static StochasticSupplier<Integer> uniformInt(int lower, int upper) { return new IntegerDistributionSS(new UniformIntegerDistribution(new MersenneTwister(), lower, upper)); }
From source file:io.coala.random.impl.RandomDistributionFactoryImpl.java
@Override public RandomNumberDistribution<Integer> getUniformInteger(final RandomNumberStream rng, final Number lower, final Number upper) { final IntegerDistribution dist = new UniformIntegerDistribution( RandomNumberStream.Util.asCommonsRandomGenerator(rng), lower.intValue(), upper.intValue()); return new RandomNumberDistribution<Integer>() { @Override/* ww w .ja v a 2 s .com*/ public Integer draw() { return dist.sample(); } }; }
From source file:hivemall.anomaly.ChangeFinder2DTest.java
public void testSota5D() throws HiveException { final int DIM = 5; final int EXAMPLES = 20001; final Double[] x = new Double[DIM]; final List<Double> xList = Arrays.asList(x); Parameters params = new Parameters(); params.set(LossFunction.logloss);//from w w w . j a v a 2 s . com params.r1 = 0.01d; params.k = 10; params.T1 = 10; params.T2 = 10; PrimitiveObjectInspector oi = PrimitiveObjectInspectorFactory.javaDoubleObjectInspector; ListObjectInspector listOI = ObjectInspectorFactory.getStandardListObjectInspector(oi); final ChangeFinder2D cf = new ChangeFinder2D(params, listOI); final double[] outScores = new double[2]; RandomGenerator rng1 = new Well19937c(31L); final UniformIntegerDistribution uniform = new UniformIntegerDistribution(rng1, 0, 10); RandomGenerator rng2 = new Well19937c(41L); final PoissonDistribution poissonEvent = new PoissonDistribution(rng2, 1000.d, PoissonDistribution.DEFAULT_EPSILON, PoissonDistribution.DEFAULT_MAX_ITERATIONS); final StringBuilder buf = new StringBuilder(256); println("# time x0 x1 x2 x3 x4 mean0 mean1 mean2 mean3 mean4 outlier change"); FIN: for (int i = 0; i < EXAMPLES;) { int len = poissonEvent.sample(); double data[][] = new double[DIM][len]; double mean[] = new double[DIM]; double sd[] = new double[DIM]; for (int j = 0; j < DIM; j++) { mean[j] = uniform.sample() * 5.d; sd[j] = uniform.sample() / 10.d * 5.d + 1.d; if (i % 5 == 0) { mean[j] += 50.d; } NormalDistribution normDist = new NormalDistribution(new Well19937c(i + j), mean[j], sd[j]); data[j] = normDist.sample(len); data[j][len / (j + 2) + DIM % (j + 1)] = mean[j] + (j + 4) * sd[j]; } for (int j = 0; j < len; j++) { if (i >= EXAMPLES) { break FIN; } x[0] = data[0][j]; x[1] = data[1][j]; x[2] = data[2][j]; x[3] = data[3][j]; x[4] = data[4][j]; cf.update(xList, outScores); buf.append(i).append(' ').append(x[0].doubleValue()).append(' ').append(x[1].doubleValue()) .append(' ').append(x[2].doubleValue()).append(' ').append(x[3].doubleValue()).append(' ') .append(x[4].doubleValue()).append(' ').append(mean[0]).append(' ').append(mean[1]) .append(' ').append(mean[2]).append(' ').append(mean[3]).append(' ').append(mean[4]) .append(' ').append(outScores[0]).append(' ').append(outScores[1]); println(buf.toString()); StringUtils.clear(buf); i++; } } }
From source file:com.vsthost.rnd.jdeoptim.DE.java
/** * Computes and returns a new population. * * @return A new population./*from w w w . ja v a 2s . c o m*/ */ private void generatePopulation() { // Declare and initialize the new population: double[][] newPopulation = new double[this.populationSize][]; // Declare and initialize the new population scores: double[] newScores = new double[this.populationSize]; // Define a uniform distribution: UniformIntegerDistribution distributionForCol = new UniformIntegerDistribution(this.randomGenerator, 0, this.dimension - 1); UniformIntegerDistribution distributionForRow = new UniformIntegerDistribution(this.randomGenerator, 0, this.populationSize - 1); UniformRealDistribution distributionForCO = new UniformRealDistribution(this.randomGenerator, 0, 1); // Iterate over the current population: for (int c = 0; c < this.populationSize; c++) { // Get the candidate as the base of the next candidate (a.k.a. trial): double[] trial = Arrays.copyOf(this.population[c], this.dimension); // TODO: Implement all strategies. // Pick a random index from the dimension to start with: int index = distributionForCol.sample(); // Get 2 elements from the population which are distinct: int r1 = -1, r2 = -1; while (c == r1 || c == r2 || r1 == r2) { r1 = distributionForRow.sample(); r2 = distributionForRow.sample(); } // Iterate over dimensions and do stuff: for (int _i = 0; _i < this.dimension; _i++) { // To crossover or not to crossover: if (distributionForCO.sample() < this.crossoverProbability) { // Using strategy "DE/best/1/bin with jitter" as in R's DEoptim package (strategy==3): trial[index] = this.bestCandidate[index] + this.weight * (distributionForCO.sample() + 0.0001) * (this.population[r1][index] - this.population[r2][index]); // Using strategy "DE/local-to-best/1/bin" as in R's DEoptim package (strategy==2): // trial[index] += this.weight * (this.population[r1][index] - this.population[r2][index]) + this.weight * (this.bestCandidate[index] - trial[index]); } // Update index: index = (index + 1) % dimension; } // // Apply limits with reflection: // for (int i = 0; i < this.lowerLimit.length; i++) { // // Check lower limit: // if (trial[i] < this.lowerLimit[i]) { // trial[i] = this.lowerLimit[i] + trial[i]; // } // // Check upper limit: // else if (trial[i] > this.upperLimit[i]) { // trial[i] = this.upperLimit[i] - trial[i]; // } // } // Apply limits: for (int i = 0; i < this.lowerLimit.length; i++) { // Check lower limit: if (trial[i] < this.lowerLimit[i]) { trial[i] = this.lowerLimit[i]; } // Check upper limit: else if (trial[i] > this.upperLimit[i]) { trial[i] = this.upperLimit[i]; } } // Compute the score of the trial: final double score = this.function.apply(trial); // Check the score of this candidate: if (score < this.scores[c]) { newPopulation[c] = trial; newScores[c] = score; } else { newPopulation[c] = this.population[c]; newScores[c] = this.scores[c]; } } // Now, reset the population and scores: this.population = newPopulation; this.scores = newScores; }
From source file:org.gitools.analysis.groupcomparison.format.math33Preview.MathArrays.java
/** * Shuffle the entries of the given array, using the * <a href="http://en.wikipedia.org/wiki/FisherYates_shuffle#The_modern_algorithm"> * FisherYates</a> algorithm./*from ww w.j a v a 2 s . c om*/ * The {@code start} and {@code pos} parameters select which portion * of the array is randomized and which is left untouched. * * @param list Array whose entries will be shuffled (in-place). * @param start Index at which shuffling begins. * @param pos Shuffling is performed for index positions between * {@code start} and either the end (if {@link Position#TAIL}) * or the beginning (if {@link Position#HEAD}) of the array. * @param rng Random number generator. */ public static void shuffle(int[] list, int start, Position pos, RandomGenerator rng) { switch (pos) { case TAIL: { for (int i = list.length - 1; i >= start; i--) { final int target; if (i == start) { target = start; } else { // NumberIsTooLargeException cannot occur. target = new UniformIntegerDistribution(rng, start, i).sample(); } final int temp = list[target]; list[target] = list[i]; list[i] = temp; } } break; case HEAD: { for (int i = 0; i <= start; i++) { final int target; if (i == start) { target = start; } else { // NumberIsTooLargeException cannot occur. target = new UniformIntegerDistribution(rng, i, start).sample(); } final int temp = list[target]; list[target] = list[i]; list[i] = temp; } } break; default: throw new MathInternalError(); // Should never happen. } }