List of usage examples for java.util Random nextDouble
public double nextDouble()
From source file:de.upb.timok.models.PDTTA.java
@Deprecated public TimedSequence createAbnormalEventSequence(Random mutation) { // choose very unlikely sequences final TIntList eventList = new TIntArrayList(); final TDoubleList timeList = new TDoubleArrayList(); boolean choseFinalState = false; int currentState = 0; while (!choseFinalState) { final List<Transition> possibleTransitions = getTransitions(currentState, true); possibleTransitions.sort((o1, o2) -> Double.compare(o1.getProbability(), o2.getProbability())); int listIndex = 3; if (possibleTransitions.size() <= listIndex) { listIndex = possibleTransitions.size() - 1; }/*from w w w . ja v a2 s .co m*/ int tempListIndex = Math.min(3, possibleTransitions.size() - 1); if (tempListIndex != listIndex) { throw new IllegalStateException(); } final List<Transition> topThree = possibleTransitions.subList(0, listIndex); final double randomValue = mutation.nextDouble(); int chosenTransitionIndex = -1; if (randomValue <= ANOMALY_TYPE_TWO_P_1) { chosenTransitionIndex = 0; } else if (randomValue > ANOMALY_TYPE_TWO_P_1 && randomValue < ANOMALY_TYPE_TWO_P_2) { chosenTransitionIndex = 1; } else { chosenTransitionIndex = 2; } int indexToTake = chosenTransitionIndex; if (indexToTake >= topThree.size()) { indexToTake = topThree.size() - 1; } tempListIndex = Math.min(chosenTransitionIndex, topThree.size() - 1); if (tempListIndex != indexToTake) { throw new IllegalStateException(); } final Transition chosenTransition = topThree.get(indexToTake); if (chosenTransition.isStopTraversingTransition() || eventList.size() > MAX_SEQUENCE_LENGTH) { choseFinalState = true; } else { currentState = chosenTransition.getToState(); final Distribution d = transitionDistributions.get(chosenTransition.toZeroProbTransition()); if (d == null) { // just do it again with other random sampling return createAbnormalEventSequence(mutation); } final double timeValue = d.sample(1, mutation)[0]; eventList.add(chosenTransition.getSymbol()); timeList.add(timeValue); } } return new TimedSequence(eventList, timeList, ClassLabel.ANOMALY); }
From source file:dk.statsbiblioteket.netark.dvenabler.DVReaderTest.java
private static File generateIndex(int documents) throws IOException { final File INDEX = new File("target/testindex.deletefreely." + documents); final long seed = new Random().nextLong(); Random random = new Random(seed); log.info("Testing with random seed" + seed); Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSION); final FieldType SINGLE_F = new FieldType(); SINGLE_F.setIndexed(true);//w w w .j a v a2 s . co m SINGLE_F.setStored(true); final FieldType MULTI_F = new FieldType(); MULTI_F.setIndexed(true); MULTI_F.setStored(true); final FieldType SEARCH_F = new FieldType(); SEARCH_F.setIndexed(true); final FieldType LONG_F = new FieldType(); LONG_F.setIndexed(true); LONG_F.setStored(true); LONG_F.setNumericType(FieldType.NumericType.LONG); final FieldType DOUBLE_F = new FieldType(); DOUBLE_F.setIndexed(true); DOUBLE_F.setStored(true); DOUBLE_F.setNumericType(FieldType.NumericType.DOUBLE); IndexWriter indexWriter = new IndexWriter(MMapDirectory.open(INDEX), new IndexWriterConfig(LUCENE_VERSION, analyzer)); for (int docID = 0; docID < documents; docID++) { Document document = new Document(); document.add(new Field(ID, Integer.toString(docID), SINGLE_F)); document.add(new Field(SEARCH, SEARCH_CONTENT + "_" + docID, SEARCH_F)); if (random.nextInt(5) > 0) { document.add(new Field(SINGLE, SINGLE_CONTENT + "_r" + random.nextInt(), SINGLE_F)); } if (random.nextInt(5) > 0) { document.add(new Field(MULTI, MULTI_CONTENT_1 + "_" + docID, MULTI_F)); if (random.nextInt(3) > 0) { document.add(new Field(MULTI, MULTI_CONTENT_2 + "_random" + random.nextInt(5), MULTI_F)); } } if (random.nextInt(5) > 0) { document.add(new LongField(LONG, random.nextLong(), LONG_F)); } if (random.nextInt(5) > 0) { document.add(new DoubleField(DOUBLE, random.nextDouble(), DOUBLE_F)); } indexWriter.addDocument(document); if (docID == documents / 3) { indexWriter.commit(); // Ensure multi-segment } } indexWriter.commit(); indexWriter.close(); return INDEX; }
From source file:com.ibm.bi.dml.test.utils.TestUtils.java
/** * <p>/*w w w. j a v a 2s. co m*/ * Generates a test matrix with the specified parameters and writes it to a * file using the text format. * </p> * <p> * Set seed to -1 to use the current time as seed. * </p> * * @param file * output file * @param rows * number of rows * @param cols * number of columns * @param min * minimum value * @param max * maximum value * @param sparsity * sparsity * @param seed * seed */ public static void generateTestMatrixToFile(String file, int rows, int cols, double min, double max, double sparsity, long seed) { try { FileSystem fs = FileSystem.get(conf); Path inFile = new Path(file); DataOutputStream out = fs.create(inFile); PrintWriter pw = new PrintWriter(out); Random random; if (seed == -1) random = TestUtils.random; else random = new Random(seed); for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j++) { if (random.nextDouble() > sparsity) continue; double value = (random.nextDouble() * (max - min) + min); if (value != 0) pw.println(i + " " + j + " " + value); } } pw.close(); out.close(); } catch (IOException e) { fail("unable to write test matrix: " + e.getMessage()); } }
From source file:com.ibm.bi.dml.test.utils.TestUtils.java
/** * <p>// w w w . j av a 2s . com * Generates a test matrix with the specified parameters as a two * dimensional array. The matrix will not contain any zero values. * </p> * <p> * Set seed to -1 to use the current time as seed. * </p> * * @param rows * number of rows * @param cols * number of columns * @param min * minimum value * @param max * maximum value * @param seed * seed * @return random matrix */ public static double[][] generateNonZeroTestMatrix(int rows, int cols, double min, double max, long seed) { double[][] matrix = new double[rows][cols]; Random random; if (seed == -1) random = TestUtils.random; else random = new Random(seed); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double randValue; do { randValue = random.nextDouble(); } while (randValue == 0); matrix[i][j] = (randValue * (max - min) + min); } } return matrix; }
From source file:sf.net.experimaestro.scheduler.SchedulerTest.java
@Test(description = "Run jobs generated at random", dataProvider = "complexDependenciesTestProvider") public void test_complex_dependencies(ComplexDependenciesParameters p) throws ExperimaestroCannotOverwrite, IOException { Random random = new Random(); long seed = p.seed == null ? random.nextLong() : p.seed; LOGGER.info("Seed is %d", seed); random.setSeed(seed);/*from w ww .j a va 2 s .co m*/ // Prepares directory and counter File jobDirectory = mkTestDir(); ThreadCount counter = new ThreadCount(); // Our set of jobs WaitingJob[] jobs = new WaitingJob[p.nbJobs]; // --- Generate the dependencies // Number of potential dependencies int nbCouples = p.nbJobs * (p.nbJobs - 1) / 2; // Maximum number of dependencies final int maxDependencies = min(p.maxDeps, nbCouples); // The list of dependencies TreeSet<Link> dependencies = new TreeSet<>(); // Number of generated dependencies int n = min(min((int) (long) (nbCouples * p.dependencyRatio * random.nextDouble()), Integer.MAX_VALUE), maxDependencies); long[] values = new long[n]; // Draw n dependencies among nbCouples possible RandomSampler.sample(n, nbCouples, n, 0, values, 0, random); LOGGER.debug("Sampling %d values from %d", n, nbCouples); for (long v : values) { final Link link = new Link(v); dependencies.add(link); LOGGER.debug("LINK %d status %d [%d]", link.from, link.to, v); assert link.from < p.nbJobs; assert link.to < p.nbJobs; assert link.from < link.to; } // --- Select the jobs that will fail ResourceState[] states = new ResourceState[jobs.length]; for (int i = 0; i < states.length; i++) states[i] = ResourceState.DONE; n = (int) max(p.minFailures, random.nextDouble() * p.failureRatio * jobs.length); long[] values2 = new long[n]; RandomSampler.sample(n, jobs.length - p.minFailureId, n, p.minFailureId, values2, 0, random); for (int i = 0; i < n; i++) states[((int) values2[i])] = ResourceState.ERROR; // --- Generate token resource final TokenResource token; if (p.token > 0) { token = Transaction.evaluate((em, t) -> { final String path = format("scheduler_test/test_complex_dependency/%s", p.name); final TokenResource _token = new TokenResource(path, p.token); _token.save(t); return _token; }); } else { token = null; } final MutableLong totalTime = new MutableLong(); // --- Generate new jobs for (int i = 0; i < jobs.length; i++) { final int j = i; Transaction.run((em, t) -> { int waitingTime = random.nextInt(p.maxExecutionTime - p.minExecutionTime) + p.minExecutionTime; jobs[j] = new WaitingJob(counter, jobDirectory, "job" + j, new Action(waitingTime, states[j] == ResourceState.DONE ? 0 : 1, 0)); totalTime.add(jobs[j].totalTime() + JOB_PROCESSING_TIME); ArrayList<String> deps = new ArrayList<>(); for (Link link : dependencies.subSet(new Link(j, 0), true, new Link(j, Integer.MAX_VALUE), true)) { assert j == link.to; jobs[j].addDependency(jobs[link.from].createDependency(null)); if (states[link.from].isBlocking()) states[j] = ResourceState.ON_HOLD; deps.add(jobs[link.from].toString()); } if (token != null) { jobs[j].addDependency(em.find(TokenResource.class, token.getId()).createDependency(null)); } jobs[j].save(t); LOGGER.debug("Job [%s] created: final=%s, deps=%s", jobs[j], states[j], Output.toString(", ", deps)); }); } LOGGER.info("Waiting for jobs status finish (%d remaining) / total time = %dms", counter.getCount(), totalTime.longValue()); waitToFinish(0, counter, jobs, totalTime.longValue(), 5); waitBeforeCheck(); int count = counter.getCount(); LOGGER.info("Finished waiting [%d]: %d jobs remaining", System.currentTimeMillis(), counter.getCount()); if (count > 0) { LOGGER.error("Time out: %d jobs were not processed", count); } // --- Check LOGGER.info("Checking job states"); int errors = 0; for (int i = 0; i < jobs.length; i++) errors += checkState(EnumSet.of(states[i]), jobs[i]); LOGGER.info("Checking job dependencies"); for (Link link : dependencies) { if (states[link.from] == ResourceState.DONE && jobs[link.to].getState() == ResourceState.DONE) errors += checkSequence(false, true, jobs[link.from], jobs[link.to]); } Assert.assertTrue(errors == 0, "Detected " + errors + " errors after running jobs"); }
From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java
/** * This method opens the FeedbackActivity from the feedback library in case if a PULL feedback is triggered with a random PULL configuration. * * @param baseURL the base URL/*from w ww . j a v a 2s . c o m*/ * @param activity the activity in which the method is called * @param applicationId the application id * @param language the language */ public static void triggerRandomPullFeedback(@NonNull final String baseURL, @NonNull final Activity activity, final long applicationId, final @NonNull String language) { Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL).addConverterFactory(GsonConverterFactory.create()) .build(); feedbackAPI fbAPI = rtf.create(feedbackAPI.class); final Call<ResponseBody> checkUpAndRunning = fbAPI.pingOrchestrator(); if (checkUpAndRunning != null) { checkUpAndRunning.enqueue(new Callback<ResponseBody>() { @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e(TAG, "Failed to ping the server. onFailure method called", t); } @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.code() == 200) { Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL) .addConverterFactory(GsonConverterFactory.create()).build(); feedbackAPI fbAPI = rtf.create(feedbackAPI.class); Call<OrchestratorConfigurationItem> result = fbAPI.getConfiguration(language, applicationId); // Asynchronous call if (result != null) { result.enqueue(new Callback<OrchestratorConfigurationItem>() { @Override public void onFailure(Call<OrchestratorConfigurationItem> call, Throwable t) { Log.e(TAG, "Failed to retrieve the configuration. onFailure method called", t); DialogUtils.showInformationDialog(activity, new String[] { activity.getResources().getString( R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) }, true); } @Override public void onResponse(Call<OrchestratorConfigurationItem> call, Response<OrchestratorConfigurationItem> response) { if (response.code() == 200) { Log.i(TAG, "Configuration successfully retrieved"); OrchestratorConfigurationItem configuration = response.body(); if (configuration != null) { List<ConfigurationItem> configurationItems = configuration .getConfigurationItems(); List<Long> shuffleIds = new ArrayList<>(); Map<Long, List<Map<String, Object>>> idParameters = new HashMap<>(); for (ConfigurationItem configurationItem : configurationItems) { if (configurationItem.getType().equals("PULL")) { shuffleIds.add(configurationItem.getId()); idParameters.put(configurationItem.getId(), configurationItem .getGeneralConfigurationItem().getParameters()); } } Random rnd = new Random(System.nanoTime()); Collections.shuffle(shuffleIds, rnd); for (int i = 0; i < shuffleIds.size(); ++i) { double likelihood = -1; // If no "showIntermediateDialog" is provided, show it boolean showIntermediateDialog = true; for (Map<String, Object> parameter : idParameters .get(shuffleIds.get(i))) { String key = (String) parameter.get("key"); // Likelihood if (key.equals("likelihood")) { likelihood = (((Double) parameter.get("value")) .floatValue()); } // Intermediate dialog if (key.equals("showIntermediateDialog")) { showIntermediateDialog = (Utils.intToBool( ((Double) parameter.get("value")).intValue())); } } if (!(rnd.nextDouble() > likelihood)) { Intent intent = new Intent(activity, FeedbackActivity.class); String jsonString = new Gson().toJson(configuration); intent.putExtra(FeedbackActivity.IS_PUSH_STRING, false); intent.putExtra(FeedbackActivity.JSON_CONFIGURATION_STRING, jsonString); intent.putExtra( FeedbackActivity.SELECTED_PULL_CONFIGURATION_INDEX_STRING, shuffleIds.get(i)); intent.putExtra(FeedbackActivity.EXTRA_KEY_BASE_URL, baseURL); intent.putExtra(FeedbackActivity.EXTRA_KEY_LANGUAGE, language); if (!showIntermediateDialog) { // Start the feedback activity without asking the user activity.startActivity(intent); break; } else { // Ask the user if (s)he would like to give feedback or not DialogUtils.PullFeedbackIntermediateDialog d = DialogUtils.PullFeedbackIntermediateDialog .newInstance(activity.getResources().getString( ch.uzh.supersede.feedbacklibrary.R.string.supersede_feedbacklibrary_pull_feedback_question_string), jsonString, shuffleIds.get(i), baseURL, language); d.show(activity.getFragmentManager(), "feedbackPopupDialog"); break; } } } } } else { Log.e(TAG, "Failed to retrieve the configuration. Response code == " + response.code()); } } }); } else { Log.e(TAG, "Failed to retrieve the configuration. Call<OrchestratorConfigurationItem> result is null"); } } else { Log.e(TAG, "The server is not up and running. Response code == " + response.code()); } } }); } else { Log.e(TAG, "Failed to ping the server. Call<ResponseBody> checkUpAndRunning result is null"); } }
From source file:eu.crisis_economics.abm.fund.FundTest.java
public void testHouseholdFundMarketInteraction() throws InsufficientFundsException { double totalInvestment; double[] householdDesiredInvestment = new double[N_HOUSEHOLDS]; double totalLoanValue; int j;/*w ww . j av a2s .c o m*/ Random rand = new Random(); rand.setSeed(12345); final MockClearingLoanMarket firstVirtualLoanMarket = new MockClearingLoanMarket(myFund, myBank, "Bonds", "3% Coupon Bond", 0.03, clearingHouse), secondVirtualLoanMarket = new MockClearingLoanMarket(myFund, myBank, "Bonds", "5% Coupon Bond", 0.05, clearingHouse); clearingHouse.addMarket(firstVirtualLoanMarket); clearingHouse.addMarket(secondVirtualLoanMarket); final List<ClearingStockMarket> stocks = new ArrayList<ClearingStockMarket>(); System.out.println("Testing Household/MutualFund/Market interaction"); for (j = 0; j < N_FIRMS; ++j) { myFund.portfolio.addStock(myFirms[j].getUniqueName()); myFirms[j].setMarketValue(10.0 * rand.nextDouble()); myFirms[j].setDividendPerShare(rand.nextDouble() * myFirms[j].getMarketValue()); final ClearingStockMarket stockMarket = new ClearingStockMarket(myFirms[j], clearingHouse); stocks.add(stockMarket); clearingHouse.addMarket(stockMarket); } myFund.setLoansToInvestIn(new AbstractCollectionProvider<ClearingLoanMarket>() { @Override public Collection<ClearingLoanMarket> get() { return clearingHouse.getMarketsOfType(ClearingLoanMarket.class); } }); myFund.setStocksToInvestIn(new AbstractCollectionProvider<ClearingStockMarket>() { @Override public Collection<ClearingStockMarket> get() { return clearingHouse.getMarketsOfType(ClearingStockMarket.class); } }); for (int i = 0; i < ITERATIONS; ++i) { totalInvestment = 0.0; for (j = 0; j < N_HOUSEHOLDS; ++j) { householdDesiredInvestment[j] = myHouseholds[j].investmentRandomAmount(); totalInvestment += householdDesiredInvestment[j]; } firstVirtualLoanMarket.expireLoans(); secondVirtualLoanMarket.expireLoans(); myFund.preClearingProcessing(); firstVirtualLoanMarket.process(); secondVirtualLoanMarket.process(); for (final ClearingStockMarket market : stocks) market.process(); myFund.postClearingProcessing(); totalLoanValue = 0.0; for (Loan loan : myFund.getAssetLoans()) { totalLoanValue += loan.getValue(); } // cashWeight = myFund.getBalance()/(myFund.marketCap()+myFund.equityCapital()); if (totalLoanValue < totalInvestment) { // Assert.assertEquals(cashWeight, // Math.min(MutualFund.INITIAL_CASH_WEIGHT, // (totalInvestment-totalLoanValue+myFund.equityCapital())/(totalInvestment+myFund.equityCapital())), // 1e-4); for (j = 0; j < N_HOUSEHOLDS; ++j) { Assert.assertEquals(myFund.getBalance(myHouseholds[j]), householdDesiredInvestment[j], 1e-8); Assert.assertEquals(myHouseholds[j].getEquity(), 200.0, 1e-8); } } Assert.assertEquals(myBank.getEquity(), 1000000.0, 1e-6); } double oldShareCount = myFund.mInvestmentAccount.getNumberOfEmittedShares(); myFund.mInvestmentAccount.recountShareDistribution(); double shareCountDrift = myFund.mInvestmentAccount.getNumberOfEmittedShares() - oldShareCount; System.out.println("Share count drift = " + shareCountDrift); myFund.portfolio.stockWeights().clear(); System.out.println("Done testing Household/MutualFund/Market interaction"); }
From source file:org.apache.flink.table.codegen.SortCodeGeneratorTest.java
private Object[] generateValues(InternalType type) { Random rnd = new Random(); int seedNum = RECORD_NUM / 5; Object[] seeds = new Object[seedNum]; seeds[0] = null;/*from w w w. ja v a 2 s. co m*/ seeds[1] = value1(type, rnd); seeds[2] = value2(type, rnd); seeds[3] = value3(type, rnd); for (int i = 4; i < seeds.length; i++) { if (type.equals(InternalTypes.BOOLEAN)) { seeds[i] = rnd.nextBoolean(); } else if (type.equals(InternalTypes.BYTE)) { seeds[i] = (byte) rnd.nextLong(); } else if (type.equals(InternalTypes.SHORT)) { seeds[i] = (short) rnd.nextLong(); } else if (type.equals(InternalTypes.INT)) { seeds[i] = rnd.nextInt(); } else if (type.equals(InternalTypes.LONG)) { seeds[i] = rnd.nextLong(); } else if (type.equals(InternalTypes.FLOAT)) { seeds[i] = rnd.nextFloat() * rnd.nextLong(); } else if (type.equals(InternalTypes.DOUBLE)) { seeds[i] = rnd.nextDouble() * rnd.nextLong(); } else if (type.equals(InternalTypes.STRING)) { seeds[i] = BinaryString.fromString(RandomStringUtils.random(rnd.nextInt(20))); } else if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; BigDecimal decimal = new BigDecimal(rnd.nextInt()).divide( new BigDecimal(ThreadLocalRandom.current().nextInt(1, 256)), ThreadLocalRandom.current().nextInt(1, 30), BigDecimal.ROUND_HALF_EVEN); seeds[i] = Decimal.fromBigDecimal(decimal, decimalType.precision(), decimalType.scale()); } else if (type instanceof ArrayType || type.equals(InternalTypes.BINARY)) { byte[] bytes = new byte[rnd.nextInt(16) + 1]; rnd.nextBytes(bytes); seeds[i] = type.equals(InternalTypes.BINARY) ? bytes : BinaryArray.fromPrimitiveArray(bytes); } else if (type instanceof RowType) { RowType rowType = (RowType) type; if (rowType.getTypeAt(0).equals(InternalTypes.INT)) { seeds[i] = GenericRow.of(rnd.nextInt()); } else { seeds[i] = GenericRow.of(GenericRow.of(rnd.nextInt())); } } else if (type instanceof GenericType) { seeds[i] = new BinaryGeneric<>(rnd.nextInt(), IntSerializer.INSTANCE); } else { throw new RuntimeException("Not support!"); } } // result values Object[] results = new Object[RECORD_NUM]; for (int i = 0; i < RECORD_NUM; i++) { results[i] = seeds[rnd.nextInt(seedNum)]; } return results; }
From source file:edu.cornell.med.icb.goby.stats.TestStatistics.java
@Test public void testFDR() { final Random randomEngine = new Random(); randomEngine.setSeed(1013);/*from w ww. j a v a 2 s . c o m*/ final BonferroniAdjustment bonferroni = new BonferroniAdjustment(); final BenjaminiHochbergAdjustment fdr = new BenjaminiHochbergAdjustment(); final DifferentialExpressionResults list = new DifferentialExpressionResults(); final String statId = "t-test-P-value"; list.declareStatistic(statId); final int statIndex = list.getStatisticIndex(statId); final int numObservations = 100000; final double proportionOfNaN = .1; for (int i = 0; i < numObservations; i++) { final DifferentialExpressionInfo info = new DifferentialExpressionInfo("element-" + i); info.statistics.size(list.getNumberOfStatistics()); final double random1 = randomEngine.nextDouble(); final double random2 = randomEngine.nextDouble(); info.statistics.set(statIndex, random1 < proportionOfNaN ? Double.NaN : random2); list.add(info); } final String secondPValueId = "another-p-value"; list.declareStatistic(secondPValueId); final int statIndex2 = list.getStatisticIndex(secondPValueId); for (final DifferentialExpressionInfo info : list) { info.statistics.size(list.getNumberOfStatistics()); info.statistics.set(statIndex2, randomEngine.nextDouble()); } final NormalizationMethod normalizationMethod = new AlignedCountNormalization(); bonferroni.adjust(list, normalizationMethod, statId, secondPValueId); fdr.adjust(list, normalizationMethod, statId, secondPValueId); final int index1 = list.getStatisticIndex("t-test-P-value-BH-FDR-q-value"); final int index2 = list.getStatisticIndex(secondPValueId + "-BH-FDR-q-value"); final double significanceThreshold = 0.05; int numRejectedHypothesesTest1 = 0; int numRejectedHypothesesTest2 = 0; for (final DifferentialExpressionInfo info : list) { final boolean test1 = info.statistics.getDouble(index1) > significanceThreshold; if (!test1) { // System.out.println("info:" + info); numRejectedHypothesesTest1++; } final boolean test2 = info.statistics.getDouble(index2) > significanceThreshold; if (!test2) { // System.out.println("info:" + info); numRejectedHypothesesTest2++; } } assertTrue("No q-value should be significant after FDR adjustment", numRejectedHypothesesTest1 < significanceThreshold * numObservations); assertTrue("No q-value should be significant after FDR adjustment", numRejectedHypothesesTest2 < significanceThreshold * numObservations); // System.out.println("list.adjusted: " + list); final int n = p.length; for (int rank = p.length; rank >= 1; rank--) { final int index = rank - 1; assertEquals("rank: " + rank, adjusted_R_nocummin[index], p[index] * (((double) n) / (double) rank), 0.01); } { final DifferentialExpressionResults list3 = fdr.adjust(toList(p), "p-value"); System.out.println("list3:" + list3); final int index = list3.getStatisticIndex("p-value-BH-FDR-q-value"); for (final DifferentialExpressionInfo infoAdjusted : list3) { final int elementIndex = Integer.parseInt(infoAdjusted.getElementId().toString()); assertEquals("adjusted p-values must match for i=" + infoAdjusted.getElementId(), adjusted_R[elementIndex], infoAdjusted.statistics.get(index), 0.01); } } }
From source file:eu.cloudscale.showcase.db.services.AService.java
public String getRandomString(int min, int max) { String newstring = new String(); Random rand = new Random(); int i;/* w w w .ja v a 2 s . c o m*/ final char[] chars = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '=', '+', '{', '}', '[', ']', '|', ':', ';', ',', '.', '?', '/', '~', ' ' }; // 79 // characters int strlen = (int) Math.floor(rand.nextDouble() * (max - min + 1)); strlen += min; for (i = 0; i < strlen; i++) { char c = chars[(int) Math.floor(rand.nextDouble() * 79)]; newstring = newstring.concat(String.valueOf(c)); } return newstring; }