示例#1
0
def run(n_restarts=5):
    from PyGMO import algorithm, island, population
    prob = earthToMars()
    algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
    # algo.screen_output = True
    algo2 = algorithm.mbh(algo, n_restarts, 0.005)
    algo2.screen_output = True
    pop = population(prob)

    pop.push_back((320.33563525584435, 0.0016748335274261476, 0.0013627675495311467, 0.0))
    pop.push_back((301.93091863294785, 0.0016076262089444425, 0.0015896115913838728, 0.0))
    pop.push_back((301.93091863294785, 0.0016076262089444425, 0.0015896115913838728, 0.0))
    pop.push_back((420.2372419060117, 0.010494326408284994, 0.0044382506954818565, 0.0))
    pop.push_back((411.21323621411335, 0.008748839048462907, 0.0033290148214346503, 0.0))
    pop.push_back((395.8283718212657, 0.006450877568564355, 0.002069880891910152, 0.0))
    pop.push_back((319.95400029222867, 0.0016702166037494744, 0.0013676901851197968, 0.0))
    pop.push_back((319.5113399461457, 0.00166499548529299, 0.0013736935829129556, 0.0))
    pop.push_back((320.0969905134936, 0.001671977113629641, 0.001365741362825864, 0.0))
    pop.push_back((324.8947207784664, 0.0017420256877963634, 0.0013024051696600683, 0.0))

    isl = island(algo2,pop)
    print("Running Monotonic Basin Hopping .... this will take a while.")
    isl.evolve(1)
    isl.join()
    print("Is the solution found a feasible trajectory? " +
          str(prob.feasibility_x(isl.population.champion.x)))
    return isl.population.champion.x
示例#2
0
def run(n_restarts=5):
    from PyGMO import algorithm, island, population
    prob = earthToMars()
    algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
    # algo.screen_output = True
    algo2 = algorithm.mbh(algo, n_restarts, 0.005)
    algo2.screen_output = True

    pop = population(prob)

    pop.push_back((-3.810404036178629e-05, 8.036667366434322e-05, 0, -0.00011631957922519811, -0.0003960700040113729, 0, 0.00014343900668268246, -0.00039460589468829016, 0, 0.0004133243825183847, -0.0002676479632615287, 0, -6.353773946676955e-05, -0.0004027302771161609, 0, -0.00019483461157664088, -0.0003938299142410649, 0, 0.0003740376551173652, -0.00045439735580127933, 0, 0.00026271994456226056, -4.17413726080276e-05, 0, 0.0004025294016016401, 9.22186764465555e-05, 0, 0.0004379362102351141, -8.202101747983173e-05, 0, 2.0842990495214604e-05, -1.927554372930426e-05, 0, -2.392388475139966e-05, -6.3420840462436174e-06, 0))
    pop.push_back((0.00018354551497353738, 0.0002897005581203533, 0, 9.385407683672441e-05, -0.0004375546286935724, 0, -0.00017406053466786356, -0.0004055793819144533, 0, 7.811816626063441e-05, -0.00028869842254392053, 0, 0.000280132941671916, -0.00045467528344872834, 0, 0.00031161406626870487, -0.0004418005074233615, 0, 0.00016912620000403375, -0.00045156036938030775, 0, 0.00043500734938167605, -4.4611940286304056e-05, 0, 0.00023373694896547512, 4.622353180355802e-06, 0, 0.00043504614537196785, -0.00042017445674379463, 0, 0.00016822207354911628, 0.00010574669088542543, 0, 2.1129649656070842e-05, 0.00020199652091584146, 0))
    # pop.push_back((301.93091863294785, 0.0016076262089444425, 0.0015896115913838728, 0.0))
    # pop.push_back((420.2372419060117, 0.010494326408284994, 0.0044382506954818565, 0.0))
    # pop.push_back((411.21323621411335, 0.008748839048462907, 0.0033290148214346503, 0.0))
    # pop.push_back((395.8283718212657, 0.006450877568564355, 0.002069880891910152, 0.0))
    # pop.push_back((319.95400029222867, 0.0016702166037494744, 0.0013676901851197968, 0.0))
    # pop.push_back((319.5113399461457, 0.00166499548529299, 0.0013736935829129556, 0.0))
    # pop.push_back((320.0969905134936, 0.001671977113629641, 0.001365741362825864, 0.0))
    # pop.push_back((324.8947207784664, 0.0017420256877963634, 0.0013024051696600683, 0.0))

    isl = island(algo2,pop)
    print("Running Monotonic Basin Hopping .... this will take a while.")
    isl.evolve(1)
    isl.join()
    print("Is the solution found a feasible trajectory? " +
          str(prob.feasibility_x(isl.population.champion.x)))
    return isl.population.champion.x
示例#3
0
def run_test():
	from PyGMO import problem, algorithm, island
	from numpy import mean, std
	number_of_trials = 200
	number_of_individuals = 20
	number_of_generations = 500

	prob_list = [problem.schwefel(10), problem.rastrigin(10), problem.rosenbrock(10), problem.ackley(10), problem.griewank(10)]
	algo_list = [algorithm.pso(number_of_generations), algorithm.de(number_of_generations,0.8,0.8,2),algorithm.sa_corana(number_of_generations*number_of_individuals,1,0.1), algorithm.ihs(number_of_generations*number_of_individuals), algorithm.sga(number_of_generations,0.8,0.1)]

	for prob in prob_list:
		print('\nTesting problem: ' + str(type(prob)) + ', Dimension: ' + str(prob.dimension))
		for algo in algo_list:
			print(' ' + str(algo))
			best = []
			best_x = []
			for i in range(0,number_of_trials):
				isl = island(algo,prob,number_of_individuals)
				isl.evolve(1)
				isl.join()
				best.append(isl.population.champion.f)
				best_x.append(isl.population.champion.x)
			print(' Best:\t' + str(min(best)[0]))
			print(' Mean:\t' + str(mean(best)))
			print(' Std:\t' + str(std(best)))
示例#4
0
文件: _ex3.py 项目: Noughmad/Sola
	def run_example3():
		from PyGMO import algorithm, island
		prob = mga_lt_EVMe()
		algo = algorithm.scipy_slsqp(max_iter = 500, acc =1e-5)
		#algo = algorithm.snopt(major_iter=2000, opt_tol=1e-3, feas_tol=1e-9)
		algo2 = algorithm.mbh(algo,5,0.05)
		algo2.screen_output = True
		isl = island(algo2,prob,1)
		print "Running Monotonic Basin Hopping ...."
		isl.evolve(1); isl.join()
		print "Is the solution found a feasible trajectory? " + str(prob.feasibility_x(isl.population.champion.x))
		prob.plot(isl.population.champion.x)
示例#5
0
def run_example1(n_restarts=5):
    from PyGMO import algorithm, island
    prob = earthToMars()
    algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
    algo2 = algorithm.mbh(algo, 5, 0.05)
    algo2.screen_output = True
    isl = island(algo2, prob, 1)
    print("Running Monotonic Basin Hopping .... this will take a while.")
    isl.evolve(1)
    isl.join()
    print("Is the solution found a feasible trajectory? " +
          str(prob.feasibility_x(isl.population.champion.x)))
    return isl.population.champion.x
示例#6
0
	def run_example1():
		from PyGMO import algorithm, island
		prob = mga_lt_earth_mars(nseg=15)
		prob.high_fidelity(True)
		algo = algorithm.scipy_slsqp(max_iter = 500, acc=1e-5)
		#algo = algorithm.snopt(major_iter=1000, opt_tol=1e-6, feas_tol=1e-11)
		algo2 = algorithm.mbh(algo,5,0.05)
		algo2.screen_output = True
		isl = island(algo2,prob,1)
		print "Running Monotonic Basin Hopping .... this will take a while"
		isl.evolve(1); isl.join()
		print "Is the solution found a feasible trajectory? " + str(prob.feasibility_x(isl.population.champion.x))
		prob.plot(isl.population.champion.x)
示例#7
0
def run_example1(n_restarts=5):

    prob                = mga_lt_earth_mars(nseg=15)
    prob.high_fidelity(True)
    algo                = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
    algo2               = algorithm.mbh(algo, n_restarts, 0.05)
    algo2.screen_output = True
    isl                 = island(algo2, prob, 1)
    print("Running Monotonic Basin Hopping .... this will take a while.")
    isl.evolve(1)
    isl.join()
    print("Is the solution found a feasible trajectory? " +
          str(prob.feasibility_x(isl.population.champion.x)))
    prob.plot(isl.population.champion.x)
示例#8
0
 def run_example3():
     from PyGMO import algorithm, island
     prob = mga_lt_EVMe()
     algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
     # algo = algorithm.snopt(major_iter=500, opt_tol=1e-3, feas_tol=1e-9)
     algo2 = algorithm.mbh(algo, 5, 0.05)
     algo2.screen_output = True
     isl = island(algo2, prob, 1)
     print("Running Monotonic Basin Hopping ....")
     isl.evolve(1)
     isl.join()
     print("Is the solution found a feasible trajectory? " +
           str(prob.feasibility_x(isl.population.champion.x)))
     prob.plot(isl.population.champion.x)
示例#9
0
 def run_example1():
     from PyGMO import algorithm, island
     prob = mga_lt_earth_mars(nseg=15)
     prob.high_fidelity(True)
     algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
     #algo = algorithm.snopt(major_iter=1000, opt_tol=1e-6, feas_tol=1e-11)
     algo2 = algorithm.mbh(algo, 5, 0.05)
     algo2.screen_output = True
     isl = island(algo2, prob, 1)
     print "Running Monotonic Basin Hopping .... this will take a while"
     isl.evolve(1)
     isl.join()
     print "Is the solution found a feasible trajectory? " + str(
         prob.feasibility_x(isl.population.champion.x))
     prob.plot(isl.population.champion.x)
示例#10
0
def run_example4(sim,n_restarts=5):
    from PyGMO import algorithm, island
    prob = rocketMars1()
    algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
    # algo = algorithm.ipopt(max_iter=500, constr_viol_tol=1e-5,dual_inf_tol=1e-5,compl_inf_tol=1e-5)
    # algo.screen_output = True
    algo2 = algorithm.mbh(algo, n_restarts, 0.05)
    algo2.screen_output = True
    isl = island(algo2, prob, 1)
    print("Running Monotonic Basin Hopping .... this will take a while.")
    isl.evolve(1)
    isl.join()
    print("Is the solution found a feasible trajectory? " +
          str(prob.feasibility_x(isl.population.champion.x)))
    return isl.population.champion.x
示例#11
0
def run_test(n_trials=200, pop_size = 20, n_gen = 500):

    number_of_trials = n_trials
    number_of_individuals = pop_size
    number_of_generations = n_gen
    
    prob_list = [problem.schwefel(dim = 10),
        problem.michalewicz(dim = 10),
        problem.rastrigin(dim = 10),
        problem.rosenbrock(dim = 10),
        problem.ackley(dim = 10),
        problem.griewank(dim = 10)]

    if __extensions__['gtop']:
        prob_list.append(problem.cassini_1())
        prob_list.append(problem.cassini_2())
        prob_list.append(problem.gtoc_1())
        prob_list.append(problem.rosetta())
        prob_list.append(problem.messenger_full())
        prob_list.append(problem.tandem(prob_id = 6, max_tof = 10))

    algo_list = [algorithm.pso(gen = number_of_generations),
                 algorithm.de(gen = number_of_generations,xtol=1e-30, ftol=1e-30),
                 algorithm.jde(gen = number_of_generations, variant_adptv=2,xtol=1e-30, ftol=1e-30),
                 algorithm.de_1220(gen = number_of_generations, variant_adptv=2,xtol=1e-30, ftol=1e-30),
                 algorithm.sa_corana(iter = number_of_generations*number_of_individuals,Ts = 1,Tf = 0.01),
                 algorithm.ihs(iter = number_of_generations*number_of_individuals),
                 algorithm.sga(gen = number_of_generations),
                 algorithm.cmaes(gen = number_of_generations,xtol=1e-30, ftol=1e-30),
                 algorithm.bee_colony(gen = number_of_generations/2)]
                 
    print('\nTrials: ' + str(n_trials) + ' - Population size: ' + str(pop_size) + ' - Generations: ' + str(n_gen))
    for prob in prob_list:
        print('\nTesting problem: ' + prob.get_name() + ', Dimension: ' + str(prob.dimension) )
        print('With Population Size: ' +  str(pop_size) )
        for algo in algo_list:
            print(' ' + str(algo))
            best = []
            best_x = []
            for i in range(0,number_of_trials):
                isl = island(algo,prob,number_of_individuals)
                isl.evolve(1)
                isl.join()
                best.append(isl.population.champion.f)
                best_x.append(isl.population.champion.x)
            print(' Best:\t' + str(min(best)[0]))
            print(' Mean:\t' + str(mean(best)))
            print(' Std:\t' + str(std(best)))
示例#12
0
 def run_example4():
     from PyGMO import algorithm, island, population
     N = 20
     prob = mga_lt_earth_mars_sundmann(nseg=N)
     algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5)
     # algo = algorithm.snopt(major_iter=1000, opt_tol=1e-6, feas_tol=1e-11)
     algo2 = algorithm.mbh(algo, 5, 0.05)
     algo2.screen_output = True
     isl = island(algo2, prob, 1)
     print("Running Monotonic Basin Hopping ....")
     isl.evolve(1)
     isl.join()
     print("Is the solution found a feasible trajectory? " +
           str(prob.feasibility_x(isl.population.champion.x)))
     print(isl.population.champion.x)
     prob.plot(isl.population.champion.x)
示例#13
0
		def __init__(self, algo1, algo2, prob, pop_size=20, min_trials=20, p = 0.05, max_runs=200):
			"""
			Upon construction of the class object the race is initialized and launched.
			
			USAGE: r = PyGMO.race2algos(algo1, algo2, prob, pop_size=20, min_trials=20, p = 0.05, max_runs=200):
			
			* algo1: first algorithm in the race
			* algo2: second algorithm in the race
			* prob: problem (i.e. the "track" the algos are racing upon)
			* pop_size: population size of the island where the algos will perform evolution
			* min_trials: minimum number of runs to compare the algorithms
			* p: confidence level
			* max_runs: maximum number of races ....
			"""
			from random import randint
			from copy import deepcopy
			from sys import stdout
			self.algo1=algo1
			self.algo2=algo2
			self.prob=prob
			self.res1 = []
			self.res2 = []
			self.pop_size = pop_size
			self.p = 0
			self.z = 0
			self.p_req = p
			print "Racing the algorithms ..."
			
			for i in range(max_runs):
				stdout.write("\rRuns: %i" % i); stdout.flush()
				#We reset the random number generators of the algorithm
				algo1.reset_rngs(randint(0,9999999)); algo2.reset_rngs(randint(0,9999999))
				#We create an island with 20 individuals. This also initalizes its population at random within the box bounds
				isl1 = island(algo1,prob,self.pop_size)
				#We copy the island and change its algo. Like this we make sure the two algorithms
				#will evolve the same inital population (good practice)
				isl2 = deepcopy(isl1)
				isl2.algorithm = algo2
				#We start the evolution (in parallel as we do not call the method join())
				isl1.evolve(1); isl2.evolve(1)
				#Here join is called implicitly as we try to access one of the islands during evolution
				self.res1.append(isl1.population.champion.f[0])
				self.res2.append(isl2.population.champion.f[0])
				#We check that the race is over (only after having accumulated at least min_trials samples)
				if (i>min_trials):
					if (self.are_different(self.res1,self.res2)):
						break
示例#14
0
def example_1(n_trials=25, variant_adptv=1, memory=True):
	from PyGMO import problem, algorithm, island, archipelago
	from PyGMO.topology import fully_connected
	from numpy import mean, median
	results = list()
	prob = problem.messenger_full()
	de_variants = [11,13,15,17]
	algos = [algorithm.jde(gen=50,variant=v, memory=memory, variant_adptv=variant_adptv) for v in de_variants]
	
	for trial in range(n_trials):
		archi = archipelago(topology=fully_connected())
		for algo in algos:
			archi.push_back(island(algo,prob,25)) 
		print "Trial N: " + str(trial)
		archi.evolve(30)
		results.append(min([isl.population.champion.f[0] for isl in archi]))
	return (mean(results), median(results), min(results), max(results))
示例#15
0
def run_test(n_trials=200, pop_size = 20, n_gen = 500):
	"""
	This function runs some tests on the algorthm. Use it to verify the correct installation
	of PyGMO.

	USAGE: PyGMO.run_test(n_trials=200, pop_size = 20, n_gen = 500)

	* n_trials: each algorithm will be called n_trials times on the same problem to then evaluate best, mean and std
	* pop_size: this determines the population size 
	* n_gen: this regulates the maximim number of function evaluation

	"""
	from PyGMO import problem, algorithm, island
	from numpy import mean, std
	number_of_trials = n_trials
	number_of_individuals = pop_size
	number_of_generations = n_gen

	prob_list = [problem.schwefel(dim = 10), problem.rastrigin(dim = 10), problem.rosenbrock(dim = 10), problem.ackley(dim = 10), problem.griewank(dim = 10), problem.levy5(10)]
	if __extensions__['gtop']:
		prob_list.append(problem.cassini_1())
		prob_list.append(problem.gtoc_1())
		prob_list.append(problem.cassini_2())
		prob_list.append(problem.messenger_full())
		
	algo_list = [algorithm.pso(gen = number_of_generations), algorithm.mde_pbx(gen = number_of_generations, xtol=1e-30, ftol=1e-30), algorithm.de(gen = number_of_generations,xtol=1e-30, ftol=1e-30), algorithm.jde(gen = number_of_generations, memory=False,xtol=1e-30, ftol=1e-30), algorithm.de_1220(gen = number_of_generations, memory=False,xtol=1e-30, ftol=1e-30), algorithm.sa_corana(iter = number_of_generations*number_of_individuals,Ts = 1,Tf = 0.01), algorithm.ihs(iter = number_of_generations*number_of_individuals), algorithm.sga(gen = number_of_generations), algorithm.cmaes(gen = number_of_generations,xtol=1e-30, ftol=1e-30, memory=False), algorithm.bee_colony(gen = number_of_generations/2)]
	print('\nTrials: ' + str(n_trials) + ' - Population size: ' + str(pop_size) + ' - Generations: ' + str(n_gen))
	for prob in prob_list:
		print('\nTesting problem: ' + prob.get_name() + ', Dimension: ' + str(prob.dimension) )
		print('With Population Size: ' +  str(pop_size) )
		for algo in algo_list:
			print(' ' + str(algo))
			best = []
			best_x = []
			for i in range(0,number_of_trials):
				isl = island(algo,prob,number_of_individuals)
				isl.evolve(1)
				isl.join()
				best.append(isl.population.champion.f)
				best_x.append(isl.population.champion.x)
			print(' Best:\t' + str(min(best)[0]))
			print(' Mean:\t' + str(mean(best)))
			print(' Std:\t' + str(std(best)))
示例#16
0
def run_test():
    from PyGMO import problem, algorithm, island
    from numpy import mean, std
    number_of_trials = 200
    number_of_individuals = 20
    number_of_generations = 500

    prob_list = [
        problem.schwefel(10),
        problem.rastrigin(10),
        problem.rosenbrock(10),
        problem.ackley(10),
        problem.griewank(10)
    ]
    algo_list = [
        algorithm.pso(number_of_generations),
        algorithm.de(number_of_generations, 0.8, 0.8, 2),
        algorithm.sa_corana(number_of_generations * number_of_individuals, 1,
                            0.1),
        algorithm.ihs(number_of_generations * number_of_individuals),
        algorithm.sga(number_of_generations, 0.8, 0.1)
    ]

    for prob in prob_list:
        print('\nTesting problem: ' + str(type(prob)) + ', Dimension: ' +
              str(prob.dimension))
        for algo in algo_list:
            print(' ' + str(algo))
            best = []
            best_x = []
            for i in range(0, number_of_trials):
                isl = island(algo, prob, number_of_individuals)
                isl.evolve(1)
                isl.join()
                best.append(isl.population.champion.f)
                best_x.append(isl.population.champion.x)
            print(' Best:\t' + str(min(best)[0]))
            print(' Mean:\t' + str(mean(best)))
            print(' Std:\t' + str(std(best)))
示例#17
0
    def do_test_migr_setup(self, pop_xs, out_pop_xs, top, n_evolves):
        """ Generic procedure for testing whether the state of populations in 'pop_xs',
        after performing 'n_evolve' migration steps is equal to the expected 'out_pop_xs', given topology 'top'. """
        prob = problem.identity()
        alg = algorithm.null()
        pops = []
        for xs in pop_xs:
            pop = population(prob)
            for x in xs:
                pop.push_back(x)
            pops.append(pop)

        archi = archipelago(distribution_type=distribution_type.broadcast, migration_direction=migration_direction.destination)
        for pop in pops:
            archi.push_back(island(alg, pop, s_policy=migration.best_s_policy(), r_policy=migration.fair_r_policy()))
        archi.topology = top
        archi.evolve_batch(n_evolves, 1, False)
        out_xs = []
        for ii, isl in enumerate(archi, 1):
            out_xs.append(tuple(sorted([i.cur_f for i in isl.population])))
        out_xs = tuple(out_xs)
        self.assertEqual(out_xs, out_pop_xs)
def problem_solver(n_trials=25):
    from PyGMO import problem, algorithm, island, archipelago
    from PyGMO.topology import fully_connected
    from numpy import mean, median
    import csv

    results = list()
    prob = problem.cassini_2()
    de_variants = [11, 13, 15, 17]
    f_variants = [0, 0.2, 0.5, 0.8, 1]
    cr_variants = [0.3, 0.9]
    np_variants = [10, 25, 50]

    for f in f_variants:
        for cr in cr_variants:
            for np in np_variants:
                algos = [algorithm.de(gen=np, f=f, cr=cr) for v in de_variants]

                for trial in range(n_trials):
                    archi = archipelago(topology=fully_connected())
                    for algo in algos:
                        archi.push_back(island(algo, prob, 25))
                    archi.evolve(30)
                    results.append(
                        min([isl.population.champion.f[0] for isl in archi]))

                with open('results.csv', 'a') as out:
                    out.write('%f;' % f)
                    out.write('%f;' % cr)
                    out.write('%f;' % np)
                    out.write('\n')

                    out.write('%f;' % mean(results))
                    out.write('%f;' % median(results))
                    out.write('%f;' % min(results))
                    out.write('%f;' % max(results))
                    out.write('\n')
                out.close()
示例#19
0
def test_aco():
	from PyGMO import problem, algorithm, island
	from numpy import mean, std
	number_of_islands = 5
	number_of_individuals = 30
	number_of_generations = 50
	w = [ [0,1,100,1], [1,0,1,100], [100,1,0,1], [1, 100, 1, 0]]
	prob_list = [problem.tsp(w)]
	algo_list = [algorithm.aco(number_of_generations)]
	for j in range(0,len(prob_list)):
		print('Testing problem: ' + str(type(prob_list[j])) + ', Dimension: ' + str(prob_list[j].dimension))
		for algo in algo_list:
			print('        Testing algorithm: ' + str(algo))
			best = []
			best_x = []
			for i in range(0,number_of_islands):
				isl = island(prob_list[j],algo,number_of_individuals)
				isl.evolve(1)
				isl.join()
				best.append(isl.population.champion.f)
				best_x.append(isl.population.champion.x)
				print('                Best fitness:\t' + str(best[i]))
				print('                Best solution:\t' + str(best_x[i]))
def problem_solver(n_trials=25):
     from PyGMO import problem, algorithm, island, archipelago
     from PyGMO.topology import fully_connected
     from numpy import mean, median
     import csv

     results = list()
     prob = problem.cassini_2()
     de_variants = [11,13,15,17]
     f_variants = [0, 0.2, 0.5, 0.8, 1]
     cr_variants = [0.3, 0.9]
     np_variants = [10, 25, 50]

     for f in f_variants:
         for cr in cr_variants:
             for np in np_variants:
                 algos = [algorithm.de(gen=np, f=f, cr=cr) for v in de_variants]

                 for trial in range(n_trials):
                         archi = archipelago(topology=fully_connected())
                         for algo in algos:
                                 archi.push_back(island(algo,prob,25))
                         archi.evolve(30)
                         results.append(min([isl.population.champion.f[0] for isl in archi]))

                 with open('results.csv', 'a') as out:
                    out.write('%f;' % f)
                    out.write('%f;' % cr)
                    out.write('%f;' % np)
                    out.write('\n')

                    out.write('%f;' % mean(results))
                    out.write('%f;' % median(results))
                    out.write('%f;' % min(results))
                    out.write('%f;' % max(results))
                    out.write('\n')
                 out.close()
示例#21
0
def test_aco():
    from PyGMO import problem, algorithm, island
    from numpy import mean, std
    number_of_islands = 5
    number_of_individuals = 30
    number_of_generations = 50
    w = [[0, 1, 100, 1], [1, 0, 1, 100], [100, 1, 0, 1], [1, 100, 1, 0]]
    prob_list = [problem.tsp(w)]
    algo_list = [algorithm.aco(number_of_generations)]
    for j in range(0, len(prob_list)):
        print('Testing problem: ' + str(type(prob_list[j])) + ', Dimension: ' +
              str(prob_list[j].dimension))
        for algo in algo_list:
            print('        Testing algorithm: ' + str(algo))
            best = []
            best_x = []
            for i in range(0, number_of_islands):
                isl = island(prob_list[j], algo, number_of_individuals)
                isl.evolve(1)
                isl.join()
                best.append(isl.population.champion.f)
                best_x.append(isl.population.champion.x)
                print('                Best fitness:\t' + str(best[i]))
                print('                Best solution:\t' + str(best_x[i]))
示例#22
0
def single_test(algo,toal_evals=1200, pop_size = 20):
    
    number_of_individuals = pop_size
    '''
    if(algo.get_name() in ('Particle Swarm optimization','Artificial Bee Colony optimization' )):
        number_of_generations = n_gen/2
    else:
        number_of_generations = n_gen
    '''
    
    prob = gauss_problem_stochastic(dim=3, seed=123456)
    isl = island(algo,prob,number_of_individuals)
    
    #best = []
    #best_x = []
    #for i in range(0,number_of_generations):
    while isl.problem.get_evals() < total_evals:
        isl.evolve(1)
        isl.join()
        #best.append( (isl.problem.get_evals(),isl.population.champion.f[0]) )
        #best_x.append(isl.population.champion.x)
    else:
        print isl.problem.get_evals() 
        
    #print(' Best:\t' + str(min(best)[0]))
    #print(' Mean:\t' + str(mean(best)))
    #print(' Std:\t' + str(std(best)))
    
    #print isl.population.champion.f
    #print isl.population.champion.x
    
    #print '!>',prob.human_readable_extra()
    
    #plot_best(best)

    return isl.problem.get_history()
        text = """\tProblem dimension: %s
        Implemented function: f1 = x1, f2 = g * ( 1 - math.sqrt(x1/g) ) (ZDT1)""" % str(self.__dim)
        return text
    

# <codecell>

if __name__ == '__main__':

    print("############### NSGA-II ##########################")
    algo = algorithm.nsga_II(gen = 250)
    prob1 = schaffer_function()
    print(prob1)
    
    pop = population(prob1,100)
    isl = island(algo,pop)
    isl.evolve(1)
    
    isl.population.plot_pareto_fronts()

# <codecell>

    prob2 = zdt_1()
    print(prob2)
    
    pop2 = population(prob2,100)
    isl2 = island(algo,pop2)
    isl2.evolve(1)
    
    isl2.population.plot_pareto_fronts()
示例#24
0
def run_eval(lib_name,algos):
    import pylab
    import numpy
    
    for name,algo in algos:
        
        collect_all_x = []
        collect_all_f = []
        collect_best_f_so_far = []
        collect_all_dx = []
        
        print name,"\t\tRun:",
                
        for i in range(repeats):
            if (i%10) == 0:
                print i,
            
            if lib_name == "PyGMO":
                #---------------------------------------------------
                prob = PyGMO_GaussNoise_Problem(dim,lb,ub)
                isl = island(algo,prob,pop_size)
                pop = isl.population
                
                best = [pop.champion.f]
                best_x = [pop.champion.x]
                all_x = [p.cur_x for p in pop]
                all_f = [p.cur_f for p in pop]
                
                for _ in range(number_of_generations):
                    pop = algo.evolve(pop)
            
                    best.append(pop.champion.f)
                    best_x.append(pop.champion.x)
                    all_x.extend([p.cur_x for p in pop])
                    all_f.extend([p.cur_f for p in pop])
            
                    #print pop.champion.f
                optimum = prob.get_optimum()
                    
                #-----------------------------------------------------
            elif lib_name == "inspyred":
                #-----------------------------------------------------
                ea = algo
                ea.terminator = inspyred.ec.terminators.evaluation_termination
                
                problem = Inspyred_GaussNoise_Problem(dim,lb,ub)
    
                final_pop = ea.evolve(generator=problem.generator, 
                              evaluator=problem.evaluator, 
                              pop_size=30, 
                              bounder=problem.bounder,
                              maximize=problem.maximize,
                              max_evaluations=total_evaluations)
                
                all_x = problem.all_x
                all_f = problem.all_f
                optimum = problem.global_optimum
                #-----------------------------------------------------
            else:
                raise RuntimeError("Unknown lib_name")
                
            all_dx = numpy.sum((numpy.array(all_x) - optimum)**2,axis=1)
            
            best_f_so_far = [all_f[0]]
            for f in all_f[1:]:
                best_f_so_far.append(min(f,best_f_so_far[-1]))
            '''
            if(i == 0):
                pylab.plot(best_f_so_far)
                pylab.plot(all_f)
                pylab.plot(all_dx)
                pylab.show()
            
            '''
            collect_all_x.append(all_x)
            collect_all_f.append(all_f)
            collect_all_dx.append( all_dx)
            collect_best_f_so_far.append(best_f_so_far)
            
        print "." #end repeats
        
        #get into numpy form, remove last dimension that comes from
        #multiobjective optimization compatibility
        collect_all_f = numpy.squeeze(numpy.array(collect_all_f))
        collect_best_f_so_far = numpy.squeeze(numpy.array(collect_best_f_so_far))
        collect_all_dx = numpy.array(collect_all_dx)
        
        #do calculations, all on best_f_so_far other than distance
        median_bf = numpy.median(collect_best_f_so_far,axis=0)
        stddev_bf = numpy.std(collect_best_f_so_far,axis=0)
        under_minusone_bf = numpy.sum( collect_best_f_so_far < -1 , axis=0)/50.0
        
        distance =  numpy.median(collect_all_dx,axis=0)
        
        file_array = numpy.c_[median_bf,stddev_bf,under_minusone_bf,distance]
        
        new_name = name+"_"+str(repeats)+"reps.txt"
        fname = os.path.join(data_dir,new_name)
        
        numpy.savetxt(fname,file_array)
        
    print create_count,exec_count
        return text

# <codecell>

if __name__ == '__main__':

    print("############### Differential Evolution ##########################") 
    algo = algorithm.de(gen = 500)
    results_de_schaffer = []
    results_de_sphere = []
    
    for i in range(30):
        prob = schaffer_function_n2()
        #print("\nSchaffer Function")
        #print(prob)
        isl = island(algo,prob,50)
        #print("Before optimisation: " +  str(isl.population.champion.f[0]) )
        isl.evolve(10)
        results_de_schaffer.append( isl.population.champion.f[0] )
        #print("After optimisation: " + str( isl.population.champion.f[0]) + '\n')
        #print("="*70 + '\n')
        #print("Sphere Function")
        prob2 = sphere_function(dim=100)
        #print(prob2)
        isl2 = island(algo,prob2,50)
        #print("Before optimisation: " + str(isl2.population.champion.f[0]))
        isl2.evolve(10)
        results_de_sphere.append( isl2.population.champion.f[0] )
        #print("After optimisation: " + str(isl2.population.champion.f[0]))
    print("\nSchaffer Function:\n")
    print(xtile(results_de_schaffer, hi = max(results_de_schaffer), lo=min(results_de_schaffer), show="%.10f") )