.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_non_bounds_constraints.py: Optimization with constraints ================================ An example showing how to do optimization with general constraints using SLSQP and cobyla. .. image:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_non_bounds_constraints_001.png :class: sphx-glr-single-img .. code-block:: python import numpy as np import matplotlib.pyplot as plt from scipy import optimize x, y = np.mgrid[-2.03:4.2:.04, -1.6:3.2:.04] x = x.T y = y.T plt.figure(1, figsize=(3, 2.5)) plt.clf() plt.axes([0, 0, 1, 1]) contours = plt.contour(np.sqrt((x - 3)**2 + (y - 2)**2), extent=[-2.03, 4.2, -1.6, 3.2], cmap=plt.cm.gnuplot) plt.clabel(contours, inline=1, fmt='%1.1f', fontsize=14) plt.plot([-1.5, 0, 1.5, 0, -1.5], [ 0, 1.5, 0, -1.5, 0], 'k', linewidth=2) plt.fill_between([ -1.5, 0, 1.5], [ 0, -1.5, 0], [ 0, 1.5, 0], color='.8') plt.axvline(0, color='k') plt.axhline(0, color='k') plt.text(-.9, 2.8, '$x_2$', size=20) plt.text(3.6, -.6, '$x_1$', size=20) plt.axis('tight') plt.axis('off') # And now plot the optimization path accumulator = list() def f(x): # Store the list of function calls accumulator.append(x) return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) def constraint(x): return np.atleast_1d(1.5 - np.sum(np.abs(x))) optimize.minimize(f, np.array([0, 0]), method="SLSQP", constraints={"fun": constraint, "type": "ineq"}) accumulated = np.array(accumulator) plt.plot(accumulated[:, 0], accumulated[:, 1]) plt.show() **Total running time of the script:** ( 0 minutes 0.040 seconds) .. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_non_bounds_constraints.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_non_bounds_constraints.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_non_bounds_constraints.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_