ThreadedEvolutionaryProcess { public State<?, ?> optimize(Function f, int dim, long timeLimit, int parentDepth) throws InterruptedException, ExecutionException { long t0 = System.currentTimeMillis(); State<?, ?> s0 = new State(new double[dim], 0.5); for (Map.Entry<Integer, Mapping> entry : mappingTable.entrySet()) { s0.setMap(entry.getKey(), entry.getValue()); } pending.add(s0); while (pending.size() < threadCount) { pending.add(s0.mutate()); } do { while (working.size() < threadCount && !pending.isEmpty()) { State<?, ?> next = pending.removeFirst(); working.add(ecs.submit(new EvalTask(f, next))); processCount++; } Future<State<?, ?>> result = ecs.take(); while (result != null) { State<?, ?> r = result.get(); resultPopulation.add(r); working.remove(result); result = ecs.poll(); } State<?, ?>[] parents = new State[parentDepth]; Iterator<State<?, ?>> j = resultPopulation.iterator(); for (int i = 0; i < parentDepth && j.hasNext(); i++) { parents[i] = j.next(); } int k = 0; while (pending.size() + working.size() < threadCount) { State<?, ?> tmp = parents[(k++) % parentDepth]; pending.add(tmp.mutate()); } } while (System.currentTimeMillis() - t0 < timeLimit); while (!working.isEmpty()) { Future<State<?, ?>> result = ecs.take(); working.remove(result); resultPopulation.add(result.get()); } pool.shutdown(); return resultPopulation.peek(); } ThreadedEvolutionaryProcess(int threadCount); void setMap(int i, Mapping m); State<?, ?> optimize(Function f, int dim, long timeLimit, int parentDepth); @Override String toString();  }
@Test public void testOptimize() throws Exception { ThreadedEvolutionaryProcess ep = new ThreadedEvolutionaryProcess(50); final Random random = RandomUtils.getRandom(); ep.optimize(new ThreadedEvolutionaryProcess.Function() { @Override public double apply(double[] params) { double sum = 0; int i = 0; for (double x : params) { x = (i + 1) * (x - i); i++; sum += x * x; } try { Thread.sleep((long) Math.floor(-2 * Math.log(1 - random.nextDouble()))); } catch (InterruptedException e) { } return -sum; } }, 5, 200, 2); System.out.println(ep); }