List of usage examples for org.apache.commons.math3.distribution UniformIntegerDistribution sample
@Override public int 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 ww . j a va 2 s .c o m*/ 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 . j av a 2 s. 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: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 {/* ww w . j a va 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:SimpleGui.QueryGenerator.java
/** * pqss are predicate query segments that decide the number of rows */// w ww. ja va 2 s . c o m private void createPQSS() { for (int p = 0; p < noOfPQSS; p++) { String tempPQS = ""; UniformIntegerDistribution uniform = new UniformIntegerDistribution(1, sqss.size() - 1); String attr2 = ""; String condition = ""; int tempAttr = uniform.sample(); while ((tempAttr == 0)) { // to avoid 0 tempAttr = uniform.sample(); } attr2 = sqss.get(tempAttr); // get a random value from sqss Random shouldHaveAttr2 = new Random(); int OKattr2 = shouldHaveAttr2.nextInt(4);//4 is an arbitrarily chosen to limit number of attributes if (OKattr2 >= 2) { // to have tempPQS = tempPQS + "," + attr2; condition = conditionArray[new Random().nextInt(8)]; // a value from condition //cardinality is a random number generated to give a number for size of the query long cardinality = Math.round(Math.abs(new Random().nextGaussian() * 1000)); // System.out.println("cardinality is "+cardinality); tempPQS = tempPQS + "," + condition + "-" + cardinality; } else { condition = conditionArray[new Random().nextInt(8)]; long cardinality = Math.round(Math.abs(new Random().nextGaussian() * 1000)); tempPQS = "," + condition + "-" + cardinality; } pqss.add(tempPQS);// + ">"); } }
From source file:SimpleGui.QueryGenerator.java
/** * Returns array of values in a given distribution * @param distribution/*w w w .j a v a2 s. c om*/ * @param numQs * @param mean * @param variance * @param exponentialMean * @param u_lower * @param u_upper * @return */ public int[] getDistributionValues(String distribution, int numQs, double mean, double variance, double exponentialMean, int u_lower, int u_upper, double slope, int upperBoundary) { int[] values = new int[numQs]; switch (distribution) { case "Poisson": { RandomEngine engine = new DRand(); Poisson poisson = new Poisson(mean, engine); int poissonObs = poisson.nextInt(); Normal normal = new Normal(mean, variance, engine); for (int i = 0; i < numQs; i++) { double normalObs = normal.nextDouble(); int sample = (int) Math.abs(normalObs); while (sample >= upperBoundary) { normalObs = normal.nextDouble(); sample = (int) Math.abs(normalObs); } values[i] = sample; //System.out.println(values[i]+"from poisson"); //============================================= PoissonDistribution p = new PoissonDistribution(mean); int randomInt = p.sample(); // values[i] = randomInt; } // Arrays.sort(values); break; } case "Random": { Random randomGenerator = new Random(); for (int i = 0; i < numQs; i++) { int randomInt = randomGenerator.nextInt(numQs - 1); values[i] = randomInt + 1; // to avoid '0' } break; } case "Uniform": { for (int i = 0; i < numQs; i++) { UniformIntegerDistribution u = new UniformIntegerDistribution(u_lower, u_upper); int randomInt = u.sample(); while (randomInt >= upperBoundary) { randomInt = u.sample(); } if (randomInt == 0) values[i] = randomInt + 1; // to avoid random '0' else values[i] = randomInt; } break; } case "Exponential": { for (int i = 0; i < numQs; i++) { ExponentialDistribution e = new ExponentialDistribution(exponentialMean); double exponential = e.sample(); while (exponential >= upperBoundary - 1) { exponential = e.sample(); } values[i] = new Double(exponential).intValue() + 1; //to avoid random value '0' } break; } case "Grading": { // y=mx+c. increment and then decrement for positive slopes. int constant = 0; for (int i = 0; i < numQs; i++) { constant += slope; int nextVal = new Double(constant).intValue(); System.out.println(upperBoundary); if (nextVal >= upperBoundary || nextVal < 0) { slope = -1 * slope; i--; } else values[i] = nextVal; } break; } } // Arrays.sort(values); return values; }
From source file:uk.ac.diamond.scisoft.ncd.passerelle.actors.forkjoin.NcdImageStatsForkJoinTransformer.java
private void generatePointROIList() { int[] imageShape = (int[]) ConvertUtils .convert(Arrays.copyOfRange(frames, frames.length - dimension, frames.length), int[].class); UniformIntegerDistribution randX = new UniformIntegerDistribution(0, imageShape[1] - 1); UniformIntegerDistribution randY = new UniformIntegerDistribution(0, imageShape[0] - 1); while (points.size() < numSamples) { int[] point = new int[] { randY.sample(), randX.sample() }; PointROI pointROI = new PointROI(point); if (intSector == null || intSector.containsPoint(point[1], point[0])) { if (mask == null || mask.getBoolean(point)) { points.append(pointROI); double radius = distance.compute(intSector.getPoint(), new double[] { point[0], point[1] }); radiiMap.put(new Pair<Integer, Integer>(point[1], point[0]), radius); }// w ww .j a v a2 s. c o m } } // Calculate resolution bins double[] sortedRadii = ArrayUtils.toPrimitive(radiiMap.values().toArray(new Double[] {})); Arrays.sort(sortedRadii); percentile.setData(sortedRadii); percentiles[0] = 0; percentiles[numBins] = Double.MAX_VALUE; for (int i = 1; i < numBins; i++) { double p = i * 100.0 / numBins; percentiles[i] = percentile.evaluate(p); } // Subdivide points into resolution bins for (int bin = 0; bin < numBins; bin++) { HashSet<Pair<Integer, Integer>> pointSet = new HashSet<Pair<Integer, Integer>>(); for (Entry<Pair<Integer, Integer>, Double> element : radiiMap.entrySet()) { double radius = element.getValue(); if (radius > percentiles[bin] && radius < percentiles[bin + 1]) { pointSet.add(element.getKey()); radiiMap.remove(element); } } resBins.add(pointSet); } }