関連情報

Rosenbrock問題の最小化

Pythonによるサンプルソースコード
使用ルーチン名:nag_opt_simplex_easy

Keyword: 最適化, 最小化, minimization, rosenbrock, optimization

概要

本サンプルはRosenbrock問題の最小化の計算を行うPythonによるサンプルプログラムです。

※本サンプルはNAG Library for Pythonに含まれるルーチン nag_opt_simplex_easy() のExampleコードです。

ご相談やお問い合わせはこちらまで

出力結果例

minimising rosenbrock function

Pythonコード (minimize_rosenbrock.py)


このPythonコードをダウンロード
#!/usr/bin/env python
"NAG Minimization Graphical Example Script."

def rosenbrock(x, y):
    "The Rosenbrock function for the contour plot calculation."

    return (1 - x)**2 + 100*(y - x**2)**2

def py_obj_funct(n, xc, fc, comm):
    """
    The objective function for the NAG minimizer.
    Each evaluation point, xc, is communicated back through comm for eventual
    plotting.
    """

    from ctypes import cast, py_object

    # To communicate the function value back to the minimizer we must treat
    # fc as an array of size 1:
    fc[0] = rosenbrock(xc[0], xc[1])

    td = cast(comm[0].p, py_object).value
    td[0].append(xc[0])
    td[1].append(xc[1])

def py_monit(fmin, fmax, sim, n, ncall, serror, vratio, comm):
    "Dummy monitoring function."

class RosenbrockPlot(object):
    """
    Minimize the Rosenbrock function.
    Plot the function's contours and the solver's evaluation path.
    """

    def __init__(self):
        from matplotlib.pyplot import figure
        from numpy import arange, meshgrid

        self.startx = 0.6
        self.starty = 0.3
        self.xaxis = [-3, 3]
        self.yaxis = self.xaxis
        self.x_grid, self.y_grid = meshgrid(arange(self.xaxis[0], self.xaxis[1], 0.025),
                                            arange(self.yaxis[0], self.yaxis[1], 0.025))
        self.z_grid = rosenbrock(self.x_grid, self.y_grid)
        self.levels = [5, 25, 50, 100, 250, 500, 1000, 1500, 2000, 2500]
        fig = figure()
        fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.ax1 = fig.add_subplot(111)

    def findminimum(self):
        """
        Minimize the Rosenbrock function using e04cbc with initial guess
        (self.startx, self.starty).
        """

        from ctypes import cast
        from nag4py.e04 import nag_opt_simplex_easy
        from nag4py.util import (Nag_Comm, NAG_E04CBC_FUNCT, NAG_E04CBC_MONIT,
                                 noisy_fail, Pointer)
        from numpy import array, empty, spacing

        # Input data:
        x = array([self.startx, self.starty])
        n = len(x)
        tolf = spacing(1)
        tolx = 0.0
        maxcal = 1000
        # Output data, initialized for the NAG call:
        f = empty(1)

        # The evaluation points during the solution process will be
        # communicated back to us through comm:
        userdata = list(), list()
        comm = Nag_Comm()
        comm.p = cast(id(userdata), Pointer)

        fail = noisy_fail()

        nag_opt_simplex_easy(n, x, f, tolf, tolx,
                             NAG_E04CBC_FUNCT(py_obj_funct),
                             NAG_E04CBC_MONIT(py_monit),
                             maxcal, comm, fail)

        return userdata

    def genplot(self):
        "Generate the plot of the Rosenbrock function."

        from matplotlib import pyplot

        self.ax1.cla()
        td = self.findminimum()
        cs = self.ax1.contour(self.x_grid, self.y_grid,
                              self.z_grid, self.levels)
        self.ax1.scatter(td[0], td[1], marker='o', c='b',
                         label='Eval. pt')
        self.ax1.plot(1, 1, 'ro', markersize=10, label='Minimum')
        self.ax1.plot(self.startx, self.starty, 'go',
                      markersize=10, label='Guess')
        pyplot.legend()
        self.ax1.axis([self.xaxis[0], self.xaxis[1], self.yaxis[0], self.yaxis[1]])
        pyplot.clabel(cs, inline=1, fontsize=10)
        pyplot.title("Minimizing the Rosenbrock function starting from " +
                     "(%.3f, %.3f)" % (self.startx, self.starty))

    def onclick(self, event):
        "Replot with new initial guess."
        self.startx = event.xdata
        self.starty = event.ydata
        self.genplot()
        event.canvas.draw()

def main():
    """
    Graphical example for e04cbc using nag4py.
    Minimizes the Rosenbrock function from a selected initial guess.
    Plots the function's contours and the solver's evaluation path.
    NAG Copyright 2015.
    """

    from matplotlib import pyplot
    from nag4py.util import nag_input

    print("NAG Minimization Graphical Example Script.")
    print("Minimizing the Rosenbrock function.")
    print("Click inside the generated plot to select a new initial guess for")
    print("  the minimization.")
    print("Close the generated plot to end the example.")

    nag_input("Press ENTER to start the plot:")

    rb = RosenbrockPlot()
    rb.genplot()
    pyplot.show()

if __name__ == '__main__':
    main()

実行コマンド例

python minimize_rosenbrock.py


Results matter. Trust NAG.

Privacy Policy | Trademarks