Genetic Algorithm in Java
Purpose
A genetic algorithm library in Java with focus on easy usage and high performance. Genetic algorithms can be used to solve optimization problems where there's an evaluation function available (also known as cost).
The following example shows the library guessing a sequence of 30 int values with a genetic population size of 3000 hypothesis:
Requirements
The library uses Java 8 functions and will only work with Java 8 and above. There are no libraries needed besides those build-in the JDK.
Usage
Usage is done in the following steps:
- Implement your own subclass of AbstractHypothesis. The constructor can rely on the randInit() method to initialize the hypothesis.
- Instantiate the GeneticAlgorithm class with the desired parameters. Good starting values for cross-over rate is
0.3
and for mutation rate is0.05
. - Call one of the GeneticAlgorithm.findMaximum() methods with an appropriate loop condition function and hypothesis creation function. There are multiple variants: One variant for simple usage, and one variant that uses an ExecutorService to calculate the fitness in parallel threads. The loop condition stays true while you want to loop. The hypothesis creation function will usually just create a new instance of your
Abstracthypothesis
subclass.
There is a documentation online.
Example
There is a simple example that implements the challenge to guess a sequence of integer numbers. Each correct digit will increase the fitness score by one.
The example usage is shown here:
GeneticAlgorithm<IntGuessingHypothesis> algorithm = new GeneticAlgorithm<>(
0.5,
0.02,
150);
int size = 9;
Optional<IntGuessingHypothesis> max = algorithm.findMaximum(h -> Math.abs(h.calculateFitness()) < size,
() -> new IntGuessingHypothesis(size));
System.out.println("Maximum is "+max);
Including it in your projects
The recommended way of including the library into your project is using maven:
<dependency>
<groupId>de.sfuhrm</groupId>
<artifactId>geneticalgorithm</artifactId>
<version>2.0.0</version>
</dependency>
License
Copyright 2016-2021 Stephan Fuhrmann
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.