Example #1
0
 def test_ls_steepest(self):
     x = np.ones(self.model.n)
     g = self.model.grad(x)
     c1model = C1LineModel(self.model, x, -g)
     ls = QuadraticCubicLineSearch(c1model)
     with pytest.raises(StopIteration):
         ls.next()
     np.allclose(ls.iterate, np.zeros(self.model.n))
Example #2
0
 def test_ls(self):
     x = np.array([-4.])
     g = np.array([1])
     c1model = C1LineModel(self.model, x, g)
     ls = QuadraticCubicLineSearch(c1model, step=8)
     ls.next()
     ls.next()
     with pytest.raises(StopIteration):
         ls.next()
     np.allclose(ls.iterate, np.array([1.69059892324]))
Example #3
0
 def test_ascent(self):
     x = np.ones(self.model.n)
     g = self.model.grad(x)
     c1model = C1LineModel(self.model, x, g)
     with pytest.raises(ValueError):
         QuadraticCubicLineSearch(c1model)
Example #4
0
def run_demo(model, x, p, step0):
    """Create arrays necessary to display steps of linesearch."""
    c1model = C1LineModel(model, x, p)
    ls = QuadraticCubicLineSearch(c1model, step=step0)

    t = np.linspace(-0.2, 1.2 * ls._step0, 1000)

    y = np.empty(t.size)
    k = 0
    for x in t:
        y[k] = c1model.obj(x)
        k += 1
    plt.figure()
    plt.ion()
    plt.plot(t, y)
    t = np.linspace(0, ls._step0, 1000)

    x_p = []
    y_p = []
    x_p.append(0.)
    y_p.append(ls._value)
    plt.annotate("$t=0$",
                 xy=(0, ls._value),
                 xytext=(-5, 5),
                 textcoords='offset points',
                 ha='right',
                 va='bottom')

    x_p.append(ls.step)
    y_p.append(ls.trial_value)
    plt.scatter(x_p, y_p)

    plt.annotate("$t_0=" + str(ls.step) + "$",
                 xy=(ls.step, ls.trial_value),
                 xytext=(-5, 5),
                 textcoords='offset points',
                 ha='right',
                 va='bottom')

    try:
        for k, step in enumerate(ls):
            print k, step
            if k == 0:
                phi = quadratic_interpolant(ls, t)
                curve, = plt.plot(t, phi)
                last_step = ls._last_step
                s = ls.step
            else:
                phi3 = cubic_interpolant(ls, t, last_step, s)
                curve, = plt.plot(t, phi3)
                last_step = ls._last_step
                s = ls.step
            x_p.append(ls.step)
            y_p.append(ls.trial_value)
            plt.annotate("$t_" + str(k + 1) + "=%3.1f" % ls.step + "$",
                         xy=(ls.step, ls.trial_value),
                         xytext=(-5, 5),
                         textcoords='offset points',
                         ha='right',
                         va='bottom')
            plt.scatter(x_p, y_p)
            plt.pause(3)
            curve.remove()
    except LineSearchFailure:
        pass