Ejemplo n.º 1
0
class LevmarOptimization(OptimizationStep):
    "Levenberg-Marquardt optimization step."
    def __init__(self, no_vars, mins, maxes, comm, stop_flag, p0=None,
            max_iter=5, central=False):
        super(LevmarOptimization, self).__init__(no_vars, mins, maxes, comm,
            stop_flag)
        self.timer = Timer()
        # If starting vector is not specified, start with min values.
        self.p0 = np.array(p0 or mins)
        self.max_iter = max_iter
        self.central = central
        self.prepare()

    def prepare(self):
        # Starting residuals (or observed values).
        self.y = np.array([0] * self.no_vars)
        self.bounds = zip(self.mins, self.maxes)

    def run(self):
        printf("Starting LM: %d iterations" % self.max_iter)
        objective = LevmarObjective(self.comm)
        self.timer.start()
        output = levmar(objective, p0=self.p0, y=self.y, bounds=self.bounds,
            maxit=self.max_iter, cdif=self.central, eps1=1e-15, eps2=1e-15,
            eps3=1e-20, full_output=True, breakf=self.__breakf)
        self.__post_run(output)
        return list(output.p)

    def __post_run(self, lm_output):
        run_time = self.timer.stop()
        info = lm_output.info
        printf("Iteration %d of %d, ||error|| %g" % (info[2], self.max_iter,
            info[1][0]))
        print "LM finished in %g s, with reason: %s" % (run_time, info[3])

    def __breakf(self, i, maxit, p, error):
        pstr = "Iteration %d of %d, ||error|| %g" % (i, maxit, error)
        self.timer.lap()
        if i > 0:
            iter_left = maxit - i
            mean_time = self.timer.time_so_far / i
            pstr += "\t(est. time to end=%d s.)" % (iter_left * mean_time)
        printf(pstr)
        if check_stop_flag(self.stop_flag):
            return 1