{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "(user_guide_optimization_ga_variants)=" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Real-Valued and Integer Genetic Algorithms" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This page covers two more genotype representations built on top of the same {py:class}`~sigmaepsilon.math.optimize.ga.GeneticAlgorithm` framework used by the Binary Genetic Algorithm, see {doc}`bga`. As there, the running example is minimizing the Rosenbrock function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from typing import Iterable\n", "from numbers import Number\n", "import numpy as np\n", "\n", "\n", "def Rosenbrock(x: Iterable[Number], a: Number = 1, b: Number = 100) -> float:\n", " return (a - x[0]) ** 2 + b * (x[1] - x[0] ** 2) ** 2\n", "\n", "\n", "ranges = [[-2, 2], [-1, 3]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Real-Valued Genetic Algorithm (RGA)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you prefer to avoid the precision/chromosome-length trade-off of binary encoding, use the real-valued genetic algorithm ({py:class}`~sigmaepsilon.math.optimize.rga.RealValuedGeneticAlgorithm`), which operates directly on real-valued chromosomes (genotype and phenotype coincide) using arithmetic crossover and Gaussian mutation. It exposes the same interface as {py:class}`~sigmaepsilon.math.optimize.bga.BinaryGeneticAlgorithm`. \ud83d\udcd6 {ref}`RGA API Reference `." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "outputs": [], "source": [ "from sigmaepsilon.math.optimize.rga import RealValuedGeneticAlgorithm as RGA\n", "\n", "rga = RGA(Rosenbrock, ranges, nPop=100, minimize=True, maxage=20, seed=0)\n", "result = rga.solve()\n", "type(result), result.phenotype, result.fitness" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Integer Genetic Algorithm (IGA)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If your decision variables are natively boolean or small bounded integers (e.g. a 0/1 knapsack indicator, or a handful of discrete levels per variable) rather than continuous reals, use the integer genetic algorithm ({py:class}`~sigmaepsilon.math.optimize.iga.IntegerGeneticAlgorithm`). It reuses BGA's bit-chromosome representation and operators, but rounds the decoded value to the nearest integer instead of keeping it as a continuous float. \ud83d\udcd6 {ref}`IGA API Reference `." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "outputs": [], "source": [ "from sigmaepsilon.math.optimize import IntegerGeneticAlgorithm as IGA\n", "\n", "# a small 0/1 knapsack problem: pick a subset of items to maximize value\n", "# without exceeding a weight budget\n", "values = np.array([60, 100, 120, 80, 30])\n", "weights = np.array([10, 20, 30, 15, 5])\n", "capacity = 50\n", "\n", "\n", "def knapsack(x):\n", " total_weight = np.dot(weights, x)\n", " total_value = np.dot(values, x)\n", " penalty = 1000 * max(0, total_weight - capacity)\n", " return total_value - penalty\n", "\n", "\n", "iga = IGA(knapsack, [[0, 1]] * len(values), length=1, nPop=50, seed=0)\n", "champion = iga.solve()\n", "selection = champion.phenotype\n", "selection, champion.fitness" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`ranges` isn't limited to `[0, 1]`; any small bounded-integer domain works, e.g. `[0, 6]` for a 7-valued discrete variable. Choose `length` so that `2 ** length - 1` comfortably covers the width of the widest range:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "outputs": [], "source": [ "def f(x):\n", " return -((x[0] - 4) ** 2)\n", "\n", "\n", "iga_int = IGA(f, [[0, 6]], length=3, nPop=20, seed=2)\n", "champion = iga_int.solve()\n", "champion.phenotype" ] } ], "metadata": { "kernelspec": { "display_name": "sigmaepsilon-math-NMVzm02N-py3.12", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }