List of usage examples for java.util Random nextGaussian
public synchronized double nextGaussian()
From source file:com.analog.lyric.dimple.test.solvers.gibbs.TestGibbsConjugateSampling.java
@Test public void test3() { // Adapted from MATLAB testConjugateSampling.m/test3 Random rand = new Random(42); final double priorMean = 3.0; final double priorPrecision = 0.01; final double dataMean = 10; final double dataPrecision = 0.001; final int numDatapoints = 100; double[] data = new double[numDatapoints]; double dataSum = 0.0; for (int i = 0; i < numDatapoints; ++i) { dataSum += data[i] = dataMean + rand.nextGaussian() * dataPrecision; }//from w w w .j a va2s . c o m final double expectedPrecision = priorPrecision + numDatapoints * dataPrecision; final double expectedStd = 1 / Math.sqrt(expectedPrecision); final double expectedMean = (priorMean * priorPrecision + dataSum * dataPrecision) / expectedPrecision; final FactorGraph fg = new FactorGraph(); Real mean; Real[] x; try (CurrentModel currrent = using(fg)) { mean = real("mean"); mean.setPrior(new Normal(priorMean, priorPrecision)); x = fixed("x", data); addFactor(new Normal(), mean, dataPrecision, x); } fg.setOption(DimpleOptions.randomSeed, 1L); fg.setOption(GibbsOptions.numSamples, 1000); fg.setOption(GibbsOptions.saveAllSamples, true); fg.setOption(GibbsOptions.saveAllScores, true); GibbsSolverGraph sfg = requireNonNull(fg.setSolverFactory(new GibbsSolver())); GibbsReal smean = sfg.getReal(mean); assertEquals("NormalSampler", smean.getSamplerName()); fg.solve(); double[] means = smean.getAllSamples(); assertEquals(expectedMean, StatUtils.mean(means), 0.01); assertEquals(expectedStd, Math.sqrt(StatUtils.variance(means)), .05); // Try again with slice sampler mean.setOption(GibbsOptions.realSampler, SliceSampler.class); fg.setOption(GibbsOptions.numSamples, 2000); fg.solve(); double[] means2 = smean.getAllSamples(); assertEquals("SliceSampler", smean.getSamplerName()); assertEquals("NormalSampler", sfg.getReal(x[0]).getSamplerName()); assertEquals(expectedMean, StatUtils.mean(means2), 0.1); assertEquals(expectedStd, Math.sqrt(StatUtils.variance(means2)), 0.1); // Try again with MH mean.setOption(GibbsOptions.realSampler, MHSampler.class); fg.setOption(GibbsOptions.scansPerSample, 10); fg.setOption(GibbsOptions.numSamples, 1000); fg.solve(); double[] means3 = smean.getAllSamples(); assertEquals("MHSampler", smean.getSamplerName()); assertEquals("NormalSampler", sfg.getReal(x[0]).getSamplerName()); assertEquals(expectedMean, StatUtils.mean(means3), 0.25); assertEquals(expectedStd, Math.sqrt(StatUtils.variance(means3)), 0.25); }
From source file:com.breel.wearables.shadowclock.graphics.ShapeShadow.java
public void parseJSON(String jsonFile) { if (jsonFile != null) { // Load all the JSONs with the numbers information try {/* w w w . j a va 2s. c o m*/ JSONObject obj = new JSONObject(loadJSONFromAsset(jsonFile)); Log.d(TAG, "SHAPE SHADOW JSON FILE " + jsonFile + ": LOADED"); id = obj.getString("id"); JSONArray jsonPathData; JSONArray jsonShadowData; if (!id.equals("5")) { jsonPathData = obj.getJSONArray("path"); jsonShadowData = obj.getJSONArray("shadow"); Log.d(TAG, "JSON PATH DATA LENGTH: " + jsonPathData.length() + ""); Log.d(TAG, "JSON SHADOW DATA LENGTH: " + jsonShadowData.length() + ""); shapePath.reset(); for (int i = 0; i < jsonPathData.length(); i++) { try { JSONObject elem = jsonPathData.getJSONObject(i); String type = elem.getString("type"); JSONArray data = elem.getJSONArray("data"); if (type.equals("move")) { shapePath.moveTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("line")) { shapePath.lineTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("bezier")) { shapePath.cubicTo((float) data.getInt(0), (float) data.getInt(1), (float) data.getInt(2), (float) data.getInt(3), (float) data.getInt(4), (float) data.getInt(5)); } } catch (JSONException e) { Log.d(TAG, "JSON ELEM EXCEPTION" + e.getMessage() + ""); } } shapePath.close(); Random r = new Random(); r.nextGaussian(); JSONArray holesContainer = obj.getJSONArray("holes"); Path holePath = new Path(); for (int i = 0; i < holesContainer.length(); i++) { JSONObject jsonInside = holesContainer.getJSONObject(i); JSONArray hole = jsonInside.getJSONArray("data"); holePath.reset(); for (int j = 0; j < hole.length(); j++) { try { JSONObject elem = hole.getJSONObject(j); String type = elem.getString("type"); JSONArray data = elem.getJSONArray("data"); if (type.equals("move")) { holePath.moveTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("line")) { holePath.lineTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("bezier")) { holePath.cubicTo((float) data.getInt(0), (float) data.getInt(1), (float) data.getInt(2), (float) data.getInt(3), (float) data.getInt(4), (float) data.getInt(5)); } } catch (JSONException e) { Log.d(TAG, "JSON HOLE EXCEPTION" + e.getMessage() + ""); } } holePath.close(); shapePath.op(holePath, Path.Op.DIFFERENCE); } pathTransform.reset(); pathTransform.setScale(scale + 0.04f, scale + 0.04f); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); pathTransform.setTranslate(positionX - 0.3f, positionY - 0.3f); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); int shadowTmpX; int shadowTmpY; shadowPaths.clear(); vertexArray.clear(); for (int i = 0; i < jsonShadowData.length(); i += 2) { shadowTmpX = jsonShadowData.getInt(i); shadowTmpY = jsonShadowData.getInt(i + 1); addVertex(shadowTmpX, shadowTmpY); } } else { jsonPathData = obj.getJSONArray("path"); jsonShadowData = obj.getJSONArray("shadow"); Log.d(TAG, "JSON PATH DATA LENGTH: " + jsonPathData.length() + ""); Log.d(TAG, "JSON SHADOW DATA LENGTH: " + jsonShadowData.length() + ""); shapePath.reset(); for (int i = 0; i < jsonPathData.length(); i++) { JSONArray cords = jsonPathData.getJSONArray(i); Path chunk = new Path(); chunk.reset(); for (int j = 0; j < cords.length(); j++) { try { JSONObject elem = cords.getJSONObject(j); String type = elem.getString("type"); JSONArray data = elem.getJSONArray("data"); if (type.equals("move")) { chunk.moveTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("line")) { chunk.lineTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("bezier")) { chunk.cubicTo((float) data.getInt(0), (float) data.getInt(1), (float) data.getInt(2), (float) data.getInt(3), (float) data.getInt(4), (float) data.getInt(5)); } } catch (JSONException e) { Log.d(TAG, "JSON 5 NUMBER ELEM EXCEPTION" + e.getMessage() + ""); } } chunk.close(); shapePath.op(chunk, Path.Op.UNION); } pathTransform.reset(); pathTransform.setScale(scale, scale); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); pathTransform.setTranslate(positionX, positionY); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); shadowPaths.clear(); vertexArray.clear(); int shadowTmpX; int shadowTmpY; for (int i = 0; i < jsonShadowData.length(); i++) { JSONArray coords = jsonShadowData.getJSONArray(i); for (int j = 0; j < coords.length(); j += 2) { shadowTmpX = coords.getInt(j); shadowTmpY = coords.getInt(j + 1); addVertex((float) shadowTmpX, (float) shadowTmpY); } } } } catch (JSONException e) { Log.d(TAG, "JSON ROOT EXCEPTION" + e.getMessage() + ""); } } }
From source file:picard.analysis.TheoreticalSensitivity.java
/** * Calculates the theoretical sensitivity with a given Phred-scaled quality score distribution at a constant * depth.//from www . ja va 2 s. c o m * @param depth Depth to compute sensitivity at * @param qualityHistogram Phred-scaled quality score histogram * @param logOddsThreshold Log odd threshold necessary for variant to be called * @param sampleSize sampleSize is the total number of simulations to run * @param alleleFraction the allele fraction to evaluate sensitivity at * @param randomSeed random number seed to use for random number generator * @return Theoretical sensitivity for the given arguments at a constant depth. */ public static double sensitivityAtConstantDepth(final int depth, final Histogram<Integer> qualityHistogram, final double logOddsThreshold, final int sampleSize, final double alleleFraction, final long randomSeed) { final RouletteWheel qualityRW = new RouletteWheel(trimDistribution(normalizeHistogram(qualityHistogram))); final Random randomNumberGenerator = new Random(randomSeed); final RandomGenerator rg = new Well19937c(randomSeed); final BinomialDistribution bd = new BinomialDistribution(rg, depth, alleleFraction); // Calculate mean and deviation of quality score distribution to enable Gaussian sampling below final double averageQuality = qualityHistogram.getMean(); final double standardDeviationQuality = qualityHistogram.getStandardDeviation(); int calledVariants = 0; // Sample simulated variants, and count the number that would get called. The ratio // of the number called to the total sampleSize is the sensitivity. for (int sample = 0; sample < sampleSize; sample++) { final int altDepth = bd.sample(); final int sumOfQualities; if (altDepth < LARGE_NUMBER_OF_DRAWS) { // If the number of alt reads is "small" we draw from the actual base quality distribution. sumOfQualities = IntStream.range(0, altDepth).map(n -> qualityRW.draw()).sum(); } else { // If the number of alt reads is "large" we draw from a Gaussian approximation of the base // quality distribution to speed up the code. sumOfQualities = drawSumOfQScores(altDepth, averageQuality, standardDeviationQuality, randomNumberGenerator.nextGaussian()); } if (isCalled(depth, altDepth, (double) sumOfQualities, alleleFraction, logOddsThreshold)) { calledVariants++; } } return (double) calledVariants / sampleSize; }
From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java
/********************************************** * /*from ww w . j a v a 2 s. c o m*/ * concertInfoNeedsUpdate * @param artistName * @return * **********************************************/ public boolean concertInfoNeedsUpdate(String artistName) { String artistConcertFileName = ((RockPlayer) context).FILEX_CONCERT_PATH + validateFileName(artistName); File artistConcertFile = new File(artistConcertFileName); if (artistConcertFile.exists()) { Random randomNumber = new Random(); double threshold = Math.abs(randomNumber.nextGaussian()) * SPREAD_INTVL + MIN_UPDATE_INTVL; Log.i("UPDATE", "" + System.currentTimeMillis() + "-" + artistConcertFile.lastModified() + ">" + threshold); if (System.currentTimeMillis() - artistConcertFile.lastModified() > threshold) return true; else return false; } else { Log.i("UPDATE", "File does not exist yet"); return true; } }
From source file:TestHTTPSource.java
private ResultWrapper putWithEncoding(String encoding, int n) throws Exception { Type listType = new TypeToken<List<JSONEvent>>() { }.getType();/*from ww w. j a v a 2 s . c om*/ List<JSONEvent> events = Lists.newArrayList(); Random rand = new Random(); for (int i = 0; i < n; i++) { Map<String, String> input = Maps.newHashMap(); for (int j = 0; j < 10; j++) { input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i)); } JSONEvent e = new JSONEvent(); e.setHeaders(input); e.setBody(String.valueOf(rand.nextGaussian()).getBytes(encoding)); events.add(e); } Gson gson = new Gson(); String json = gson.toJson(events, listType); StringEntity input = new StringEntity(json); input.setContentType("application/json; charset=" + encoding); postRequest.setEntity(input); HttpResponse resp = httpClient.execute(postRequest); return new ResultWrapper(resp, events); }
From source file:eu.amidst.core.inference.MAPInferenceExperiments.java
private static Assignment randomEvidence(long seed, double evidenceRatio, BayesianNetwork bn) throws UnsupportedOperationException { if (evidenceRatio <= 0 || evidenceRatio >= 1) { throw new UnsupportedOperationException("Error: invalid ratio"); }//from w w w . j a v a 2s . c o m int numVariables = bn.getVariables().getNumberOfVars(); Random random = new Random(seed); //1823716125 int numVarEvidence = (int) Math.ceil(numVariables * evidenceRatio); // Evidence on 20% of variables //numVarEvidence = 0; //List<Variable> varEvidence = new ArrayList<>(numVarEvidence); double[] evidence = new double[numVarEvidence]; Variable aux; HashMapAssignment assignment = new HashMapAssignment(numVarEvidence); int[] indexesEvidence = new int[numVarEvidence]; //indexesEvidence[0]=varInterest.getVarID(); //if (Main.VERBOSE) System.out.println(variable.getVarID()); if (Main.VERBOSE) System.out.println("Evidence:"); for (int k = 0; k < numVarEvidence; k++) { int varIndex = -1; do { varIndex = random.nextInt(bn.getNumberOfVars()); //if (Main.VERBOSE) System.out.println(varIndex); aux = bn.getVariables().getVariableById(varIndex); double thisEvidence; if (aux.isMultinomial()) { thisEvidence = random.nextInt(aux.getNumberOfStates()); } else { thisEvidence = random.nextGaussian(); } evidence[k] = thisEvidence; } while (ArrayUtils.contains(indexesEvidence, varIndex)); indexesEvidence[k] = varIndex; //if (Main.VERBOSE) System.out.println(Arrays.toString(indexesEvidence)); if (Main.VERBOSE) System.out.println("Variable " + aux.getName() + " = " + evidence[k]); assignment.setValue(aux, evidence[k]); } if (Main.VERBOSE) System.out.println(); return assignment; }
From source file:TestHTTPSource.java
@Test public void testHttpsSourceNonHttpsClient() throws Exception { Type listType = new TypeToken<List<JSONEvent>>() { }.getType();/*from ww w .j a v a 2s .com*/ List<JSONEvent> events = Lists.newArrayList(); Random rand = new Random(); for (int i = 0; i < 10; i++) { Map<String, String> input = Maps.newHashMap(); for (int j = 0; j < 10; j++) { input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i)); } input.put("MsgNum", String.valueOf(i)); JSONEvent e = new JSONEvent(); e.setHeaders(input); e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8")); events.add(e); } Gson gson = new Gson(); String json = gson.toJson(events, listType); HttpURLConnection httpURLConnection = null; try { URL url = new URL("http://0.0.0.0:" + sslPort); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.getOutputStream().write(json.getBytes()); httpURLConnection.getResponseCode(); Assert.fail("HTTP Client cannot connect to HTTPS source"); } catch (Exception exception) { Assert.assertTrue("Exception expected", true); } finally { httpURLConnection.disconnect(); } }
From source file:org.onebusaway.nyc.vehicle_tracking.impl.VehicleLocationSimulationServiceImpl.java
private CoordinatePoint applyLocationNoise(double lat, double lon, double locationSigma, Random random) { if (locationSigma == 0) return new CoordinatePoint(lat, lon); final double latRadiusInMeters = random.nextGaussian() * locationSigma; final double lonRadiusInMeters = random.nextGaussian() * locationSigma; final CoordinateBounds bounds = SphericalGeometryLibrary.bounds(lat, lon, Math.abs(latRadiusInMeters), Math.abs(lonRadiusInMeters)); final double latRadius = (bounds.getMaxLat() - bounds.getMinLat()) / 2 * (latRadiusInMeters / Math.abs(latRadiusInMeters)); final double lonRadius = (bounds.getMaxLon() - bounds.getMinLon()) / 2 * (lonRadiusInMeters / Math.abs(lonRadiusInMeters)); return new CoordinatePoint(lat + latRadius, lon + lonRadius); }
From source file:com.clust4j.utils.VecUtils.java
public static double[] randomGaussian(final int n, final Random seed, final double scalar) { if (n < 1) throw new IllegalArgumentException("illegal dimensions"); final double[] out = new double[n]; for (int i = 0; i < n; i++) out[i] = seed.nextGaussian() * scalar; return out;/*from ww w . j av a 2 s. c o m*/ }
From source file:picard.analysis.TheoreticalSensitivityTest.java
@Test(dataProvider = "sumOfGaussiansDataProvider") public void testDrawSumOfQScores(final File metricsFile, final int altDepth, final double tolerance) throws Exception { final MetricsFile<TheoreticalSensitivityMetrics, Integer> metrics = new MetricsFile<>(); try (final FileReader metricsFileReader = new FileReader(metricsFile)) { metrics.read(metricsFileReader); }//w w w . j a v a 2s . c o m final List<Histogram<Integer>> histograms = metrics.getAllHistograms(); final Histogram<Integer> qualityHistogram = histograms.get(1); final TheoreticalSensitivity.RouletteWheel qualityRW = new TheoreticalSensitivity.RouletteWheel( TheoreticalSensitivity .trimDistribution(TheoreticalSensitivity.normalizeHistogram(qualityHistogram))); final Random randomNumberGenerator = new Random(51); // Calculate mean and deviation of quality score distribution to enable Gaussian sampling below final double averageQuality = qualityHistogram.getMean(); final double standardDeviationQuality = qualityHistogram.getStandardDeviation(); for (int k = 0; k < 1; k++) { int sumOfQualitiesFull = IntStream.range(0, altDepth).map(n -> qualityRW.draw()).sum(); int sumOfQualities = TheoreticalSensitivity.drawSumOfQScores(altDepth, averageQuality, standardDeviationQuality, randomNumberGenerator.nextGaussian()); Assert.assertEquals(sumOfQualitiesFull, sumOfQualities, sumOfQualitiesFull * tolerance); } }