{"id":50614646,"url":"https://github.com/algodesigner/genetic","last_synced_at":"2026-06-06T07:03:05.596Z","repository":{"id":155961840,"uuid":"632781998","full_name":"algodesigner/genetic","owner":"algodesigner","description":"A simple self-contained Genetic Programming library for Java","archived":false,"fork":false,"pushed_at":"2026-03-05T14:52:07.000Z","size":454,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-05T17:21:19.517Z","etag":null,"topics":["evolutionary-algorithm","evolutionary-algorithms","evolutionary-algorithms-framework","evolutionary-computation","genetic-algorithm","genetic-algorithm-framework","genetic-programming","java","library"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/algodesigner.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-04-26T05:54:32.000Z","updated_at":"2026-03-05T14:56:21.000Z","dependencies_parsed_at":null,"dependency_job_id":"a3d71bda-b546-4ff2-afd2-de7bfa9f00a5","html_url":"https://github.com/algodesigner/genetic","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/algodesigner/genetic","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/algodesigner%2Fgenetic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/algodesigner%2Fgenetic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/algodesigner%2Fgenetic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/algodesigner%2Fgenetic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/algodesigner","download_url":"https://codeload.github.com/algodesigner/genetic/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/algodesigner%2Fgenetic/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33972398,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-06T02:00:07.033Z","response_time":107,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["evolutionary-algorithm","evolutionary-algorithms","evolutionary-algorithms-framework","evolutionary-computation","genetic-algorithm","genetic-algorithm-framework","genetic-programming","java","library"],"created_at":"2026-06-06T07:03:04.727Z","updated_at":"2026-06-06T07:03:05.585Z","avatar_url":"https://github.com/algodesigner.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# algodesigner-genetic: A Lightweight Genetic Programming Library for Java\n\n[![Java](https://img.shields.io/badge/Java-8%2B-blue.svg)](https://www.oracle.com/java/)\n[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)\n\n**algodesigner-genetic** is a straightforward and easy-to-use Genetic Programming (GP) library designed for Java developers. With a focus on simplicity and clarity, it provides a minimalist framework for implementing GP algorithms without any external dependencies.\n\nThis library is ideal for educational purposes, quick prototyping, or as a foundation for more advanced genetic algorithm applications. Its intuitive design makes it accessible for both beginners and experienced developers.\n\n## Table of Contents\n\n- [Features](#features)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Core Concepts](#core-concepts)\n  - [Basic Example: Dominant Gene Evolution](#basic-example-dominant-gene-evolution)\n  - [Practical Example: Max Area Problem](#practical-example-max-area-problem)\n  - [Practical Example: Subtraction Problem](#practical-example-subtraction-problem)\n- [Customising Evolution](#customising-evolution)\n- [API Overview](#api-overview)\n  - [Key Classes](#key-classes)\n  - [Interfaces](#interfaces)\n- [Building from Source](#building-from-source)\n- [Running Tests](#running-tests)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Features\n\n- **Zero dependencies** - Pure Java implementation\n- **Simple API** - Easy to learn and use\n- **Flexible configuration** - Customisable crossover, mutation, and selection strategies\n- **Extensible design** - Implement your own fitness functions and strategies\n- **Educational focus** - Clear, readable code with comprehensive test examples\n- **Dual evolution engines** - Both simple and composite engine implementations\n\n## Installation\n\n### Manual Installation\n\nSince this is a lightweight library with no dependencies, you can simply:\n\n1. **Download the JAR**: Build the project using Ant (see below) to generate `algodesigner-genetic-0.0.2.jar`\n2. **Add to classpath**: Include the JAR in your project's classpath\n3. **Use the source**: Copy the source files directly into your project\n\n### Building from Source\n\nThe recommended way to use this library is to build it from source using Ant:\n\n```bash\n# Clone the repository\ngit clone https://github.com/algodesigner/genetic.git\ncd genetic\n\n# Build the library (compiles, runs tests, creates JAR)\nant all\n\n# The JAR will be created in the lib/ directory\n# Use: lib/algodesigner-genetic-0.0.2.jar\n```\n\n## Quick Start\n\nHere's a minimal example to get started:\n\n```java\nimport com.algodesigner.genetic.*;\n\n// Create initial generation\nGenerationBuilder builder = new GenerationBuilder();\nfor (int i = 0; i \u003c 100; i++) {\n    builder.addChromosome(\"010101010101010101010101010101010101010101010101\");\n}\nGeneration initialGeneration = builder.build();\n\n// Define fitness function\nIFitnessFunction fitnessFunction = chromosome -\u003e {\n    Gene[] genes = chromosome.getGenes();\n    int zeroCount = 0;\n    for (Gene gene : genes) {\n        if (((Character)gene.getValue()).charValue() == '0') {\n            zeroCount++;\n        }\n    }\n    return (double)zeroCount / genes.length;\n};\n\n// Create evolution engine\nEvolutionEngine engine = new EvolutionEngine(\n    initialGeneration,\n    0.7,  // crossover rate\n    0.5,  // mutation rate\n    fitnessFunction,\n    true  // elitism enabled\n);\n\n// Run evolution\nTerminationCriteria criteria = new TerminationCriteria(3000, 10000);\nengine.findSolution(1.0, criteria);\n\n// Get results\nSystem.out.println(\"Best fitness: \" + engine.getBestFitnessScore());\nSystem.out.println(\"Best chromosome: \" + engine.getGeneration().getChromosome(engine.getBestIndex()));\n```\n\n## Core Concepts\n\n### Basic Example: Dominant Gene Evolution\n\nThis example demonstrates a simple genetic algorithm where the fitness function promotes dominant genes (`0` or `1`) while ignoring \"useless\" genes (`.`):\n\n```java\n// Fitness function that favours dominant genes\nIFitnessFunction fitnessFunction = chromosome -\u003e {\n    Gene[] genes = chromosome.getGenes();\n    int zeroCount = 0;\n    int oneCount = 0;\n    for (int i = 0; i \u003c genes.length; i++) {\n        char c = ((Character)genes[i].getValue()).charValue();\n        if (c == '0')\n            zeroCount++;\n        else if (c == '1')\n            oneCount++;\n    }\n    return (double)Math.max(zeroCount, oneCount) / (double)genes.length;\n};\n\n// Create engine with initial population\nEvolutionEngine engine = new EvolutionEngine(\n    createInitialGeneration(),\n    0.7,  // crossover rate\n    0.5,  // mutation rate\n    fitnessFunction,\n    true  // elitism\n);\n\n// Run until perfect solution found or timeout\nTerminationCriteria criteria = new TerminationCriteria(1000 * 60 * 3, 10000);\nengine.findSolution(1.0, criteria);\n```\n\n**Sample Output:**\n```\nInitial generation (mixed 0s, 1s, and .s) evolves to:\n000000000000000000000000000000000000000000000000 1.0 \u003c- Winner!\n```\n\n### Practical Example: Max Area Problem\n\nThis example solves an optimisation problem to maximise area given perimeter constraints:\n\n```java\n// Fitness function for maximising area with perimeter constraint\nprivate static class FitnessFunction implements IFitnessFunction {\n    private final int maxPerimeter;\n    \n    public FitnessFunction(int maxPerimeter) {\n        this.maxPerimeter = maxPerimeter;\n    }\n    \n    @Override\n    public double evaluate(Chromosome chromosome) {\n        Gene[] genes = chromosome.getGenes();\n        int a = Integer.parseInt(\"\" + genes[0].getValue() + genes[1].getValue());\n        int b = Integer.parseInt(\"\" + genes[2].getValue() + genes[3].getValue());\n        int perimeter = 2 * (a + b);\n        if (perimeter \u003e maxPerimeter)\n            return 0;\n        return a * b;\n    }\n}\n\n// Create engine with composite strategy (multiple populations)\nCompositeEvolutionEngine engine = new CompositeEvolutionEngine(\n    createInitialGeneration(),\n    0.7,  // crossover rate\n    0.5,  // mutation rate\n    new FitnessFunction(200),\n    true, // elitism\n    3     // number of subpopulations\n);\n\nengine.findSolution(Double.MAX_VALUE, new TerminationCriteria(3000, 3000));\n```\n\n### Practical Example: Subtraction Problem\n\nThis example solves a mathematical puzzle: find three distinct digits A, B, C such that CBA - ABC produces a valid result:\n\n```java\n// Fitness function for subtraction problem\nprivate static class FitnessFunction implements IFitnessFunction {\n    private static final int CHROMOSOME_LENGTH = 9;\n    \n    @Override\n    public double evaluate(Chromosome chromosome) {\n        if (chromosome.length() != CHROMOSOME_LENGTH)\n            throw new IllegalArgumentException(\"Invalid chromosome length\");\n        \n        final String cs = chromosome.toString();\n        \n        // Decode the first three digits (A, B, C)\n        int a = cs.charAt(0) - '0';\n        int b = cs.charAt(1) - '0';\n        int c = cs.charAt(2) - '0';\n        \n        // Calculate CBA - ABC\n        int result = (c * 100 + b * 10 + a) - (a * 100 + b * 10 + c);\n        String resultStr = String.valueOf(result);\n        \n        // Evaluate fitness based on multiple criteria\n        double c1 = resultStr.indexOf(cs.charAt(0)) != -1 ? 1 : 0;  // A in result\n        double c2 = resultStr.indexOf(cs.charAt(1)) != -1 ? 1 : 0;  // B in result\n        double c3 = resultStr.indexOf(cs.charAt(2)) != -1 ? 1 : 0;  // C in result\n        double c4 = (a != b \u0026\u0026 b != c) ? 1 : 0;  // All digits distinct\n        double c5 = result \u003e 0 ? 1 : 0;  // Positive result\n        \n        return (c1 + c2 + c3 + c4 + c5) / 5;  // Average of criteria\n    }\n}\n\n// Create evolution engine\nEvolutionEngine engine = new EvolutionEngine(\n    createInitGeneration(),\n    0.7,  // crossover rate\n    0.5,  // mutation rate\n    new FitnessFunction(),\n    true  // elitism\n);\n\n// Create initial generation\nprivate static Generation createInitGeneration() {\n    GenerationBuilder builder = new GenerationBuilder();\n    // Create population of chromosomes with digits 1-9\n    builder.addChromosomes(256, \"123456789\");\n    return builder.build();\n}\n\n// Run evolution\nengine.findSolution(1.0, new TerminationCriteria(3000, 3000));\n\n// Display solution\nChromosome solution = engine.getGeneration().getChromosome(engine.getBestIndex());\nSystem.out.println(\"Solution found in \" + engine.getGenerationCount() + \" generations:\");\nSystem.out.println(\"Chromosome: \" + solution);\n```\n\n**Sample Solution:**\n```\n  CBA\n- ABC\n  ---\n  495\n```\nWhere A=4, B=9, C=5 gives 594 - 459 = 495\n\n## Customising Evolution\n\nThe library provides several customisation points:\n\n### Configuring Evolution Parameters\n\n```java\n// Create engine with custom parameters\nEvolutionEngine engine = new EvolutionEngine(\n    initialGeneration,\n    0.7,   // crossover rate (0.0 to 1.0)\n    0.05,  // mutation rate (0.0 to 1.0)\n    fitnessFunction,\n    true,  // elitism (preserve best individuals)\n    new Random(12345)  // optional random seed for reproducibility\n);\n\n// Configure termination criteria\nTerminationCriteria criteria = new TerminationCriteria(\n    5000,   // maximum time in milliseconds\n    10000   // maximum number of generations\n);\n\n// Find solution with target fitness\nint solutionIndex = engine.findSolution(0.95, criteria);\n```\n\n### Implementing Custom Fitness Functions\n\n```java\npublic class MyFitnessFunction implements IFitnessFunction {\n    @Override\n    public double evaluate(Chromosome chromosome) {\n        // Decode chromosome into solution representation\n        Gene[] genes = chromosome.getGenes();\n        \n        // Calculate fitness (higher is better)\n        double fitness = 0.0;\n        // ... your fitness calculation logic\n        \n        return fitness;\n    }\n}\n```\n\n### Using Composite Evolution Engine\n\nThe `CompositeEvolutionEngine` maintains multiple subpopulations for better diversity:\n\n```java\nCompositeEvolutionEngine engine = new CompositeEvolutionEngine(\n    initialGeneration,\n    0.7,   // crossover rate\n    0.5,   // mutation rate\n    fitnessFunction,\n    true,  // elitism\n    3      // number of subpopulations\n);\n```\n\n## API Overview\n\n### Key Classes\n\n| Class | Purpose |\n|-------|---------|\n| `EvolutionEngine` | Main evolution engine with standard genetic algorithm |\n| `CompositeEvolutionEngine` | Engine with multiple subpopulations for better diversity |\n| `Chromosome` | Represents an individual solution with genes |\n| `Gene` | Basic building block of a chromosome |\n| `Generation` | Collection of chromosomes in a population |\n| `GenerationBuilder` | Helper for creating initial generations |\n| `TerminationCriteria` | Defines when evolution should stop (time/generations) |\n| `DefaultSelector` | Default selection strategy (roulette wheel) |\n\n### Interfaces\n\n| Interface | Purpose |\n|-----------|---------|\n| `IEvolutionEngine` | Evolution engine contract |\n| `IFitnessFunction` | Fitness evaluation contract |\n| `ISelector` | Selection strategy contract |\n| `ICrossoverStrategy` | Crossover strategy contract |\n| `IMutationStrategy` | Mutation strategy contract |\n\n## Building from Source\n\n### Prerequisites\n\n- Java 8 or higher\n- Apache Ant 1.9+\n\n### Using Ant\n\nThe project includes an Ant build file (`build.xml`) that handles everything:\n\n```bash\n# Build everything (compile, test, create JAR)\nant all\n\n# Run tests only\nant test\n\n# Clean all build artifacts\nant clean\n\n# Generate Javadoc documentation\nant javadoc\n\n# Just compile the source\nant compile\n\n# Create JAR file (after compilation)\nant jar\n\n# Run the example (requires jar target first)\nant run\n```\n\n### Build Output\n\nAfter running `ant all`, you'll get:\n- `lib/algodesigner-genetic-0.0.2.jar` - Main library JAR\n- `lib/algodesigner-genetic-0.0.2-sources.jar` - Source code JAR\n- `lib/algodesigner-genetic-0.0.2-javadoc.jar` - Javadoc JAR\n- Compiled classes in `obj/` directory\n\n## Running Tests\n\nThe library includes comprehensive unit tests that serve as practical examples. When you run the tests, you'll see actual evolution in action:\n\n```bash\n# Run all tests with Ant (shows evolution progress)\nant test\n\n# Example output from EvolutionEngineTest:\n# Shows initial generation with mixed 0s, 1s, and .s\n# Then shows evolved generation with dominant genes winning\n# Final output shows perfect chromosome with fitness 1.0\n```\n\nKey test files to explore:\n- `EvolutionEngineTest.java` - Basic evolution example (dominant gene problem)\n- `MaxAreaTest.java` - Optimisation problem example (maximise area with perimeter constraint)  \n- `SubtractionProblemTest.java` - Mathematical problem example (CBA - ABC puzzle)\n- `ExtendedEvolutionEngineTest.java` - Advanced usage examples (currently ignored)\n\n**Test Output Examples:**\n- **EvolutionEngineTest**: Shows chromosomes evolving from mixed patterns (`010101...`, `101010...`) to uniform solutions (`000000...` or `111111...`)\n- **SubtractionProblemTest**: Finds digits A=4, B=9, C=5 that solve 954 - 459 = 495\n- **MaxAreaTest**: Optimises rectangle dimensions to maximise area within perimeter constraints\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the BSD 3-Clause License - see the [LICENSE](https://opensource.org/license/bsd-3-clause) file for details.\n\nCopyright (c) 2008-2023, Vlad Shurupov\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falgodesigner%2Fgenetic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falgodesigner%2Fgenetic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falgodesigner%2Fgenetic/lists"}