List of usage examples for java.util Random nextDouble
public double nextDouble()
From source file:pltag.parser.params.SparseVec.java
@Override public Vec set(final Random random, final double min, final double max, final double noise) { try {/*w w w . j av a 2 s . c o m*/ counts.mapToSelf(new UnivariateRealFunction() { @Override public double value(double d) throws FunctionEvaluationException { return Math.pow(min + (random.nextDouble() * ((max - min) + 1)), noise); } }); } catch (FunctionEvaluationException ex) { LogInfo.error(ex); } return computeSum(); }
From source file:pltag.parser.params.SparseVec.java
public Vec set(final Random random, final double noise, final TypeAdd type) { try {//from www. j a va2 s . c o m counts.mapToSelf(new UnivariateRealFunction() { @Override public double value(double d) throws FunctionEvaluationException { return (type == TypeAdd.RANDOM) ? Math.pow(1 + random.nextDouble(), noise) : random.nextDouble() * noise; } }); } catch (FunctionEvaluationException ex) { LogInfo.error(ex); } return computeSum(); }
From source file:br.upe.ecomp.doss.algorithm.pso.PSO.java
protected double[] getInitialVelocity() { Random random = new Random(System.nanoTime()); double[] velocity = new double[this.dimensions]; for (int i = 0; i < this.dimensions; i++) { // The initial velocity ought be a value between zero and one velocity[i] = random.nextDouble(); }//w w w . j av a2 s .c o m return velocity; }
From source file:org.rapidandroid.activity.FormReviewer.java
private Date getRandomDate() { Calendar cdr = Calendar.getInstance(); // cdr.set(1999, 1, 1); cdr.set(Calendar.MONTH, cdr.get(Calendar.MONTH) - 3); cdr.set(Calendar.HOUR_OF_DAY, 0); cdr.set(Calendar.MINUTE, 0);/* w w w . j a v a 2 s . c om*/ cdr.set(Calendar.SECOND, 0); long val1 = cdr.getTimeInMillis(); cdr = Calendar.getInstance(); cdr.set(Calendar.HOUR_OF_DAY, 23); cdr.set(Calendar.MINUTE, 59); cdr.set(Calendar.SECOND, 0); long val2 = cdr.getTimeInMillis(); Random random = new Random(); long randomTS = (long) (random.nextDouble() * (val2 - val1)) + val1; Date d = new Date(randomTS); return d; }
From source file:com.twitter.graphjet.bipartite.GraphConcurrentTestHelper.java
/** * This helper method sets up a concurrent read-write situation with a single writer and multiple * readers that access the same underlying bipartiteGraph, and tests for correct edge access during * simultaneous edge writes. This helps test read consistency during arbitrary points of * inserting edges. Note that the exact read-write sequence here is non-deterministic and would * vary depending on the machine, but the hope is that given the large number of readers the reads * would be done at many different points of edge insertion. The test itself checks only for * partial correctness (it could have false positives) so this should only be used as a supplement * to other testing./*from w w w . j a v a 2 s . c o m*/ * * @param graph is the underlying * {@link BipartiteGraph} * @param numReadersPerNode is the number of reader threads to use per node * @param leftSize is the number of left nodes * @param rightSize is the number of right nodes * @param edgeProbability is the probability of an edge between a left-right node pair * @param random is the random number generator to use for generating a random graph */ public static <T extends BipartiteGraph & DynamicBipartiteGraph> void testRandomConcurrentReadWriteThreads( T graph, int numReadersPerNode, int leftSize, int rightSize, double edgeProbability, Random random) { int maxWaitingTimeForThreads = 20; // in milliseconds int numLeftReaders = leftSize * numReadersPerNode; int numRightReaders = rightSize * numReadersPerNode; int totalNumReaders = numLeftReaders + numRightReaders; CountDownLatch readersDoneLatch = new CountDownLatch(totalNumReaders); // First, construct a random set of edges to insert in the graph Set<Pair<Long, Long>> edges = Sets .newHashSetWithExpectedSize((int) (leftSize * rightSize * edgeProbability)); List<BipartiteGraphReader> leftReaders = Lists.newArrayListWithCapacity(numLeftReaders); List<BipartiteGraphReader> rightReaders = Lists.newArrayListWithCapacity(numRightReaders); Long2ObjectMap<LongSet> leftSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize); Long2ObjectMap<LongSet> rightSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize); int averageLeftDegree = (int) (rightSize * edgeProbability); for (int i = 0; i < leftSize; i++) { LongSet nodeEdges = new LongOpenHashSet(averageLeftDegree); for (int j = 0; j < rightSize; j++) { if (random.nextDouble() < edgeProbability) { nodeEdges.add(j); if (!rightSideGraph.containsKey(j)) { rightSideGraph.put(j, new LongOpenHashSet(new long[] { i })); } else { rightSideGraph.get(j).add(i); } edges.add(Pair.of((long) i, (long) j)); } } leftSideGraph.put(i, nodeEdges); } // Create a bunch of leftReaders per node that'll read from the graph at random for (int i = 0; i < leftSize; i++) { for (int j = 0; j < numReadersPerNode; j++) { leftReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, true, random.nextInt(maxWaitingTimeForThreads))); } } // Create a bunch of rightReaders per node that'll read from the graph at random for (int i = 0; i < rightSize; i++) { for (int j = 0; j < numReadersPerNode; j++) { rightReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, false, random.nextInt(maxWaitingTimeForThreads))); } } // Create a single writer that will insert these edges in random order List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(edges.size()); List<Pair<Long, Long>> edgesList = Lists.newArrayList(edges); Collections.shuffle(edgesList); CountDownLatch writerDoneLatch = new CountDownLatch(edgesList.size()); for (Pair<Long, Long> edge : edgesList) { writerInfo.add(new WriterInfo(edge.getLeft(), edge.getRight(), new CountDownLatch(0), writerDoneLatch)); } ExecutorService executor = Executors.newFixedThreadPool(totalNumReaders + 1); // single writer List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(totalNumReaders + 1); // First, we add the writer allThreads.add(Executors.callable(new BipartiteGraphWriter(graph, writerInfo), 1)); // then the readers for (int i = 0; i < numLeftReaders; i++) { allThreads.add(Executors.callable(leftReaders.get(i), 1)); } for (int i = 0; i < numRightReaders; i++) { allThreads.add(Executors.callable(rightReaders.get(i), 1)); } // these will execute in some non-deterministic order Collections.shuffle(allThreads, random); // Wait for all the processes to finish try { List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS); for (Future<Integer> result : results) { assertTrue(result.isDone()); assertEquals(1, result.get().intValue()); } } catch (InterruptedException e) { throw new RuntimeException("Execution for a thread was interrupted: ", e); } catch (ExecutionException e) { throw new RuntimeException("Execution issue in an executor thread: ", e); } // confirm that these worked as expected try { readersDoneLatch.await(); writerDoneLatch.await(); } catch (InterruptedException e) { throw new RuntimeException("Execution for a latch was interrupted: ", e); } // Check that all readers' read info is consistent with the graph // first check the left side for (int i = 0; i < numLeftReaders; i++) { LongSet expectedLeftEdges = leftSideGraph.get(leftReaders.get(i).queryNode); assertTrue(leftReaders.get(i).getQueryNodeDegree() <= expectedLeftEdges.size()); if (leftReaders.get(i).getQueryNodeDegree() == 0) { assertNull(leftReaders.get(i).getQueryNodeEdges()); } else { for (long edge : leftReaders.get(i).getQueryNodeEdges()) { assertTrue(expectedLeftEdges.contains(edge)); } } } // then the right side for (int i = 0; i < numRightReaders; i++) { LongSet expectedRightEdges = rightSideGraph.get(rightReaders.get(i).queryNode); assertTrue(rightReaders.get(i).getQueryNodeDegree() <= expectedRightEdges.size()); if (rightReaders.get(i).getQueryNodeDegree() == 0) { assertNull(rightReaders.get(i).getQueryNodeEdges()); } else { for (long edge : rightReaders.get(i).getQueryNodeEdges()) { assertTrue(expectedRightEdges.contains(edge)); } } } }
From source file:org.lenskit.pf.HPFModelProvider.java
/** * Initialization of parameter matrices// w w w. ja v a 2 s . co m * @param gammaShp * @param gammaRte * @param kappaRte * @param kappaShp * @param lambdaShp * @param lambdaRte * @param tauRte * @param tauShp */ public void initialize(RealMatrix gammaShp, RealMatrix gammaRte, RealVector kappaRte, RealVector kappaShp, RealMatrix lambdaShp, RealMatrix lambdaRte, RealVector tauRte, RealVector tauShp) { final int userNum = ratings.getUserIndex().size(); final int itemNum = ratings.getItemIndex().size(); final int featureCount = hyperParameters.getFeatureCount(); final double a = hyperParameters.getUserWeightShpPrior(); final double aPrime = hyperParameters.getUserActivityShpPrior(); final double bPrime = hyperParameters.getUserActivityPriorMean(); final double c = hyperParameters.getItemWeightShpPrior(); final double cPrime = hyperParameters.getItemActivityShpPrior(); final double dPrime = hyperParameters.getItemActivityPriorMean(); // Initialization Random random = new Random(rndSeed); final double kRte = aPrime + featureCount; final double tRte = cPrime + featureCount; for (int u = 0; u < userNum; u++) { for (int k = 0; k < featureCount; k++) { double valueShp = a + maxOffsetShp * random.nextDouble(); double valueRte = aPrime + maxOffsetRte * random.nextDouble(); gammaShp.setEntry(u, k, valueShp); gammaRte.setEntry(u, k, valueRte); } double kShp = aPrime + maxOffsetShp * random.nextDouble(); kappaRte.setEntry(u, kRte); kappaShp.setEntry(u, kShp); } for (int i = 0; i < itemNum; i++) { for (int k = 0; k < featureCount; k++) { double valueShp = c + maxOffsetShp * random.nextDouble(); double valueRte = cPrime + maxOffsetRte * random.nextDouble(); lambdaShp.setEntry(i, k, valueShp); lambdaRte.setEntry(i, k, valueRte); } double tShp = cPrime + maxOffsetShp * random.nextDouble(); tauRte.setEntry(i, tRte); tauShp.setEntry(i, tShp); } }
From source file:main.Driver.java
/** * Given a leadsheet file and a reference queue file, encode the leadsheet file with the autoencoder, and generate from the encoded queue for a number of divisions of a full interpolation towards the target queue * @param autoencoder// ww w .jav a 2s .c o m * @param autoencoderConnectomePath * @param inputFile * @param outputFolder * @param tradingPartSize * @param interpRange * @param interpMin * @param herdStrength * @param mutationStrength * @param crossoverStrength */ public static void populationTradingTest(ProductCompressingAutoencoder autoencoder, String autoencoderConnectomePath, File inputFile, File outputFolder, int tradingPartSize, double interpRange, double interpMin, double herdStrength, double mutationStrength, double crossoverStrength) { LeadsheetDataSequence inputSequence = leadsheetToSequence(inputFile.getPath()); LeadsheetDataSequence outputSequence = inputSequence.copy(); outputSequence.clearMelody(); LeadsheetDataSequence decoderInputSequence = outputSequence.copy(); LogTimer.log("Extending outputSequence..."); LeadsheetDataSequence humanTradingPartsSequence = inputSequence.copy(); LeadsheetDataSequence newOutputSequence = new LeadsheetDataSequence(); int numTradingParts = 0; int lastTradingPartSize = 0; while (outputSequence.hasNonMelodyDataLeft()) { LeadsheetDataSequence currExtendedPart = new LeadsheetDataSequence(); int i = 0; for (; i < tradingPartSize && outputSequence.hasNonMelodyDataLeft(); i++) { currExtendedPart.pushStep(outputSequence.pollBeats(), outputSequence.pollChords(), null); } lastTradingPartSize = i; numTradingParts++; currExtendedPart.concat(currExtendedPart.copy()); newOutputSequence.concat(currExtendedPart); } outputSequence = newOutputSequence; LogTimer.log("Setting up population..."); QueuePopulation population = new QueuePopulation(100); Random interpRand = new Random(); for (int i = 0; i < numTradingParts; i++) { LogTimer.startLog("Generating trading part..."); LogTimer.startLog("Encoding input part"); int currTradingPartSize = (i == numTradingParts - 1) ? lastTradingPartSize : tradingPartSize; for (int j = 0; j < currTradingPartSize; j++) { autoencoder.encodeStep(inputSequence.retrieve()); } LogTimer.endLog(); LogTimer.startLog("Modifying queue"); FragmentedNeuralQueue generatedQueue = autoencoder.getQueue(); FragmentedNeuralQueue modifiedQueue = generatedQueue.copy(); if (i > 0) { modifiedQueue.basicInterpolate(population.sample(), (interpRand.nextDouble() * interpRange) + interpMin); } autoencoder.setQueue(modifiedQueue); LogTimer.endLog(); LogTimer.startLog("Pushing human part"); for (int j = 0; j < currTradingPartSize; j++) { outputSequence.pushStep(null, null, humanTradingPartsSequence.pollMelody()); } LogTimer.endLog(); LogTimer.startLog("Decoding generated part"); for (int j = 0; j < currTradingPartSize; j++) { outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); } LogTimer.endLog(); LogTimer.startLog("Performing population operations"); if (i != numTradingParts - 1) { if (i > 0) { population.herd(generatedQueue, herdStrength); } population.add(generatedQueue); population.evolve(mutationStrength, crossoverStrength); } LogTimer.endLog(); refreshNetworkState(autoencoder, autoencoderConnectomePath); LogTimer.endLog(); } String fileName = inputFile.getName().replace(".ls", ""); writeLeadsheetFile(outputSequence, outputFolder.getPath(), fileName, "_TradingOutput", "Trading on " + fileName); }
From source file:com.isentropy.accumulo.test.AccumuloMapTest.java
public void testApp() { try {/*from w w w . j a v a2 s . co m*/ Connector c = new MockInstance().getConnector("root", new PasswordToken()); demo2(c); // Connector c = new ZooKeeperInstance("t0","zk:2181").getConnector("root", new PasswordToken("secret")); testLinks(c); testFixedPointSerde(c); testMapFactory(c); testMultiMap(c, 9999); testMultiMap(c, -1); testEmptyMap(); AccumuloSortedMap asm = new AccumuloSortedMap(c, "mytable" + Util.randomHexString(10)); asm.setTimeOutMs(-1); boolean err = false; try { AccumuloSortedMap asmSameNameConflict = new AccumuloSortedMap(c, asm.getTable(), true, true); } catch (AccumuloException e) { err = true; } assertTrue(err); err = false; try { AccumuloSortedMap asmSameNameNoConflict = new AccumuloSortedMap(c, asm.getTable(), true, false); } catch (AccumuloException e) { err = true; } assertFalse(err); err = false; try { AccumuloSortedMap readOnly = new AccumuloSortedMap(c, "ro" + Util.randomHexString(10), true, false); readOnly.setReadOnly(true); readOnly.put(123, 456); } catch (UnsupportedOperationException e) { err = true; } assertTrue(err); long preaddts = System.currentTimeMillis(); asm.setKeySerde(new FixedPointSerde()).setValueSerde(new FixedPointSerde()); for (long i = 0; i < 1000; i++) { asm.put(i, 2 * i); } //asm.dump(System.out); System.out.println("asm.size() = " + asm.size()); long postaddts = System.currentTimeMillis(); long ts123 = asm.getTimestamp(123); asm.regexFilter("20", "4").dump(System.out); ; //sample random range Random rand = new Random(); double r1 = rand.nextDouble(), r2 = rand.nextDouble(); double from = Math.min(r1, r2); double to = Math.max(r1, r2); long checksum = asm.sample("abc", from, to).checksum(); long checksum2 = asm.sample("abc", from, to).checksum(); //verfiy sample is the same assertTrue(checksum == checksum2); System.out.println("checksum = " + checksum); System.out.println("ts123 = " + new Date(ts123)); assertTrue(ts123 >= preaddts && ts123 <= postaddts); assertTrue(asm.timeFilter(0, preaddts - 1).size() == 0); assertTrue(asm.timeFilter(preaddts, postaddts).size() == 1000); assertTrue(asm.timeFilter(postaddts + 1, Long.MAX_VALUE).size() == 0); assertTrue(asm.containsKey(123l)); assertFalse(asm.containsKey(-123l)); assertNull(asm.get(-1)); assertTrue(asm.keySet().contains(123l)); assertTrue(asm.firstKey().equals(0l)); assertTrue(asm.get(100).equals(200l)); assertTrue(asm.size() == 1000); assertTrue(asm.values().contains(1002l)); assertFalse(asm.values().contains(1001l)); int hs = asm.headMap(123).size(); assertTrue(asm.headMap(123).size() == 123); assertTrue(asm.tailMap(123).size() == 1000 - 123); /* * for(Object o : asm.keySet()){ System.out.println("ks "+o); } */ assertTrue(asm.keySet().contains(999l)); assertFalse(asm.keySet().contains(1001l)); AccumuloSortedMap copyOfAsm = new AccumuloSortedMap(c, "othertable" + Util.randomHexString(10)); copyOfAsm.setKeySerde(new FixedPointSerde()).setValueSerde(new FixedPointSerde()); copyOfAsm.putAll(asm); int sz = asm.size(); assertTrue(copyOfAsm.size() == sz); Object o = copyOfAsm.get(101l); assertTrue(copyOfAsm.get(101l).equals(202l)); HashMap toAdd = new HashMap(); for (int x = 1000; x < 1010; x++) toAdd.put(x, 3 * x); copyOfAsm.putAll(toAdd); assertTrue(copyOfAsm.size() == sz + 10); copyOfAsm.remove(0l); assertTrue(copyOfAsm.size() == sz + 9); copyOfAsm.setClearable(true).clear(); assertTrue(copyOfAsm.size() == 0); copyOfAsm.importAll(new ImportSimulationIterator(10)); assertTrue(copyOfAsm.size() == 10); assertTrue(copyOfAsm.get(1l).equals(2l)); copyOfAsm.dump(System.out); AccumuloSortedMap transformedCopyOfAsm = new AccumuloSortedMap(c, "transformed" + Util.randomHexString(10)); transformedCopyOfAsm.setKeySerde(new FixedPointSerde()).setValueSerde(new FixedPointSerde()); transformedCopyOfAsm.putAll(asm, new KeyValueTransformer() { @Override public Entry transformKeyValue(Object fk, Object fv) { // invert key and value return new AbstractMap.SimpleEntry(fv, fk); } }); assertTrue(transformedCopyOfAsm.get(202l).equals(101l)); assertTrue(transformedCopyOfAsm.size() == sz); System.out.println("Inverted map: "); transformedCopyOfAsm.subMap(10, 20).dump(System.out); testImport(c); //asm.subMap(0, 5).dump(System.out); AccumuloSortedMap submap = asm.subMap(10, 20); err = false; try { submap.put(1, -1); } catch (UnsupportedOperationException e) { err = true; } // put should throw err in submap assertTrue(err); submap = submap.subMap(11, 33); assertTrue(submap.size() == 9); assertTrue(submap.get(11).equals(asm.get(11))); assertTrue(submap.get(12).equals(asm.get(12))); assertTrue(submap.lastKey().equals(19l)); //System.out.println("submap.get(11) = "+submap.get(11)); //System.out.println("asm.get(11) = "+asm.get(11)); System.out.println("submap(10,20).submap(11,33)"); printCollections(submap); System.out.println("submap(10,20).submap(11,33).sample(.5)"); printCollections(submap.sample(.5)); AccumuloSortedMap sample = asm.sample(.5); System.out.println("sample(.5).sample(.1)"); printCollections(sample.sample(.1)); asm.setTimeOutMs(5000); Thread.sleep(3000); asm.put(123, 345); Thread.sleep(2000); //all entries except 123 will have timed out by now. size should be 1 System.out.println("map size after sleep = " + asm.size()); assertTrue(asm.size() == 1); } catch (Exception e) { e.printStackTrace(); fail(); } }
From source file:net.lizalab.util.RdRandRandomTest.java
/** * Runs the Monte Carlo Pi approximation test for the specified * instance of Random.// w ww . jav a 2s .c om * @param random The RNG instance to test. * @param doAssert Flag to indicate whether result should be asserted or simply logged. */ private void monteCarloPiTest(Random random, boolean doAssert) { final String methodName = "monteCarloPiTest : "; int inRandCircle = 0; // xr and yr will be the random point // zr will be the calculated distance to the center double xr, yr, zr; long start = System.currentTimeMillis(); for (int i = 0; i < numPoints; i++) { xr = random.nextDouble(); yr = random.nextDouble(); zr = (xr * xr) + (yr * yr); if (zr <= 1.0) { inRandCircle++; } } long end = System.currentTimeMillis(); LOGGER.info("{} Time: {}ms", methodName, end - start); // calculate the Pi approximations double randomPi = (double) inRandCircle / numPoints * 4.0; // calculate the difference and % error double diff = (randomPi - Math.PI); double randomError = diff / Math.PI * 100; LOGGER.info("{} Pi Approximation: {}, Diff: {}, Error %: {}", methodName, randomPi, diff, randomError); BigDecimal randomPiBD = new BigDecimal(randomPi); randomPiBD = randomPiBD.setScale(precision - 1, RoundingMode.DOWN); // Verify result. boolean result = randomPiBD.compareTo(pi) == 0; String msg = "Pi approximation not sufficiently precise for " + random.getClass(); if (doAssert) { assertTrue(msg, result); } else { if (!result) { LOGGER.warn("{} {}", methodName, msg); } } }
From source file:org.jtransforms.utils.IOUtils.java
/** * Fills 3D matrix with random numbers./*from ww w . j av a2 s. c o m*/ * @param n1 slices * @param n2 rows * @param n3 columns * @param m 3D matrix */ public static void fillMatrix_3D(long n1, long n2, long n3, double[] m) { Random r = new Random(2); long sliceStride = n2 * n3; long rowStride = n3; for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { for (int k = 0; k < n3; k++) { m[(int) (i * sliceStride + j * rowStride + k)] = r.nextDouble(); } } } }