def optimize(results, dir): pg.mp_bfe.init_pool(50) prob = pg.problem(MotGunOptimizationProblem(dir)) bfe = pg.bfe(pg.mp_bfe()) nsga2 = pg.nsga2() nsga2.set_bfe(bfe) algo = pg.algorithm(nsga2) pop = pg.population(prob=prob, size=256, b=bfe) iteration = 1 while True: print(f"\033[31mITERATION: {iteration}\033[m") plt.title(f'Iteration {iteration}') plt.xlabel('Emittance (nm)') plt.ylabel('Charge (fC)') pg.plot_non_dominated_fronts(pop.get_f()) plt.savefig(results / f'{iteration}.png', dpi=300) plt.clf() assert len(pop.get_x()) == len(pop.get_f()) with open(results / f'iteration_{iteration}.txt', 'w+') as f: f.write( '[Mot Z Offset (mm), Phase (deg)] -> [Emittance 4D sqrt (nm), Charge (fC)]\n' ) for i in range(len(pop.get_x())): f.write('{} -> {}\n'.format(pop.get_x()[i], pop.get_f()[i])) pop = algo.evolve(pop) iteration += 1
def addIsland(arc, algo): isl = pg.island( udi=pg.mp_island(), algo=algo, prob=prob, #b=pg.mp_bfe(), b=pg.bfe(udbfe=multi_bfre2()), size=16) arc.push_back(isl)
def _create_algorithm(method, algo_options, n_cores): """Create a pygmo algorithm.""" pygmo_uda = getattr(pg, method) algo = pygmo_uda(**algo_options) try: algo.set_bfe(pg.bfe()) except AttributeError: if n_cores >= 2: warnings.warn( f"Your specified algorithm {method} does not support parallelization. " "Choose another algorithm such as pygmo_gaco to parallelize.") out = pg.algorithm(algo) return out
def _create_population(problem, population_size, x, seed, discard_start_params): """Create a pygmo population object. Args: problem (pygmo.Problem) algo_options (dict) x (np.ndarray) Todo: - constrain random initial values to be in some bounds """ if not discard_start_params: population_size = population_size - 1 pop = pg.population( problem, size=population_size, seed=seed, b=pg.bfe(), ) if not discard_start_params: pop.push_back(x) return pop
def runTest(self): from dcgpy import symbolic_regression, generate_koza_quintic, kernel_set_double, moes4cgp import pygmo as pg import pickle X, Y = generate_koza_quintic() # Interface for the UDPs udp = symbolic_regression(points=X, labels=Y, rows=1, cols=20, levels_back=21, arity=2, kernels=kernel_set_double( ["sum", "diff", "mul", "pdiv"])(), n_eph=2, multi_objective=True, parallel_batches=0) prob = pg.problem(udp) pop = pg.population(prob, 10) # Interface for the UDAs uda = moes4cgp(gen=5, max_mut=3, ftol=1e-3, learn_constants=True, seed=32) algo = pg.algorithm(uda) algo.set_verbosity(0) # Testing some evolutions pop = algo.evolve(pop) # In parallel archi = pg.archipelago(prob=prob, algo=algo, n=16, pop_size=4) archi.evolve() archi.wait_check() # In parallel via bfe uda.set_bfe(pg.bfe(pg.mp_bfe())) pop = uda.evolve(pop) # Pickling. self.assertTrue(repr(algo) == repr(pickle.loads(pickle.dumps(algo))))
import sched, time from threading import Timer tpool = ThreadPool(processes=20) bpool = ThreadPool(processes=20) def bfeCallback(x): def temp(): return udp.fitness(x) return bpool.apply_async(func=temp) muBfe = multi_bfre(callback=bfeCallback) bfe = pg.bfe(udbfe=muBfe) def fdCallback(x): def temp(): e = ExternalR(cmd="C:\\Program Files\\R\\R-4.0.2\\bin\\Rscript.exe", args=["FireDrillUDP.R"], cwd="C:\\repos\\lnu_anti-patterns\\optim") return e.fitness(x=x) res = tpool.apply(func=temp) return res def fdBfeCallback(dvs): muBfe(prob=prob, dvs=dvs)
class ext_proc_objf: def __init__(self, pathToExe): self.pathToExe = pathToExe class my_bfre: def __call__(self, prob, dvs): nx = prob.get_nx() dvs_arr = np.reshape(dvs, (int(len(dvs) / nx), nx)) res = [prob.fitness(x) for x in dvs_arr] # Remember that fitness() returns a vector return np.array(res).flatten() bfe = pg.bfe(udbfe=my_bfre()) class sphere_1d: def get_bounds(self): return ([0], [1]) def fitness(self, dv): return [dv[0]**2] def gradient(self, x): return pg.estimate_gradient(lambda x: self.fitness(x), x) class toy_problem: def __init__(self, dim):
if __name__ == "__main__": class sphere_1d: def get_bounds(self): return ([0], [1]) def fitness(self, dv): i = 0 while (i < 1e7): i = i + 1 return [dv[0]**2] mpbfe = pg.mp_bfe(chunksize=1) pg.mp_bfe.init_pool(processes=4) bfe = pg.bfe(udbfe=mpbfe) udp = pg.schwefel(dim=19) prob = pg.problem(udp) algo = pg.algorithm(pg.simulated_annealing()) pop = pg.population(prob=prob, b=bfe, size=22) archi = pg.archipelago(n=1, algo=algo, pop=pop) print(archi.get_champions_f()) archi.evolve() archi.wait() print(archi.get_champions_f()) print(pop.champion_f) pop = algo.evolve(pop)
# prob=prob, # size=7) # isl2 = pg.island( # udi=pg.mp_island(), # algo = pg.algorithm(pg.cstrs_self_adaptive(iters=500, algo=pg.simulated_annealing())), # prob=prob, # size=7) archi = pg.archipelago( n=0, t=pg.topology(udt=pg.fully_connected(n=80)), # udi=pg.mp_island(), # algo=pg.algorithm(pg.cstrs_self_adaptive(iters=1000, algo=pg.pso())), # prob=prob, # pop_size=16, b=pg.bfe(udbfe=multi_bfre2())) def addIsland(arc, algo): isl = pg.island( udi=pg.mp_island(), algo=algo, prob=prob, #b=pg.mp_bfe(), b=pg.bfe(udbfe=multi_bfre2()), size=16) arc.push_back(isl) for i in range(2): addIsland(arc=archi, algo=pg.algorithm( pg.cstrs_self_adaptive(iters=1000, algo=pg.de(gen=50))))