{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "active-ipynb",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    from openmdao.utils.notebook_utils import notebook_mode\n",
    "except ImportError:\n",
    "    !python -m pip install openmdao[notebooks]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DifferentialEvolutionDriver\n",
    "\n",
    "```{note}\n",
    "DifferentialEvolutionDriver is based on SimpleGADriver and supports most of the same options and capabilities.\n",
    "```\n",
    "\n",
    "This [differential evolution](https://en.wikipedia.org/wiki/Differential_evolution) variant of a genetic algorithm optimizer supports only continuous variables. The DifferentialEvolutionDriver supports both constrained and unconstrained optimization.\n",
    "\n",
    "The DifferentialEvolutionDriver has advantages and disadvantages when compared to the SimpleGADriver:\n",
    "\n",
    " - Pros\n",
    "    - DifferentialEvolutionDriver is typically about 3 times faster than SimpleGADriver\n",
    "    - DifferentialEvolutionDriver is usually more accurate than SimpleGADriver because it does not limit the number of bits available to represent inputs\n",
    "    - DifferentialEvolutionDriver does not require the user to manually specify a number of representation bits\n",
    "\n",
    " - Cons\n",
    "    - DifferentialEvolutionDriver only supports continuous input variables; SimpleGADriver also supports discrete\n",
    "    - DifferentialEvolutionDriver does not support SimpleGADriver’s “compute_pareto” option for multi-objective optimization\n",
    "\n",
    "Genetic algorithms do not use gradient information to find optimal solutions. This makes them ideal for problems that do not have gradients or problems with many local minima where gradient information is not helpful in finding the global minimum. A well known example of this is finding the global minimum of of the Rastrigin function: ![2D Rastrigin Example](rastrigin2d.png)\n",
    "\n",
    "The example below shows an OpenMDAO solution of a higher order [Rastrigin function](https://en.wikipedia.org/wiki/Rastrigin_function)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import openmdao.api as om\n",
    "import numpy as np\n",
    "\n",
    "ORDER = 6  # dimension of problem\n",
    "span = 5   # upper and lower limits\n",
    "\n",
    "class RastriginComp(om.ExplicitComponent):\n",
    "    def setup(self):\n",
    "        self.add_input('x', np.zeros(ORDER))\n",
    "        self.add_output('y', 0.0)\n",
    "\n",
    "    def compute(self, inputs, outputs):\n",
    "        x = inputs['x']\n",
    "\n",
    "        # nth dimensional Rastrigin function, array input and scalar output\n",
    "        # global minimum at f(0,0,0...) = 0\n",
    "        n = len(x)\n",
    "        s = 10 * n\n",
    "        for i in range(n):\n",
    "            if np.abs(x[i]) < 1e-200:  # avoid underflow runtime warnings from squaring tiny numbers\n",
    "                x[i] = 0.0\n",
    "            s += x[i] * x[i] - 10 * np.cos(2 * np.pi * x[i])\n",
    "\n",
    "        outputs['y'] = s\n",
    "\n",
    "prob = om.Problem()\n",
    "\n",
    "prob.model.add_subsystem('rastrigin', RastriginComp(), promotes_inputs=['x'])\n",
    "prob.model.add_design_var('x',\n",
    "                          lower=-span * np.ones(ORDER),\n",
    "                          upper=span * np.ones(ORDER))\n",
    "prob.model.add_objective('rastrigin.y')\n",
    "\n",
    "prob.driver = om.DifferentialEvolutionDriver()\n",
    "prob.driver.options['max_gen'] = 400\n",
    "prob.driver.options['Pc'] = 0.5\n",
    "prob.driver.options['F'] = 0.5\n",
    "\n",
    "prob.setup()\n",
    "prob.run_driver()\n",
    "\n",
    "print(prob['rastrigin.y'])\n",
    "print(prob['x'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.assert_utils import assert_near_equal\n",
    "assert_near_equal(prob['rastrigin.y'], 0.0, 1e-6)\n",
    "assert_near_equal(prob['x'], np.zeros(ORDER), 1e-6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DifferentialEvolutionDriver Options"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "om.show_options_table(\"openmdao.drivers.differential_evolution_driver.DifferentialEvolutionDriver\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DifferentialEvolutionDriver Constructor\n",
    "\n",
    "The call signature for the DifferentialEvolutionDriver constructor is:\n",
    "\n",
    "```{eval-rst}\n",
    "    .. automethod:: openmdao.drivers.differential_evolution_driver.DifferentialEvolutionDriver.__init__\n",
    "       :noindex:\n",
    "``` \n",
    "\n",
    "## Using DifferentialEvolutionDriver\n",
    "\n",
    "You can change the number of generations to run the genetic algorithm by setting the “max_gen” option."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.notebook_utils import get_code\n",
    "from myst_nb import glue\n",
    "glue(\"code_src15\", get_code(\"openmdao.test_suite.components.branin.Branin\"), display=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{Admonition} `Branin` class definition \n",
    ":class: dropdown\n",
    "\n",
    "{glue:}`code_src15`\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "import openmdao.api as om\n",
    "from openmdao.test_suite.components.branin import Branin\n",
    "\n",
    "prob = om.Problem()\n",
    "model = prob.model\n",
    "\n",
    "model.add_subsystem('comp', Branin(), promotes_inputs=[('x0', 'xI'), ('x1', 'xC')])\n",
    "\n",
    "model.add_design_var('xI', lower=-5.0, upper=10.0)\n",
    "model.add_design_var('xC', lower=0.0, upper=15.0)\n",
    "model.add_objective('comp.f')\n",
    "\n",
    "prob.driver = om.DifferentialEvolutionDriver()\n",
    "prob.driver.options['max_gen'] = 5\n",
    "\n",
    "prob.setup()\n",
    "prob.run_driver()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can change the population size by setting the “pop_size” option. The default value for pop_size is 0, which means that the driver automatically computes a population size that is 20 times the total number of input variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "import openmdao.api as om\n",
    "from openmdao.test_suite.components.branin import Branin\n",
    "\n",
    "prob = om.Problem()\n",
    "model = prob.model\n",
    "\n",
    "model.add_subsystem('comp', Branin(), promotes_inputs=[('x0', 'xI'), ('x1', 'xC')])\n",
    "\n",
    "model.add_design_var('xI', lower=-5.0, upper=10.0)\n",
    "model.add_design_var('xC', lower=0.0, upper=15.0)\n",
    "model.add_objective('comp.f')\n",
    "\n",
    "prob.driver = om.DifferentialEvolutionDriver()\n",
    "prob.driver.options['pop_size'] = 10\n",
    "\n",
    "prob.setup()\n",
    "prob.run_driver()"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.1"
  },
  "nbsphinx": {
   "timeout": 90
  },
  "orphan": true
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
