
import numpy
from scikits.optimization import *
from matplotlib import pyplot

from display_with_line import add_line, create_figure
from function import Function

class Recorder(object):
  def __init__(self):
    self.values = []
    self.parameters = []
  def __call__(self, **state):
    self.values.append(state["new_value"])
    self.parameters.append(state['new_parameters'])
    pyplot.plot(self.values)
    pyplot.savefig('%04i.png' % state['iteration'])
    if len(self.parameters) > 1:
      fig = create_figure()
      add_line(fig, self.parameters)
      pyplot.savefig('3d_%04i.png' % state['iteration'])
    pyplot.close('all')

fun = Function()

mystep = step.GradientStep()
mylinesearch = line_search.GoldenSectionSearch(min_alpha_step = 0.0001, alpha_step = .5)
mycriterion = criterion.criterion(ftol = 0.0000001, iterations_max = 10)
myrecorder = Recorder()
myoptimizer = optimizer.StandardOptimizer(function = fun,
                                          step = mystep,
                                          line_search = mylinesearch,
                                          criterion = mycriterion,
                                          record = myrecorder,
                                          x0 = numpy.array((.8, 1.)))

print myoptimizer.optimize()

print myoptimizer.state
