List of usage examples for org.apache.commons.math3.random JDKRandomGenerator setSeed
public void setSeed(int[] seed)
From source file:fi.smaa.common.RandomUtil.java
public static RandomUtil createWithFixedSeed() { JDKRandomGenerator engine = new JDKRandomGenerator(); engine.setSeed(666); return new RandomUtil(engine); }
From source file:com.gordoni.opal.ScenarioSet.java
public ScenarioSet(Config config, HistReturns hist, String cwd, Map<String, Object> params, String param_filename) throws ExecutionException, IOException, InterruptedException { this.config = config; this.cwd = cwd; // Override default scenario based on scenario file. boolean param_filename_is_default = (param_filename == null); if (param_filename_is_default) param_filename = config.prefix + "-scenario.txt"; File f = new File(cwd + '/' + param_filename); if (!f.exists()) { if (!param_filename_is_default) throw new FileNotFoundException(param_filename); } else {//from w w w . ja va2 s .c om BufferedReader reader = new BufferedReader(new FileReader(f)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(System.getProperty("line.separator")); } Map<String, Object> fParams = new HashMap<String, Object>(); config.load_params(fParams, stringBuilder.toString()); config.applyParams(fParams); } // Override default scenario based on command line arguments. if (params != null) config.applyParams(params); generate_stats = new VitalStats(this, config, hist, config.generate_time_periods); generate_stats.compute_stats(config.generate_life_table, 1); // Compute here so we can access death.length. validate_stats = new VitalStats(this, config, hist, config.validate_time_periods); validate_stats.compute_stats(config.validate_life_table, 1); generate_annuity_stats = new AnnuityStats(this, config, hist, generate_stats, config.generate_time_periods, config.annuity_table); validate_annuity_stats = new AnnuityStats(this, config, hist, validate_stats, config.validate_time_periods, config.annuity_table); System.out.println("Parameters:"); config.dumpParams(); System.out.println(); boolean do_compare = !config.skip_compare; Scenario compare_scenario = null; if (do_compare) { assert (config.tax_rate_div == null); assert (!config.ef.equals("none")); List<String> asset_classes = new ArrayList<String>(Arrays.asList("stocks", "bonds")); compare_scenario = new Scenario(this, config, hist, false, !config.skip_validate, asset_classes, asset_classes, config.ret_equity_premium, 1, 1, 1, null, null); } Scenario scenario = new Scenario(this, config, hist, config.compute_risk_premium, !config.skip_validate, config.asset_classes, config.asset_class_names, config.ret_equity_premium, 1, 1, 1, config.start_ria, config.start_nia); scenario.report_returns(); if (config.compute_risk_premium) return; Scenario[] error_scenario = new Scenario[config.error_count]; if (config.error_count > 0) { List<String> asset_classes = new ArrayList<String>(Arrays.asList("stocks", "bonds")); Scenario risk_premium_scenario = new Scenario(this, config, hist, true, false, asset_classes, asset_classes, config.ret_equity_premium, 1, 1, 1, config.start_ria, config.start_nia); List<double[]> rp_returns = Utils.zipDoubleArray(risk_premium_scenario.returns_generate.original_data); double n = rp_returns.get(0).length; double sample_erp_am = Utils.mean(rp_returns.get(0)); double sample_erp_sd = Utils.standard_deviation(rp_returns.get(0)); JDKRandomGenerator random = new JDKRandomGenerator(); random.setSeed(0); ChiSquaredDistribution chi_squared = new ChiSquaredDistribution(random, n - 1); LogNormalDistribution gamma_distribution = null; if (config.gamma_vol > 0) gamma_distribution = new LogNormalDistribution(random, 0, config.gamma_vol); LogNormalDistribution q_distribution = null; if (config.q_vol > 0) q_distribution = new LogNormalDistribution(random, 0, config.q_vol); for (int i = 0; i < error_scenario.length; i++) { double erp; double equity_vol_adjust; if (config.equity_premium_vol) { double population_erp_am = sample_erp_am; equity_vol_adjust = Math.sqrt((n - 1) / chi_squared.sample()); double population_erp_sd = sample_erp_sd * equity_vol_adjust; double erp_am = population_erp_am; double erp_sd = population_erp_sd / Math.sqrt(n); erp = erp_am + erp_sd * random.nextGaussian(); } else { erp = sample_erp_am; equity_vol_adjust = 1; } double gamma_adjust = ((config.gamma_vol > 0) ? gamma_distribution.sample() : 1); double q_adjust = ((config.q_vol > 0) ? q_distribution.sample() : 1); error_scenario[i] = new Scenario(this, config, hist, false, false, config.asset_classes, config.asset_class_names, erp, equity_vol_adjust, gamma_adjust, q_adjust, config.start_ria, config.start_nia); } } if (do_compare) compare_scenario.run_mvo("compare"); // Helps determine max_stocks based on risk tolerance. scenario.run_mvo("scenario"); for (int i = 0; i < error_scenario.length; i++) error_scenario[i].run_mvo("error"); executor = Executors.newFixedThreadPool(config.workers); try { if (do_compare) compare_scenario.run_compare(); scenario.run_main(); if (error_scenario.length > 0) { long start = System.currentTimeMillis(); for (int i = 0; i < error_scenario.length; i++) { if (config.trace || config.trace_error) System.out.println("error scenario " + (i + 1)); generate_stats.compute_stats(config.generate_life_table, error_scenario[i].q_adjust); error_scenario[i].run_error(); } generate_stats.compute_stats(config.generate_life_table, 1); // Reset to default. dump_error(scenario, error_scenario, "0.68", 0.68); dump_error(scenario, error_scenario, "0.95", 0.95); double elapsed = (System.currentTimeMillis() - start) / 1000.0; System.out.println("Error done: " + f1f.format(elapsed) + " seconds"); System.out.println(); } } catch (Exception | AssertionError e) { executor.shutdownNow(); throw e; } executor.shutdown(); }
From source file:objenome.NumericAnalysisTest.java
@Test public void testMultivariate() throws IncompleteSolutionException { Objenome o = Objenome.solve(new OptimizeMultivariate(ExampleMultivariateFunction.class, (Function<ExampleMultivariateFunction, Double>) s -> { double v = s.output(0.0) + s.output(0.5) + s.output(1.0); return v; }) {// ww w .j a v a 2 s . c o m @Override protected RandomGenerator getRandomGenerator() { JDKRandomGenerator j = new JDKRandomGenerator(); j.setSeed(0); return j; } }.minimize(), ExampleMultivariateFunction.class); double bestParam = ((Number) o.getSolutions().get(1)).doubleValue(); assertEquals(-2.5919, bestParam, 0.001); }
From source file:org.dllearner.algorithms.qtl.experiments.SPARQLLearningProblemsGenerator.java
public void generateBenchmark(int nrOfSPARQLQueries, final int minDepth, final int maxDepth, int minNrOfExamples) { Collection<OWLClass> classes = getClasses(); ArrayList<OWLClass> classesList = new ArrayList<>(classes); Collections.shuffle(classesList, new Random(123)); classes = classesList;// ww w. j a v a2 s . c o m // classes = Sets.newHashSet(new OWLClassImpl(IRI.create("http://semantics.crl.ibm.com/univ-bench-dl.owl#TennisFan"))); // ExecutorService tp = Executors.newFixedThreadPool(threadCount); List<Path> allPaths = new ArrayList<>(); // ThreadPoolExecutor tp = new CustomFutureReturningExecutor( // threadCount, threadCount, // 5000L, TimeUnit.MILLISECONDS, // new ArrayBlockingQueue<Runnable>(classes.size(), true)); ExecutorService tp = Executors.newFixedThreadPool(threadCount); CompletionService<List<Path>> ecs = new ExecutorCompletionService<List<Path>>(tp); JDKRandomGenerator rndGen = new JDKRandomGenerator(); rndGen.setSeed(123); int nrOfQueriesPerDepth = nrOfSPARQLQueries / (maxDepth - minDepth + 1); // for each depth <= maxDepth for (int depth = minDepth; depth <= maxDepth; depth++) { System.out.println("Generating " + nrOfQueriesPerDepth + " queries for depth " + depth); Iterator<OWLClass> iterator = classes.iterator(); // generate paths of depths <= maxDepth List<Path> pathsForDepth = new ArrayList<>(); while (pathsForDepth.size() < nrOfQueriesPerDepth && iterator.hasNext()) { Collection<Future<List<Path>>> futures = new ArrayList<>(); try { int cnt = 0; while (iterator.hasNext() && (pathsForDepth.size() + ++cnt < nrOfQueriesPerDepth)) { // pick next class OWLClass cls = iterator.next(); // int depth = rndGen.nextInt(maxDepth) + 1; Future<List<Path>> future = ecs .submit(new PathDetectionTask(dataDir, ks, schema, cls, depth, minNrOfExamples)); futures.add(future); } int n = futures.size(); try { for (int i = 0; i < n; ++i) { Future<List<Path>> f = ecs.take(); if (!f.isCancelled()) { List<Path> paths = f.get(); if (paths != null) { for (int j = 0; j < Math.min(paths.size(), maxPathsPerClassAndDepth); j++) { pathsForDepth.add(paths.get(j)); } } // System.out.println("#Paths: " + paths.size()); // paths.forEach(p -> System.out.println(p)); if (pathsForDepth.size() >= nrOfQueriesPerDepth) { break; } } } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } finally { for (Future<List<Path>> f : futures) { f.cancel(true); } } } allPaths.addAll(pathsForDepth); } // for (Future<Path> future : futures) { // try { // Path path = future.get(); // if(path != null) { // paths.add(path); // } // if(paths.size() == nrOfSPARQLQueries) { // System.err.println("Benchmark generation finished. Stopping all running threads."); // tp.shutdownNow(); // } // } catch (InterruptedException | ExecutionException e) { // e.printStackTrace(); // } // if(paths.size() == nrOfSPARQLQueries) { // System.err.println("Benchmark generation finished. Stopping all running threads."); // tp.shutdownNow(); // } // } tp.shutdownNow(); try { tp.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // try { // tp.awaitTermination(1, TimeUnit.DAYS); // } catch (InterruptedException e) { // e.printStackTrace(); // } // write queries to disk String queries = ""; for (Path path : allPaths) { System.out.println(path); queries += path.asSPARQLQuery(Var.alloc("s")) + "\n"; } File file = new File(benchmarkDirectory, "queries_" + nrOfSPARQLQueries + "_" + minDepth + "-" + maxDepth + "_" + minNrOfExamples + ".txt"); try { Files.write(queries, file, Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } }