Skip to content

slickArgonian/jenetics

 
 

Repository files navigation

Jenetics

Build Status Maven Central Javadoc Code Quality: Java Total Alerts

Jenetics is an Genetic Algorithm, Evolutionary Algorithm and Genetic Programming library, respectively, written in Java. It is designed with a clear separation of the several concepts of the algorithm, e.g. Gene, Chromosome, Genotype, Phenotype, Population and fitness Function. Jenetics allows you to minimize and maximize the given fitness function without tweaking it. In contrast to other GA implementations, the library uses the concept of an evolution stream (EvolutionStream) for executing the evolution steps. Since the EvolutionStream implements the Java Stream interface, it works smoothly with the rest of the Java Stream API.

Other languages

  • Jenetics.Net: Experimental .NET Core port in C# of the base library.
  • Helisa: Scala wrapper around the Jenetics library.

Documentation

The library is fully documented (javadoc) and comes with an user manual (pdf).

Requirements

Runtime

  • JRE 8: Java runtime version 8 is needed for using the library, respectively for running the examples.

Build time

  • JDK 8: The Java JDK 8 must be installed.
  • Gradle 5.x: Gradle is used for building the library. (Gradle is download automatically, if you are using the Gradle Wrapper script ./gradlew, located in the base directory, for building the library.)

Test compile/execution

  • TestNG 6.x: Jenetics uses TestNG framework for unit tests.
  • Apache Commons Math 3.6: Library is used for testing statistical collectors.

Build Jenetics

For building the Jenetics library from source, download the most recent, stable package version from Github and extract it to some build directory.

$ unzip jenetics-<version>.zip -d <builddir>

<version> denotes the actual Jenetics version and <builddir> the actual build directory. Alternatively you can check out the master branch from Github.

$ git clone https://github.com/jenetics/jenetics.git <builddir>

Jenetics uses Gradle as build system and organizes the source into sub-projects (modules). Each sub-project is located in it’s own sub-directory:

Published projects

The following projects/modules are also published to Maven.

  • jenetics Javadoc: This project contains the source code and tests for the Jenetics core-module.
  • jenetics.ext Javadoc: This module contains additional non-standard GA operations and data types. It also contains classes for solving multi-objective problems (MOEA).
  • jenetics.prog Javadoc: The modules contains classes which allows to do genetic programming (GP). It seamlessly works with the existing EvolutionStream and evolution Engine.
  • jenetics.xml Javadoc: XML marshalling module for the Jenetics base data structures.

Non-published projects

  • jenetics.example: This project contains example code for the core-module.
  • jenetics.doc: Contains the code of the web-site and the manual.
  • jenetics.tool: This module contains classes used for doing integration testing and algorithmic performance testing. It is also used for creating GA performance measures and creating diagrams from the performance measures.

For building the library change into the <builddir> directory (or one of the module directory) and call one of the available tasks:

  • compileJava: Compiles the Jenetics sources and copies the class files to the <builddir>/<module-dir>/build/classes/main directory.
  • jar: Compiles the sources and creates the JAR files. The artifacts are copied to the <builddir>/<module-dir>/build/libs directory.
  • javadoc: Generates the API documentation. The Javadoc is stored in the <builddir>/<module-dir>/build/docs directory
  • test: Compiles and executes the unit tests. The test results are printed onto the console and a test-report, created by TestNG, is written to <builddir>/<module-dir> directory.
  • clean: Deletes the <builddir>/build/* directories and removes all generated artifacts.

For building the library jar from the source call

$ cd <build-dir>
$ ./gradlew jar

Example

Hello World (Ones counting)

The minimum evolution Engine setup needs a genotype factory, Factory<Genotype<?>>, and a fitness Function. The Genotype implements the Factory interface and can therefore be used as prototype for creating the initial Population and for creating new random Genotypes.

import io.jenetics.BitChromosome;
import io.jenetics.BitGene;
import io.jenetics.Genotype;
import io.jenetics.engine.Engine;
import io.jenetics.engine.EvolutionResult;
import io.jenetics.util.Factory;

public class HelloWorld {
    // 2.) Definition of the fitness function.
    private static Integer eval(Genotype<BitGene> gt) {
        return gt.getChromosome()
            .as(BitChromosome.class)
            .bitCount();
    }

    public static void main(String[] args) {
        // 1.) Define the genotype (factory) suitable
        //     for the problem.
        Factory<Genotype<BitGene>> gtf =
            Genotype.of(BitChromosome.of(10, 0.5));

        // 3.) Create the execution environment.
        Engine<BitGene, Integer> engine = Engine
            .builder(HelloWorld::eval, gtf)
            .build();

        // 4.) Start the execution (evolution) and
        //     collect the result.
        Genotype<BitGene> result = engine.stream()
            .limit(100)
            .collect(EvolutionResult.toBestGenotype());

        System.out.println("Hello World:\n" + result);
    }
}

In contrast to other GA implementations, the library uses the concept of an evolution stream (EvolutionStream) for executing the evolution steps. Since the EvolutionStream implements the Java Stream interface, it works smoothly with the rest of the Java streaming API. Now let's have a closer look at listing above and discuss this simple program step by step:

  1. The probably most challenging part, when setting up a new evolution Engine, is to transform the problem domain into a appropriate Genotype (factory) representation. In our example we want to count the number of ones of a BitChromosome. Since we are counting only the ones of one chromosome, we are adding only one BitChromosome to our Genotype. In general, the Genotype can be created with 1 to n chromosomes.

  2. Once this is done, the fitness function which should be maximized, can be defined. Utilizing the new language features introduced in Java 8, we simply write a private static method, which takes the genotype we defined and calculate it's fitness value. If we want to use the optimized bit-counting method, bitCount(), we have to cast the Chromosome<BitGene> class to the actual used BitChromosome class. Since we know for sure that we created the Genotype with a BitChromosome, this can be done safely. A reference to the eval method is then used as fitness function and passed to the Engine.build method.

  3. In the third step we are creating the evolution Engine, which is responsible for changing, respectively evolving, a given population. The Engine is highly configurable and takes parameters for controlling the evolutionary and the computational environment. For changing the evolutionary behavior, you can set different alterers and selectors. By changing the used Executor service, you control the number of threads, the Engine is allowed to use. An new Engine instance can only be created via its builder, which is created by calling the Engine.builder method.

  4. In the last step, we can create a new EvolutionStream from our Engine. The EvolutionStream is the model or view of the evolutionary process. It serves as a »process handle« and also allows you, among other things, to control the termination of the evolution. In our example, we simply truncate the stream after 100 generations. If you don't limit the stream, the EvolutionStream will not terminate and run forever. Since the EvolutionStream extends the java.util.stream.Stream interface, it integrates smoothly with the rest of the Java Stream API. The final result, the best Genotype in our example, is then collected with one of the predefined collectors of the EvolutionResult class.

Evolving images

This example tries to approximate a given image by semitransparent polygons. It comes with an Swing UI, where you can immediately start your own experiments. After compiling the sources with

$ ./gradlew compileTestJava

you can start the example by calling

$ ./jrun io.jenetics.example.image.EvolvingImages

Evolving images

The previous image shows the GUI after evolving the default image for about 4,000 generations. With the »Open« button it is possible to load other images for polygonization. The »Save« button allows to store polygonized images in PNG format to disk. At the button of the UI, you can change some of the GA parameters of the example.

Projects using Jenetics

  • Renaissance Suite: Renaissance is a modern, open, and diversified benchmark suite for the JVM, aimed at testing JIT compilers, garbage collectors, profilers, analyzers and other tools.
  • Chartsy|One: Chartsy|One is a Netbeans based tool for stock market investors and traders.
  • Chronetic: Chronetic is an open-source time pattern analysis library built to describe time-series data.
  • APP4MC: Eclipse APP4MC is a platform for engineering embedded multi- and many-core software systems.

Blogs

Citations

Release notes

Bugs

  • #550: Erroneous index check for Sample.argAt(int) method in io.jenetics.prog.regression package.
  • #554: ClassCastException in io.jenetics.prog.regression.Regression class.

Improvements

  • #534: Generify Regression classes so it can be used for regression analysis of arbitrary types.
  • #529: Implementation of Hybridizing PSM and RSM mutation operator (HPRM)
  • #518: Implementation of Symbolic Regression classes. This makes it easier to solve such optimization problems.
  • #515: Rename Tree.getIndex(Tree) to Tree.indexOf(Tree).
  • #509: Allow to collect the nth best optimization results.
final ISeq<EvolutionResult<DoubleGene, Double>> best = engine.stream()
    .limit(Limits.bySteadyFitness(50))
    .flatMap(MinMax.toStrictlyIncreasing())
    .collect(ISeq.toISeq(10));
  • #504: Rename Tree.getChild(int) to Tree.childAt(int).
  • #500: Implementation of Reverse Sequence mutation operator (RSM).
  • #497: Implement Boolean operators for GP.
  • #496: Implement GT operator for GP.
  • #493: Add dotty tree formatter
  • #488: Implement new tree formatter TreeFormatter.LISP. This allows to create a Lisp string representation from a given Tree.
  • #487: Re-implementation of 'MathTreePruneAlterer'. The new implementation uses the newly introduced Tree Rewriting API, implemented in #442.
  • #486: Implement TreeRewriteAlterer, based on the new Tree Rewriting API.
  • #485: Cleanup of MathExpr class.
  • #484: The Tree.toString() now returns a parentheses string.
  • #481: The parentheses tree representation now only escapes "protected" characters.
  • #469: Implementation of additional Evaluator factory methods.
  • #465: Remove fitness scaler classes. The fitness scaler doesn't carry its weight.
  • #455: Implementation of CompletableFutureEvaluator.
  • #450: Improvement of FutureEvaluator class.
  • #449: The Engine.Builder constructor is now public and is the most generic way for creating engine builder instances. All other builder factory methods are calling this primary constructor.
  • #447: Remove evolution iterators. The whole evolution is no performed via streams.
  • #442: Introduce Tree Rewriting API, which allows to define own rewrite rules/system. This is very helpful when solving GP related problems.
final TRS<String> trs = TRS.parse(
    "add(0,$x) -> $x",
    "add(S($x),$y) -> S(add($x,$y))",
    "mul(0,$x) -> 0",
    "mul(S($x),$y) -> add(mul($x,$y),$y)"
);

// Converting the input tree into its normal form.
final TreeNode<String> tree = TreeNode.parse("add(S(0),S(mul(S(0),S(S(0)))))");
trs.rewrite(tree);
assert tree.equals(TreeNode.parse("S(S(S(S(0))))"));
  • #372: Allow to define the chromosome index an Alterer is allowed to change. This allows to define alterers for specific chromosomes in a genotype.
// The genotype prototype, consisting of 4 chromosomes
final Genotype<DoubleGene> gtf = Genotype.of(
    DoubleChromosome.of(0, 1),
    DoubleChromosome.of(1, 2),
    DoubleChromosome.of(2, 3),
    DoubleChromosome.of(3, 4)
);

// Define the GA engine.
final Engine<DoubleGene, Double> engine = Engine
    .builder(gt -> gt.getGene().doubleValue(), gtf)
    .selector(new RouletteWheelSelector<>())
    .alterers(
        // The `Mutator` is used on chromosome with index 0 and 2.
        PartialAlterer.of(new Mutator<DoubleGene, Double>(), 0, 2),
        // The `MeanAlterer` is used on chromosome 3.
        PartialAlterer.of(new MeanAlterer<DoubleGene, Double>(), 3),
        // The `GaussianMutator` is used on all chromosomes.
        new GaussianMutator<>()
    )
    .build();
  • #368: Remove deprecated code.
  • #364: Clean implementation of async fitness functions.
  • #342: The Tree accessor names are no longer in a Java Bean style: getChild(int) -> childAt(int). This corresponds to the childAtPath(path) methods.
  • #331: Remove hashCode and equals method from Selector and Alterer.
  • #314: Add factory method for AdaptiveEngine, which simplifies its creation.
  • #308: General improvement of object serialization.
  • #50: Improve Genotype validation. The new Constraint interface, and its implementation RetryConstraint, now allows a finer control of the validation and recreation of individuals.

Bugs

  • #520: Fix tree-rewriting for Const values. This leads to non-matching nodes when trying to simplify the GP tree.
  • #475: Level function returns different results depending on whether the iterator is iterating through a ProgramGene or TreeNode.
  • #473: DynamicGenotype example causes IllegalArgumentException.

All Release Notes

License

The library is licensed under the Apache License, Version 2.0.

Copyright 2007-2019 Franz Wilhelmstötter

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.

Used software

IntelliJ

About

Jenetics - Java Genetic Algorithm Library

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 95.4%
  • CSS 1.4%
  • Groovy 0.9%
  • TeX 0.8%
  • Gnuplot 0.6%
  • Shell 0.3%
  • Other 0.6%