{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Optimization of a two-parameter function\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n\n\n# Define the function that we are interested in\ndef sixhump(x):\n return (\n (4 - 2.1 * x[0] ** 2 + x[0] ** 4 / 3) * x[0] ** 2\n + x[0] * x[1]\n + (-4 + 4 * x[1] ** 2) * x[1] ** 2\n )\n\n\n# Make a grid to evaluate the function (for plotting)\nxlim = [-2, 2]\nylim = [-1, 1]\nx = np.linspace(*xlim) # type: ignore[call-overload]\ny = np.linspace(*ylim) # type: ignore[call-overload]\nxg, yg = np.meshgrid(x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A 2D image plot of the function\n Simple visualization in 2D\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nplt.figure()\nplt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin=\"lower\") # type: ignore[arg-type]\nplt.colorbar()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A 3D surface plot of the function\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax: Axes3D = fig.add_subplot(111, projection=\"3d\")\nsurf = ax.plot_surface(\n xg,\n yg,\n sixhump([xg, yg]),\n rstride=1,\n cstride=1,\n cmap=\"viridis\",\n linewidth=0,\n antialiased=False,\n)\n\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nax.set_zlabel(\"f(x, y)\")\nax.set_title(\"Six-hump Camelback function\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Find minima\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import scipy as sp\n\n# local minimization\nres_local = sp.optimize.minimize(sixhump, x0=[0, 0])\n\n# global minimization\nres_global = sp.optimize.differential_evolution(sixhump, bounds=[xlim, ylim])\n\nplt.figure()\n# Show the function in 2D\nplt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin=\"lower\") # type: ignore[arg-type]\nplt.colorbar()\n# Mark the minima\nplt.scatter(res_local.x[0], res_local.x[1], label=\"local minimizer\")\nplt.scatter(res_global.x[0], res_global.x[1], label=\"global minimizer\")\nplt.legend()\nplt.show()" ] } ], "metadata": { "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.12.11" } }, "nbformat": 4, "nbformat_minor": 0 }