def runme(): # instantiate the solver _solver = NelderMeadSimplexSolver(3) lb, ub = [0., 0., 0.], [10., 10., 10.] _solver.SetRandomInitialPoints(lb, ub) _solver.SetEvaluationLimits(1000) # add a monitor stream stepmon = VerboseMonitor(1) _solver.SetGenerationMonitor(stepmon) # configure the bounds _solver.SetStrictRanges(lb, ub) # configure stop conditions term = Or(VTR(), ChangeOverGeneration()) _solver.SetTermination(term) # add a periodic dump to an archive tmpfile = 'mysolver.pkl' _solver.SetSaveFrequency(10, tmpfile) # run the optimizer _solver.Solve(rosen) # get results x = _solver.bestSolution y = _solver.bestEnergy # load the saved solver solver = LoadSolver(tmpfile) #os.remove(tmpfile) # obligatory check that state is the same assert all(x == solver.bestSolution) assert y == solver.bestEnergy # modify the termination condition term = VTR(0.0001) solver.SetTermination(term) # run the optimizer solver.Solve(rosen) os.remove(tmpfile) # check the solver serializes _s = dill.dumps(solver) return dill.loads(_s)
ndim = len(lb) maxiter = 10 maxfun = 1e+6 def cost(x): ax, bx, c = x return (ax)**2 - bx + c monitor = Monitor() solver = NelderMeadSimplexSolver(ndim) solver.SetRandomInitialPoints(min=lb, max=ub) solver.SetStrictRanges(min=lb, max=ub) solver.SetEvaluationLimits(maxiter, maxfun) solver.SetGenerationMonitor(monitor) solver.Solve(cost) solved = solver.bestSolution monitor.info("solved: %s" % solved) lmon = len(monitor) assert solver.bestEnergy == monitor.y[-1] for xs, x in zip(solved, monitor.x[-1]): assert xs == x solver.SetEvaluationLimits(maxiter * 2, maxfun) solver.SetGenerationMonitor(monitor) solver.Solve(cost) assert len(monitor) > lmon
# select parameter bounds constraints from numpy import inf min_bounds = [0, -1, -300, -1, 0, -1, -100, -inf, -inf] max_bounds = [200, 1, 0, 1, 200, 1, 0, inf, inf] # configure monitors stepmon = VerboseMonitor(100) evalmon = Monitor() # use Nelder-Mead to solve 8th-order Chebyshev coefficients solver = NelderMeadSimplexSolver(ndim) solver.SetInitialPoints(x0) solver.SetEvaluationLimits(generations=999) solver.SetEvaluationMonitor(evalmon) solver.SetGenerationMonitor(stepmon) solver.SetStrictRanges(min_bounds, max_bounds) solver.enable_signal_handler() solver.Solve(chebyshev8cost, termination=CRT(1e-4,1e-4), \ sigint_callback=plot_solution) solution = solver.bestSolution # get solved coefficients and Chi-Squared (from solver members) iterations = solver.generations cost = solver.bestEnergy print "Generation %d has best Chi-Squared: %f" % (iterations, cost) print "Solved Coefficients:\n %s\n" % poly1d(solver.bestSolution) # compare solution with actual 8th-order Chebyshev coefficients print "Actual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs)