def main(): solver = DifferentialEvolutionSolver(ND, NP) solver.SetRandomInitialPoints(min=[-100.0] * ND, max=[100.0] * ND) solver.SetEvaluationLimits(generations=MAX_GENERATIONS) solver.SetGenerationMonitor(VerboseMonitor(30)) solver.enable_signal_handler() strategy = Best1Exp #strategy = Best1Bin solver.Solve(ChebyshevCost, termination=VTR(0.01), strategy=strategy, \ CrossProbability=1.0, ScalingFactor=0.9, \ sigint_callback=plot_solution) solution = solver.Solution() return solution
def test_sumt2(): def costfunc(x): return (x[0] - 1.)**2 + (x[1]-2.)**2 + (x[2]-3.)**4 x0 = [0., 0., 0.] ndim = 3 constraints_string = """ x2 > 5. 4.*x1-5.*x3 < -1. (x1-10.)**2 + (x2+1.)**2 < 50. """ # print("constraints equations:%s" % (constraints_string.rstrip(),)) from mystic.solvers import DifferentialEvolutionSolver from mystic.solvers import NelderMeadSimplexSolver from mystic.termination import VTR #solver = DifferentialEvolutionSolver(ndim, npop) solver = NelderMeadSimplexSolver(ndim) solver.SetInitialPoints(x0) term = VTR() #FIXME: sumt, issolution no longer take constraints strings end_solver = sumt(constraints_string, ndim, costfunc, solver,\ term, disp=True) soln = end_solver.Solution() assert issolution(constraints_string, soln)
def test_NelderMeadSimplexSolver_VTR(self): from mystic.solvers import NelderMeadSimplexSolver from mystic.termination import VTR self.solver = NelderMeadSimplexSolver(self.ND) self.term = VTR() self._run_solver()
def test_DifferentialEvolutionSolver2_VTR(self): from mystic.solvers import DifferentialEvolutionSolver2 from mystic.termination import VTR self.solver = DifferentialEvolutionSolver2(self.ND, self.NP) self.term = VTR() self._run_solver()
freeze_support() # help Windows use multiprocessing def print_solution(func): print func return psow = VerboseMonitor(10) ssow = VerboseMonitor(10) random_seed(seed) print "first sequential..." solver = DifferentialEvolutionSolver2(ND, NP) #XXX: sequential solver.SetRandomInitialPoints(min=[-100.0] * ND, max=[100.0] * ND) solver.SetEvaluationLimits(generations=MAX_GENERATIONS) solver.SetGenerationMonitor(ssow) solver.Solve(myCost, VTR(TOL), strategy=Best1Exp, \ CrossProbability=CROSS, ScalingFactor=SCALE, disp=1) print "" print_solution(solver.bestSolution) random_seed(seed) print "\n and now parallel..." solver2 = DifferentialEvolutionSolver2(ND, NP) #XXX: parallel solver2.SetMapper(Pool(NNODES).map) solver2.SetRandomInitialPoints(min=[-100.0] * ND, max=[100.0] * ND) solver2.SetEvaluationLimits(generations=MAX_GENERATIONS) solver2.SetGenerationMonitor(psow) solver2.Solve(myCost, VTR(TOL), strategy=Best1Exp, \ CrossProbability=CROSS, ScalingFactor=SCALE, disp=1) print "" print_solution(solver2.bestSolution)
x0 = [(-100, 100)] * ndim random_seed(123) # configure monitors stepmon = VerboseMonitor(50) evalmon = Monitor() # use DE to solve 8th-order Chebyshev coefficients npop = 10 * ndim solver = DifferentialEvolutionSolver2(ndim, npop) solver.SetRandomInitialPoints(min=[-100] * ndim, max=[100] * ndim) solver.SetEvaluationLimits(generations=999) solver.SetEvaluationMonitor(evalmon) solver.SetGenerationMonitor(stepmon) solver.enable_signal_handler() solver.Solve(chebyshev8cost, termination=VTR(0.01), strategy=Best1Exp, \ CrossProbability=1.0, ScalingFactor=0.9) 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)) # plot convergence of coefficients per iteration plot_frame('iterations') plot_params(stepmon) getch() # plot convergence of coefficients per function call
def test_griewangk(): """Test Griewangk's function, which has many local minima. Testing Griewangk: Expected: x=[0.]*10 and f=0 Using DifferentialEvolutionSolver: Solution: [ 8.87516194e-09 7.26058147e-09 1.02076001e-08 1.54219038e-08 -1.54328461e-08 2.34589663e-08 2.02809360e-08 -1.36385836e-08 1.38670373e-08 1.59668900e-08] f value: 0.0 Iterations: 4120 Function evaluations: 205669 Time elapsed: 34.4936850071 seconds Using DifferentialEvolutionSolver2: Solution: [ -2.02709316e-09 3.22017968e-09 1.55275472e-08 5.26739541e-09 -2.18490470e-08 3.73725584e-09 -1.02315312e-09 1.24680355e-08 -9.47898116e-09 2.22243557e-08] f value: 0.0 Iterations: 4011 Function evaluations: 200215 Time elapsed: 32.8412370682 seconds """ print "Testing Griewangk:" print "Expected: x=[0.]*10 and f=0" from mystic.models import griewangk as costfunc ndim = 10 lb = [-400.]*ndim ub = [400.]*ndim maxiter = 10000 seed = 123 # Re-seed for each solver to have them all start at same x0 # DifferentialEvolutionSolver print "\nUsing DifferentialEvolutionSolver:" npop = 50 random_seed(seed) from mystic.solvers import DifferentialEvolutionSolver from mystic.termination import ChangeOverGeneration as COG from mystic.termination import CandidateRelativeTolerance as CRT from mystic.termination import VTR from mystic.strategy import Rand1Bin, Best1Bin, Rand1Exp esow = Monitor() ssow = Monitor() solver = DifferentialEvolutionSolver(ndim, npop) solver.SetRandomInitialPoints(lb, ub) solver.SetStrictRanges(lb, ub) solver.SetEvaluationLimits(generations=maxiter) solver.SetEvaluationMonitor(esow) solver.SetGenerationMonitor(ssow) solver.enable_signal_handler() #term = COG(1e-10) #term = CRT() term = VTR(0.) time1 = time.time() # Is this an ok way of timing? solver.Solve(costfunc, term, strategy=Rand1Exp, \ CrossProbability=0.3, ScalingFactor=1.0) sol = solver.Solution() time_elapsed = time.time() - time1 fx = solver.bestEnergy print "Solution: ", sol print "f value: ", fx print "Iterations: ", solver.generations print "Function evaluations: ", len(esow.x) print "Time elapsed: ", time_elapsed, " seconds" assert almostEqual(fx, 0.0, tol=3e-3) # DifferentialEvolutionSolver2 print "\nUsing DifferentialEvolutionSolver2:" npop = 50 random_seed(seed) from mystic.solvers import DifferentialEvolutionSolver2 from mystic.termination import ChangeOverGeneration as COG from mystic.termination import CandidateRelativeTolerance as CRT from mystic.termination import VTR from mystic.strategy import Rand1Bin, Best1Bin, Rand1Exp esow = Monitor() ssow = Monitor() solver = DifferentialEvolutionSolver2(ndim, npop) solver.SetRandomInitialPoints(lb, ub) solver.SetStrictRanges(lb, ub) solver.SetEvaluationLimits(generations=maxiter) solver.SetEvaluationMonitor(esow) solver.SetGenerationMonitor(ssow) #term = COG(1e-10) #term = CRT() term = VTR(0.) time1 = time.time() # Is this an ok way of timing? solver.Solve(costfunc, term, strategy=Rand1Exp, \ CrossProbability=0.3, ScalingFactor=1.0) sol = solver.Solution() time_elapsed = time.time() - time1 fx = solver.bestEnergy print "Solution: ", sol print "f value: ", fx print "Iterations: ", solver.generations print "Function evaluations: ", len(esow.x) print "Time elapsed: ", time_elapsed, " seconds" assert almostEqual(fx, 0.0, tol=3e-3)
from mystic.solvers import DifferentialEvolutionSolver from mystic.solvers import NelderMeadSimplexSolver, PowellDirectionalSolver from mystic.termination import VTR, ChangeOverGeneration, When, Or from mystic.models import rosen from mystic.solvers import LoadSolver import os import sys is_pypy = hasattr(sys, 'pypy_version_info') if is_pypy: print('Skipping: test_solver_sanity.py') exit() solver = PowellDirectionalSolver(3) solver.SetRandomInitialPoints([0., 0., 0.], [10., 10., 10.]) term = VTR() solver.Solve(rosen, term) x = solver.bestSolution y = solver.bestEnergy assert solver._state == None assert LoadSolver(solver._state) == None solver = PowellDirectionalSolver(3) solver.SetRandomInitialPoints([0., 0., 0.], [10., 10., 10.]) term = VTR() tmpfile = 'mysolver.pkl' solver.SetSaveFrequency(10, tmpfile) solver.Solve(rosen, term) x = solver.bestSolution y = solver.bestEnergy _solver = LoadSolver(tmpfile)
# xinit = [0.8,1.2,1.7] #... better when using "bad" range min = [-0.999, -0.999, 0.999] #XXX: behaves badly when large range max = [200.001, 100.001, inf] #... for >=1 x0 out of bounds; (up xtol) # min = [-0.999, -0.999, -0.999] # max = [200.001, 100.001, inf] # min = [-0.999, -0.999, 0.999] #XXX: tight range and non-randomness # max = [2.001, 1.001, 1.001] #...: is _bad_ for DE solvers #print(diffev(rosen,xinit,NP,retall=0,full_output=0)) solver = DifferentialEvolutionSolver(len(xinit), NP) solver.SetInitialPoints(xinit) solver.SetStrictRanges(min, max) solver.SetEvaluationLimits(generations=MAX_GENERATIONS) solver.SetEvaluationMonitor(esow) solver.SetGenerationMonitor(ssow) solver.Solve(rosen, VTR(0.0001), \ CrossProbability=0.5, ScalingFactor=0.6, disp=1) sol = solver.bestSolution print(sol) #print("Current function value: %s" % solver.bestEnergy) #print("Iterations: %s" % solver.generations) #print("Function evaluations: %s" % solver.evaluations) times.append(time.time() - start) algor.append('Differential Evolution\t') for k, t in zip(algor, times): print("%s\t -- took %s" % (k, t)) #print(len(esow.x)) #print(len(ssow.x))
nd = 2 npop = 20 tol = 0.05 lb = [-3.] * nd ub = [3.] * nd from mystic.tools import random_seed #random_seed(123) from mystic.differential_evolution import DifferentialEvolutionSolver from mystic.termination import VTR from mystic.termination import ChangeOverGeneration as COG solver = DifferentialEvolutionSolver(nd, npop) solver.SetRandomInitialPoints(lb, ub) solver.SetStrictRanges(lb, ub) term = VTR(tol) #term = COG() solver.Solve(peaks, term, disp=True) sol = solver.Solution() print('solution = %s' % sol) print('expected = [0.23, -1.63]') try: from scipy.stats import uniform except ImportError: exit() from mystic.math import Distribution print('-' * 60) print('using a uniform distribution...') solver = DifferentialEvolutionSolver(nd, npop)
# License: 3-clause BSD. The full license text is available at: # - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/mystic/LICENSE """ Testing the 'Peaks" Function. (tests VTR when minimum has negative value) """ from math import * from mystic.models import peaks nd = 2 npop = 20 lb = [-3.]*nd ub = [3.]*nd from mystic.tools import random_seed #random_seed(123) from mystic.differential_evolution import DifferentialEvolutionSolver from mystic.termination import VTR from mystic.termination import ChangeOverGeneration as COG solver = DifferentialEvolutionSolver(nd, npop) solver.SetRandomInitialPoints(lb, ub) solver.SetStrictRanges(lb, ub) term = VTR() #term = COG() solver.Solve(peaks, term, disp=True) sol = solver.Solution() print 'solution = ', sol print 'expected = [0.23, -1.63]'
def impose_expectation(param, f, npts, bounds=None, weights=None, **kwds): """impose a given expextation value (m +/- D) on a given function f. Optimization on f over the given bounds seeks a mean 'm' with deviation 'D'. (this function is not 'mean-, range-, or variance-preserving') Inputs: param -- a tuple of target parameters: param = (mean, deviation) f -- a function that takes a list and returns a number npts -- a tuple of dimensions of the target product measure bounds -- a tuple of sample bounds: bounds = (lower_bounds, upper_bounds) weights -- a list of sample weights Additional Inputs: constraints -- a function that takes a nested list of N x 1D discrete measure positions and weights x' = constraints(x, w) npop -- size of the trial solution population maxiter -- number - the maximum number of iterations to perform maxfun -- number - the maximum number of function evaluations Outputs: samples -- a list of sample positions For example: >>> # provide the dimensions and bounds >>> nx = 3; ny = 2; nz = 1 >>> x_lb = [10.0]; y_lb = [0.0]; z_lb = [10.0] >>> x_ub = [50.0]; y_ub = [9.0]; z_ub = [90.0] >>> >>> # prepare the bounds >>> lb = (nx * x_lb) + (ny * y_lb) + (nz * z_lb) >>> ub = (nx * x_ub) + (ny * y_ub) + (nz * z_ub) >>> >>> # generate a list of samples with mean +/- dev imposed >>> mean = 2.0; dev = 0.01 >>> samples = impose_expectation((mean,dev), f, (nx,ny,nz), (lb,ub)) >>> >>> # test the results by calculating the expectation value for the samples >>> expectation(f, samples) >>> 2.00001001012246015 """ # param[0] is the target mean # param[1] is the acceptable deviation from the target mean # FIXME: the following is a HACK to recover from lost 'weights' information # we 'mimic' discrete measures using the product measure weights # plug in the 'constraints' function: samples' = constrain(samples, weights) constrain = None # default is no constraints if 'constraints' in kwds: constrain = kwds['constraints'] if not constrain: # if None (default), there are no constraints constraints = lambda x: x else: #XXX: better to use a standard "xk' = constrain(xk)" interface ? def constraints(rv): coords = _pack(_nested(rv, npts)) coords = zip(*coords) # 'mimic' a nested list coords = constrain(coords, [weights for i in range(len(coords))]) coords = zip(*coords) # revert back to a packed list return _flat(_unpack(coords, npts)) # construct cost function to reduce deviation from expectation value def cost(rv): """compute cost from a 1-d array of model parameters, where: cost = | E[model] - m |**2 """ # from mystic.math.measures import _pack, _nested, expectation samples = _pack(_nested(rv, npts)) Ex = expectation(f, samples, weights) return (Ex - param[0])**2 # if bounds are not set, use the default optimizer bounds if not bounds: lower_bounds = [] upper_bounds = [] for n in npts: lower_bounds += [None] * n upper_bounds += [None] * n else: lower_bounds, upper_bounds = bounds # construct and configure optimizer debug = kwds['debug'] if 'debug' in kwds else False npop = kwds.pop('npop', 200) maxiter = kwds.pop('maxiter', 1000) maxfun = kwds.pop('maxfun', 1e+6) crossover = 0.9 percent_change = 0.9 def optimize(cost, (lb, ub), tolerance, _constraints): from mystic.solvers import DifferentialEvolutionSolver2 from mystic.termination import VTR from mystic.strategy import Best1Exp from mystic.monitors import VerboseMonitor, Monitor from mystic.tools import random_seed if debug: random_seed(123) evalmon = Monitor() stepmon = Monitor() if debug: stepmon = VerboseMonitor(10) ndim = len(lb) solver = DifferentialEvolutionSolver2(ndim, npop) solver.SetRandomInitialPoints(min=lb, max=ub) solver.SetStrictRanges(min=lb, max=ub) solver.SetEvaluationLimits(maxiter, maxfun) solver.SetEvaluationMonitor(evalmon) solver.SetGenerationMonitor(stepmon) solver.Solve(cost,termination=VTR(tolerance),strategy=Best1Exp, \ CrossProbability=crossover,ScalingFactor=percent_change, \ constraints = _constraints) solved = solver.Solution() diameter_squared = solver.bestEnergy func_evals = len(evalmon) return solved, diameter_squared, func_evals
def solve(measurements, method): """Find reasonable marker positions based on a set of measurements.""" print(method) marker_measurements = measurements if np.size(measurements) == 21: marker_measurements = measurements[(21 - 15) :] # m0 has known positions (0, 0, 0) # m1 has unknown x-position # All others have unknown xy-positions num_params = 0 + 1 + 2 + 2 + 2 + 2 bound = 400.0 lower_bound = [ 0.0, 0.0, 0.0, 0.0, 0.0, -bound, 0.0, -bound, 0.0, ] upper_bound = [ bound, bound, bound, bound, bound, bound, bound, bound, bound, ] def costx_no_nozzle(posvec): """Identical to cost_no_nozzle, except the shape of inputs""" positions = posvec2matrix_no_nozzle(posvec) return cost_no_nozzle(positions, marker_measurements) guess_0 = [0.0] * num_params intermediate_cost = 0.0 intermediate_solution = [] if method == "SLSQP": sol = scipy.optimize.minimize( costx_no_nozzle, guess_0, method="SLSQP", bounds=list(zip(lower_bound, upper_bound)), tol=1e-20, options={"disp": True, "ftol": 1e-40, "eps": 1e-10, "maxiter": 500}, ) intermediate_cost = sol.fun intermediate_solution = sol.x elif method == "L-BFGS-B": sol = scipy.optimize.minimize( costx_no_nozzle, guess_0, method="L-BFGS-B", bounds=list(zip(lower_bound, upper_bound)), options={"disp": True, "ftol": 1e-12, "gtol": 1e-12, "maxiter": 50000, "maxfun": 1000000}, ) intermediate_cost = sol.fun intermediate_solution = sol.x elif method == "PowellDirectionalSolver": from mystic.solvers import PowellDirectionalSolver from mystic.termination import Or, CollapseAt, CollapseAs from mystic.termination import ChangeOverGeneration as COG from mystic.monitors import VerboseMonitor from mystic.termination import VTR, And, Or solver = PowellDirectionalSolver(num_params) solver.SetRandomInitialPoints(lower_bound, upper_bound) solver.SetEvaluationLimits(evaluations=3200000, generations=100000) solver.SetTermination(Or(VTR(1e-25), COG(1e-10, 20))) solver.SetStrictRanges(lower_bound, upper_bound) solver.SetGenerationMonitor(VerboseMonitor(5)) solver.Solve(costx_no_nozzle) intermediate_cost = solver.bestEnergy intermediate_solution = solver.bestSolution elif method == "differentialEvolutionSolver": from mystic.solvers import DifferentialEvolutionSolver2 from mystic.monitors import VerboseMonitor from mystic.termination import VTR, ChangeOverGeneration, And, Or from mystic.strategy import Best1Exp, Best1Bin stop = Or(VTR(1e-18), ChangeOverGeneration(1e-9, 500)) npop = 3 stepmon = VerboseMonitor(100) solver = DifferentialEvolutionSolver2(num_params, npop) solver.SetEvaluationLimits(evaluations=3200000, generations=100000) solver.SetRandomInitialPoints(lower_bound, upper_bound) solver.SetStrictRanges(lower_bound, upper_bound) solver.SetGenerationMonitor(stepmon) solver.Solve( costx_no_nozzle, termination=stop, strategy=Best1Bin, ) intermediate_cost = solver.bestEnergy intermediate_solution = solver.bestSolution else: print("Method %s is not supported!" % method) sys.exit(1) print("Best intermediate cost: ", intermediate_cost) print("Best intermediate positions: \n%s" % posvec2matrix_no_nozzle(intermediate_solution)) if np.size(measurements) == 15: print("Got only 15 samples, so will not try to find nozzle position\n") return nozzle_measurements = measurements[: (21 - 15)] # Look for nozzle's xyz-offset relative to marker 0 num_params = 3 lower_bound = [ 0.0, 0.0, -bound, ] upper_bound = [bound, bound, 0.0] def costx_nozzle(posvec): """Identical to cost_nozzle, except the shape of inputs""" positions = posvec2matrix_nozzle(posvec, intermediate_solution) return cost_nozzle(positions, measurements) guess_0 = [0.0, 0.0, 0.0] final_cost = 0.0 final_solution = [] if method == "SLSQP": sol = scipy.optimize.minimize( costx_nozzle, guess_0, method="SLSQP", bounds=list(zip(lower_bound, upper_bound)), tol=1e-20, options={"disp": True, "ftol": 1e-40, "eps": 1e-10, "maxiter": 500}, ) final_cost = sol.fun final_solution = sol.x elif method == "L-BFGS-B": sol = scipy.optimize.minimize( costx_nozzle, guess_0, method="L-BFGS-B", bounds=list(zip(lower_bound, upper_bound)), options={"disp": True, "ftol": 1e-12, "gtol": 1e-12, "maxiter": 50000, "maxfun": 1000000}, ) final_cost = sol.fun final_solution = sol.x elif method == "PowellDirectionalSolver": from mystic.solvers import PowellDirectionalSolver from mystic.termination import Or, CollapseAt, CollapseAs from mystic.termination import ChangeOverGeneration as COG from mystic.monitors import VerboseMonitor from mystic.termination import VTR, And, Or solver = PowellDirectionalSolver(num_params) solver.SetRandomInitialPoints(lower_bound, upper_bound) solver.SetEvaluationLimits(evaluations=3200000, generations=100000) solver.SetTermination(Or(VTR(1e-25), COG(1e-10, 20))) solver.SetStrictRanges(lower_bound, upper_bound) solver.SetGenerationMonitor(VerboseMonitor(5)) solver.Solve(costx_nozzle) final_cost = solver.bestEnergy final_solution = solver.bestSolution elif method == "differentialEvolutionSolver": from mystic.solvers import DifferentialEvolutionSolver2 from mystic.monitors import VerboseMonitor from mystic.termination import VTR, ChangeOverGeneration, And, Or from mystic.strategy import Best1Exp, Best1Bin stop = Or(VTR(1e-18), ChangeOverGeneration(1e-9, 500)) npop = 3 stepmon = VerboseMonitor(100) solver = DifferentialEvolutionSolver2(num_params, npop) solver.SetEvaluationLimits(evaluations=3200000, generations=100000) solver.SetRandomInitialPoints(lower_bound, upper_bound) solver.SetStrictRanges(lower_bound, upper_bound) solver.SetGenerationMonitor(stepmon) solver.Solve( costx_nozzle, termination=stop, strategy=Best1Bin, ) final_cost = solver.bestEnergy final_solution = solver.bestSolution print("Best final cost: ", final_cost) print("Best final positions:") final = posvec2matrix_nozzle(final_solution, intermediate_solution)[1:] for num in range(0, 6): print( "{0: 8.3f} {1: 8.3f} {2: 8.3f} <!-- Marker {3} -->".format(final[num][0], final[num][1], final[num][2], num) )
def test_PowellDirectionalSolver_VTR(self): from mystic.solvers import PowellDirectionalSolver from mystic.termination import VTR self.solver = PowellDirectionalSolver(self.ND) self.term = VTR() self._run_solver()
from mystic.termination import And, Or, When if __name__ == '__main__': info = 'self' #False #True _all = And #__and _any = Or #__or _one = When #__when from mystic.solvers import DifferentialEvolutionSolver s = DifferentialEvolutionSolver(4, 4) from mystic.termination import VTR from mystic.termination import ChangeOverGeneration from mystic.termination import NormalizedChangeOverGeneration v = VTR() c = ChangeOverGeneration() n = NormalizedChangeOverGeneration() print "define conditions..." _v = _one(v) _c = _one(c) _n = _one(n) vAc = _all(v, c) vAn = _all(v, n) vOc = _any(v, c) vOn = _any(v, n) vAc_On = _any(vAc, _n) vAc_Oc = _any(vAc, _c) vAn_On = _any(vAn, _n) cAv = _all(c, v)
freeze_support() # help Windows use multiprocessing def print_solution(func): print(poly1d(func)) return psow = VerboseMonitor(10) ssow = VerboseMonitor(10) random_seed(seed) print("first sequential...") solver = DifferentialEvolutionSolver2(ND, NP) solver.SetRandomInitialPoints(min=[-100.0] * ND, max=[100.0] * ND) solver.SetEvaluationLimits(generations=MAX_GENERATIONS) solver.SetGenerationMonitor(ssow) solver.Solve(ChebyshevCost, VTR(0.01), strategy=Best1Exp, \ CrossProbability=1.0, ScalingFactor=0.9, disp=1) print("") print_solution(solver.bestSolution) random_seed(seed) print("\n and now parallel...") solver2 = DifferentialEvolutionSolver2(ND, NP) solver2.SetMapper(Pool(NNODES).map) # parallel solver2.SetRandomInitialPoints(min=[-100.0] * ND, max=[100.0] * ND) solver2.SetEvaluationLimits(generations=MAX_GENERATIONS) solver2.SetGenerationMonitor(psow) solver2.Solve(ChebyshevCost, VTR(0.01), strategy=Best1Exp, \ CrossProbability=1.0, ScalingFactor=0.9, disp=1) print("") print_solution(solver2.bestSolution)
def test_me(info='self'): from mystic.solvers import DifferentialEvolutionSolver s = DifferentialEvolutionSolver(4, 4) from mystic.termination import VTR from mystic.termination import ChangeOverGeneration from mystic.termination import NormalizedChangeOverGeneration v = VTR() c = ChangeOverGeneration() n = NormalizedChangeOverGeneration() if disp: print("define conditions...") _v = When(v) _c = When(c) _n = When(n) v_and_c = And(v, c) v_and_n = And(v, n) v_or_c = Or(v, c) v_or_n = Or(v, n) v_and_c__or_n = Or(v_and_c, _n) v_and_c__or_c = Or(v_and_c, _c) v_and_n__or_n = Or(v_and_n, _n) c_and_v = And(c, v) c_or_v = Or(c, v) c_or__c_and_v = Or(_c, c_and_v) assert len(_v) == len(_c) == len(_n) == 1 assert list(_v).index(v) == list(_c).index(c) == list(_n).index(n) == 0 assert list(_v).count(v) == list(_c).count(c) == list(_n).count(n) == 1 assert v in _v and c in _c and n in _n assert v in v_and_c and c in v_and_c assert v in v_and_n and n in v_and_n assert v in v_or_c and c in v_or_c assert v in v_or_n and n in v_or_n assert len(v_and_c) == len(v_and_n) == len(v_or_c) == len(v_or_n) == 2 assert len(v_and_c__or_n) == len(v_and_c__or_c) == len(v_and_n__or_n) == 2 assert v not in v_and_c__or_n and c not in v_and_c__or_n and n not in v_and_c__or_n assert v_and_c in v_and_c__or_n and _n in v_and_c__or_n assert v_and_c in v_and_c__or_c and _c in v_and_c__or_c assert v_and_n in v_and_n__or_n and _n in v_and_n__or_n assert c in c_and_v and v in c_and_v assert c in c_or_v and v in c_or_v assert list(c_and_v).index(c) == list(v_and_c).index(v) assert list(c_and_v).index(v) == list(v_and_c).index(c) assert list(c_or_v).index(c) == list(v_or_c).index(v) assert list(c_or_v).index(v) == list(v_or_c).index(c) assert c_and_v in c_or__c_and_v and _c in c_or__c_and_v if disp: print("_v:%s" % _v) print("_c:%s" % _c) print("_n:%s" % _n) print("v_and_c:%s" % v_and_c) print("v_and_n:%s" % v_and_n) print("v_or_c:%s" % v_or_c) print("v_or_n:%s" % v_or_n) print("v_and_c__or_n:%s" % v_and_c__or_n) print("v_and_c__or_c:%s" % v_and_c__or_c) print("v_and_n__or_n:%s" % v_and_n__or_n) print("c_and_v:%s" % c_and_v) print("c_or_v:%s" % c_or_v) print("c_or__c_and_v:%s" % c_or__c_and_v) if disp: print("initial conditions...") _v_and_c = v_and_c(s, info) _v_and_n = v_and_n(s, info) _v_or_c = v_or_c(s, info) _v_or_n = v_or_n(s, info) assert not _v_and_c assert not _v_and_n assert not _v_or_c assert not _v_or_n if disp: print("v_and_c:%s" % _v_and_c) print("v_and_n:%s" % _v_and_n) print("v_or_c:%s" % _v_or_c) print("v_or_n:%s" % _v_or_n) if disp: print("after convergence toward zero...") s.energy_history = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # _v and _n are True, _c is False _v_and_c = v_and_c(s, info) _v_and_n = v_and_n(s, info) _v_or_c = v_or_c(s, info) _v_or_n = v_or_n(s, info) assert not _v_and_c assert _v_and_n assert _v_or_c assert _v_or_n if info == 'self': assert v in _v_and_n and n in _v_and_n assert v in _v_or_c and c not in _v_or_c assert v in _v_or_n and n in _v_or_n if disp: print("v_and_c:%s" % _v_and_c) print("v_and_n:%s" % _v_and_n) print("v_or_c:%s" % _v_or_c) print("v_or_n:%s" % _v_or_n) if disp: print("nested compound termination...") # _v and _n are True, _c is False _v_and_c__or_n = v_and_c__or_n(s, info) _v_and_c__or_c = v_and_c__or_c(s, info) _v_and_n__or_n = v_and_n__or_n(s, info) assert _v_and_c__or_n assert not _v_and_c__or_c assert _v_and_n__or_n if info == 'self': assert _n in _v_and_c__or_n and v_and_c not in _v_and_c__or_n assert v not in _v_and_c__or_n and c not in _v_and_c__or_n assert v_and_n in _v_and_n__or_n and _n in _v_and_n__or_n assert v not in _v_and_n__or_n and n not in _v_and_n__or_n if disp: print("v_and_c__or_n:%s" % _v_and_c__or_n) print("v_and_c__or_c:%s" % _v_and_c__or_c) print("v_and_n__or_n:%s" % _v_and_n__or_n) if disp: print("individual conditions...") __v = _v(s, info) __c = _c(s, info) __n = _n(s, info) assert __v and __n assert not __c if info == 'self': assert v in __v and n in __n if disp: print("v:%s" % __v) print("c:%s" % __c) print("n:%s" % __n) if disp: print("conditions with false first...") _c_and_v = c_and_v(s, info) _c_or_v = c_or_v(s, info) _c_or__c_and_v = c_or__c_and_v(s, info) assert not _c_and_v assert _c_or_v assert not _c_or__c_and_v if info == 'self': assert v in _c_or_v and c not in _c_or_v if disp: print("c_and_v:%s" % _c_and_v) print("c_or_v:%s" % _c_or_v) print("c_or__c_and_v:%s" % _c_or__c_and_v)