Skip to content

Instantly share code, notes, and snippets.

@jenetics
Created January 12, 2017 21:38
Show Gist options
  • Save jenetics/5c50c39e80b475d3ad0d8c983e5e1c8f to your computer and use it in GitHub Desktop.
Save jenetics/5c50c39e80b475d3ad0d8c983e5e1c8f to your computer and use it in GitHub Desktop.
import static java.nio.file.Files.exists;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jenetics.BitGene;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.engine.Problem;
import org.jenetics.example.Knapsack.Item;
import org.jenetics.util.IO;
import org.jenetics.util.ISeq;
import org.jenetics.util.RandomRegistry;
public class EvolutionResume {
// The problem definition.
private final Problem<ISeq<Item>, BitGene, Double> knapsack =
Knapsack.of(250, RandomRegistry.getRandom());
// The evolution engine.
private final Engine<BitGene, Double> engine = Engine.builder(knapsack)
.populationSize(100)
.build();
// Run the evolution.
private EvolutionResult<BitGene, Double> run(
final EvolutionResult<BitGene, Double> last,
final AtomicBoolean proceed
) {
System.out.println("Starting evolution with existing result.");
return (last != null ? engine.stream(last) : engine.stream())
.limit(r -> proceed.get())
.collect(EvolutionResult.toBestEvolutionResult());
}
public static void main(final String[] args)
throws IOException, InterruptedException, ExecutionException
{
if (args.length == 0) {
System.out.println("Missing evolution result path.");
System.exit(1);
}
// The result path.
final Path resultPath = Paths.get(args[0]);
@SuppressWarnings("unchecked")
final EvolutionResult<BitGene, Double> result = exists(resultPath)
? (EvolutionResult<BitGene, Double>)IO.object.read(resultPath)
: null;
final AtomicBoolean proceed = new AtomicBoolean(true);
final EvolutionResume resume = new EvolutionResume();
final CompletableFuture<EvolutionResult<BitGene, Double>> future =
CompletableFuture.supplyAsync(() -> resume.run(result, proceed));
System.out.println("Evolution started.");
// Read console command: type 'exit' for stopping evolution.
while (!System.console().readLine().equals("exit"))
proceed.set(false);
System.out.println("Evolution stopped.");
// Writing the best evolution result to file.
System.out.println("Writing evolution result.");
IO.object.write(future.get(), resultPath);
System.out.println("Best fitness: " + future.get().getBestFitness());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment