def test_multi_obj(problem, algorithm): res = minimize(problem, algorithm, ('n_gen', 300), seed=1, verbose=True) pf = problem.pareto_front() assert IGD(pf).do(res.F) < 0.05
def _evaluate(self, x, f, g, *args, **kwargs): f[:, 0] = -np.min(x * [3, 1], axis=1) g[:, 0] = x[:, 0] + x[:, 1] - 10 def repair(problem, pop, **kwargs): pop.set("X", np.round(pop.get("X")).astype(np.int)) return pop res = minimize(MyProblem(), method='ga', method_args={ 'pop_size': 20, 'crossover': SimulatedBinaryCrossover(prob_cross=0.9, eta_cross=3), 'mutation': PolynomialMutation(eta_mut=2), 'eliminate_duplicates': True, 'func_repair': repair }, termination=('n_gen', 30), disp=True) print("Best solution found: %s" % res.X) print("Function value: %s" % res.F) print("Constraint violation: %s" % res.CV)
from pymoo.optimize import minimize #from Pymoo import algorithm, callback, display from Pymoo.problem import problem from Pymoo.algorithm import algorithm from Pymoo.callback import callback from Pymoo.display import display res = minimize( problem, algorithm, ("n_gen", 5), callback=callback, seed=1, # pf=problem.pareto_front(use_cache=False), save_history=True, display=display, verbose=True) print('Variables:') print(callback.data['var']) print('Objectives:') print(callback.data['obj']) print('Best Objective 1:') for i in range(len(callback.data['best_obj1'])): print('%.6f' % callback.data['best_obj1'][i]) print('Best Objective 2:') for i in range(len(callback.data['best_obj2'])): print('%.6f' % callback.data['best_obj2'][i])
# START nsga3 from pymoo.algorithms.nsga3 import NSGA3 from pymoo.factory import get_problem, get_reference_directions from pymoo.optimize import minimize from pymoo.visualization.scatter import Scatter # create the reference directions to be used for the optimization ref_dirs = get_reference_directions("das-dennis", 3, n_partitions=12) # create the algorithm object algorithm = NSGA3(pop_size=92, ref_dirs=ref_dirs) # execute the optimization res = minimize(get_problem("dtlz1"), algorithm, seed=1, termination=('n_gen', 600)) Scatter().add(res.F).show() # END nsga3 # START inverted_dtzl_1 res = minimize(get_problem("dtlz1^-1"), algorithm, seed=1, termination=('n_gen', 600)) Scatter().add(res.F).show() # END inverted_dtzl_1
from pymoo.algorithms.nsga2 import NSGA2 from pymoo.factory import get_problem, get_sampling, get_crossover, get_mutation from pymoo.optimize import minimize from pymoo.visualization.scatter import Scatter problem = get_problem("zdt5") algorithm = NSGA2(pop_size=100, sampling=get_sampling("bin_random"), crossover=get_crossover("bin_two_point"), mutation=get_mutation("bin_bitflip"), eliminate_duplicates=True) res = minimize(problem, algorithm, ('n_gen', 500), seed=1, verbose=False) Scatter().add(res.F).show()
import numpy as np from pymoo.algorithms.convex.adam import Adam from pymoo.factory import Rosenbrock from pymoo.optimize import minimize problem = Rosenbrock() X = np.random.random((1, problem.n_var)) algorithm = Adam(X) res = minimize(problem, algorithm, ("n_evals", 100), seed=2, verbose=True) print(res.X) print(res.F)
out["F"] = np.column_stack([f1, f2]) out["G"] = g1 from pymoo.model.repair import Repair class MyRepair(Repair): def _do(self, problem, pop, **kwargs): for k in range(len(pop)): x = pop[k].X if np.random.random() < 0.5: x[2] = 2 - x[0] else: x[0] = 2 - x[2] return pop from pymoo.algorithms.nsga2 import NSGA2 algorithm = NSGA2(pop_size=100, repair=MyRepair(), eliminate_duplicates=True) from pymoo.optimize import minimize from pymoo.visualization.scatter import Scatter res = minimize(MyProblem(), algorithm, ('n_gen', 20), seed=1, verbose=True) plot = Scatter() plot.add(res.F, color="red") plot.show()
#costfunction([1,1]) from pymoo.algorithms.nsga2 import NSGA2 from pymoo.factory import get_problem, get_sampling, get_crossover, get_mutation from pymoo.optimize import minimize from pymoo.visualization.scatter import Scatter from pymoo.model.problem import Problem class IFFL(Problem): def __init__(self): super().__init__(n_var=2, n_obj=2, n_constr=0, xl=anp.array([1, 1]), xu=anp.array([200, 100])) def _evaluate(self, x, out, *args, **kwargs): f = costfunction([x[:, 0], x[:, 1]]) out["F"] = anp.column_stack(f) algorithm = NSGA2(pop_size=40) res = minimize(IFFL(), algorithm, ('n_gen', 40), seed=1, verbose=True) plot = Scatter() plot.add(problem.pareto_front(), plot_type="line", color="black", alpha=0.7) plot.add(res.F, color="red") plot.show()
# parameters algorithm = NSGA2(pop_size=40, n_offsprings=10, sampling=get_sampling("real_random"), crossover=get_crossover("real_sbx", prob=0.9, eta=15), mutation=get_mutation("real_pm", eta=20), eliminate_duplicates=True) # termination criteria (stop criterium) termination = get_termination("n_gen", 40) #solve problem res = minimize(problem, algorithm, termination, seed=1, save_history=True, verbose=True) #%% GET RESULTS #get solutions X = res.X F = res.F #%% PLOT PARETO FRONT # In this case it is possible this plot because there are only 2 objective functions import matplotlib.pyplot as plt plt.figure(figsize=(7, 5)) plt.scatter(F[:, 0], F[:, 1], s=30, facecolors='none', edgecolors='blue')
def test_thread_pool(self): minimize(MyThreadedProblem(), NSGA2(), ("n_gen", 10), seed=1, save_history=False)
def main(): # Define search algorithms algorithms = list() # 1: GA algorithm = GA( pop_size=config.POPULATION_SIZE, sampling=SudoRandomInitialization(), # crossover=AdaptiveSinglePointCrossover(prob=0.8), crossover=get_crossover("real_k_point", n_points=2), mutation=BitStringMutation(), eliminate_duplicates=RefactoringSequenceDuplicateElimination()) algorithms.append(algorithm) # 2: NSGA II algorithm = NSGA2( pop_size=config.POPULATION_SIZE, sampling=SudoRandomInitialization(), # crossover=AdaptiveSinglePointCrossover(prob=0.8), crossover=get_crossover("real_k_point", n_points=2), mutation=BitStringMutation(), eliminate_duplicates=RefactoringSequenceDuplicateElimination()) algorithms.append(algorithm) # 3: NSGA III # Todo: Ask for best practices in determining ref_dirs ref_dirs = get_reference_directions("energy", 8, 90, seed=1) algorithm = NSGA3( ref_dirs=ref_dirs, pop_size=config.POPULATION_SIZE, sampling=SudoRandomInitialization(), # crossover=AdaptiveSinglePointCrossover(prob=0.8), crossover=get_crossover("real_k_point", n_points=2), mutation=BitStringMutation(), eliminate_duplicates=RefactoringSequenceDuplicateElimination()) algorithms.append(algorithm) # Define problems problems = list() problems.append( ProblemSingleObjective(n_refactorings_lowerbound=config.LOWER_BAND, n_refactorings_upperbound=config.UPPER_BAND)) problems.append( ProblemMultiObjective(n_refactorings_lowerbound=config.LOWER_BAND, n_refactorings_upperbound=config.UPPER_BAND)) problems.append( ProblemManyObjective(n_refactorings_lowerbound=config.LOWER_BAND, n_refactorings_upperbound=config.UPPER_BAND)) # Do optimization for various problems with various algorithms res = minimize(problem=problems[2], algorithm=algorithms[2], termination=('n_gen', config.MAX_ITERATIONS), seed=1, verbose=True) logger.info("** FINISHED **") logger.info("Best Individual:") logger.info(res.X) logger.info("Objective Values:") logger.info(res.F) logger.info("==================") logger.info("Other Solutions:") for ind in res.opt: logger.info(ind.X) logger.info(ind.F) logger.info("==================") logger.info(f"Start Time: {res.start_time}") logger.info(f"End Time: {res.end_time}") logger.info(f"Execution Time in Seconds: {res.exec_time}")
problem = get_problem("carside") #problem = ConvexProblem(DTLZ2(n_var=12, n_obj=3)) n_gen = 400 pop_size = 91 ref_dirs = UniformReferenceDirectionFactory(3, n_partitions=12, scaling=1.0).do() # create the pareto front for the given reference lines pf = problem.pareto_front( UniformReferenceDirectionFactory(3, n_partitions=70, scaling=1.0).do()) res = minimize( problem, method='nsga3', method_args={ 'pop_size': 91, 'ref_dirs': ref_dirs, 'survival': DSSSurvival() }, termination=('n_gen', n_gen), # pf=pf, save_history=True, seed=31, disp=True) #plotting.plot(pf, res.F, labels=["Pareto-front", "F"]) plotting.plot(res.F, labels=["F"])
crossover_func_args, mutation_func, mutation_func_args, )) if algorithm is None: raise RuntimeError("Input alg_name = {} is not valid or " "not supported within run_MOO.py".format( MOO_CONFIG.alg_name)) # convert dict {'n_gen': 2}} to tuple ('n_gen', 2) termination = list(MOO_CONFIG["termination"].items())[0] MOO_log(msg="termination = {}".format(termination)) res = minimize(problem=problem, algorithm=algorithm, termination=termination, verbose=True) x = res.pop.get("X") MOO_log(msg="location index = \n {}".format(x)) X_1D = x.flatten() X_1D = X_1D.astype('int64') # read accessible_camp_ipc.csv df = pd.read_csv("accessible_camp_ipc.csv") camp_coords_df = df[['lon', 'lat']] coords = camp_coords_df.to_numpy() # obtain coordinates of selected camps popu = coords[X_1D, :]
from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.factory import get_problem from pymoo.optimize import minimize problem = get_problem("g01") algorithm = GA(pop_size=100, eliminate_duplicates=True) res = minimize(problem, algorithm, termination=('n_gen', 50), seed=1, verbose=False) print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
from pymoo.algorithms.nsga2 import NSGA2 from pymoo.factory import get_problem, get_termination from pymoo.optimize import minimize problem = get_problem("zdt3") algorithm = NSGA2(pop_size=100) termination = get_termination("x_tol", tol=0.001, n_last=20, n_max_gen=None, nth_gen=10) res = minimize(problem, algorithm, termination, pf=problem.pareto_front(), seed=1, verbose=False) print(res.algorithm.n_gen)
return Population.merge(bias, other) parse_doc_string(MMGA.__init__) if __name__ == '__main__': problem = MultiModalSimple2() algorithm = MMGA( pop_size=20, eliminate_duplicates=True) ret = minimize(problem, algorithm, termination=('n_gen', 100), seed=1, save_history=True, verbose=False) def plot(algorithm): pop = algorithm.pop sc = Scatter(title=algorithm.n_gen) sc.add(curve(algorithm.problem), plot_type="line", color="black") sc.add(np.column_stack([pop.get("X"), pop.get("F")]), color="red") sc.do() plot(ret.algorithm) plt.show()
import numpy as np from pymoo.algorithms.nsga3 import NSGA3 from pymoo.factory import get_problem, get_reference_directions from pymoo.optimize import minimize from pymoo.visualization.pcp import PCP p = "dtlz5" # create the reference directions to be used for the optimization ref_dirs = get_reference_directions("das-dennis", 5, n_partitions=6) problem = get_problem(p, n_obj=5) # create the algorithm object algorithm = NSGA3(ref_dirs=ref_dirs) # execute the optimization ret = minimize( problem, algorithm, # pf=problem.pareto_front(ref_dirs), seed=1, termination=('n_gen', 1000), verbose=True) np.savetxt("%s_%s.f" % (p, len(ref_dirs)), ret.F) PCP().add(ret.F).show()
if __name__ == "__main__": np.random.seed(123456) # create the reference directions to be used for the optimization refs = get_reference_directions("das-dennis", 10, n_partitions=7) print(refs[0:3]) print("refs.shape =", refs.shape) ref_dirs = simplex(refs.shape[0], 10) print(ref_dirs[0:3]) print("ref_dirs.shape =", ref_dirs.shape) # sys.exit(0) # create the algorithm object algorithm = NSGA3(pop_size=ref_dirs.shape[0], ref_dirs=ref_dirs) # execute the optimization res = minimize(GAA(), algorithm, seed=1, termination=('n_gen', 8000), verbose=True) # save the results if res.X is not None: np.savetxt("x-das.csv", res.X, delimiter=',', fmt='%1.4e') np.savetxt("f-das.csv", res.F, delimiter=',', fmt='%1.4e') np.savetxt("g-das.csv", res.G, delimiter=',', fmt='%1.4e') np.savetxt("cv-das.csv", res.CV, delimiter=',', fmt='%1.4e') else: print("Error: no solution found, X is empty.")
f1 = T f2 = L f3 = M g1 = (np.zeros((x.shape, 1)))**2 - 1e-5 #%%problem from pymoo.model.problem import FunctionalProblem from pymoo.model.problem import ConstraintsAsPenaltyProblem problem = FunctionalProblem(2, objs, xl=-2, xu=2, constr_ieq=constr_ieq, constr_eq=constr_eq) problem = ConstraintsAsPenaltyProblem(problem, penalty=1e6) #%%optimize from pymoo.algorithms.nsga2 import NSGA2 from pymoo.optimize import minimize algorithm = NSGA2(pop_size=40) res = minimize(problem, algorithm, seed=1) #%%visualize from pymoo.visualization.scatter import Scatter plot = Scatter(title="Objective Space") plot.add(res.F) plot.show()
mask[next_ind] = False survivors.append(int(next_ind)) niche_count[next_niche] += 1 return survivors if __name__ == "__main__": problem = get_problem("dtlz1", n_var=7, n_obj=3) # create the reference directions to be used for the optimization ref_dirs = UniformReferenceDirectionFactory(3, n_partitions=12).do() # create the pareto front for the given reference lines pf = problem.pareto_front(ref_dirs) res = minimize(problem, method='nsga3', method_args={ 'pop_size': 92, 'ref_dirs': ref_dirs, 'survival': KKTPMReferenceSurvival(ref_dirs) }, termination=('n_gen', 400), pf=pf, seed=31, disp=True) plotting.plot(pf, res.F, labels=["Pareto-front", "F"]) # plotting.plot(res.F, labels=["F"])
def generate_new_goal(self, pose=np.zeros((1, 3)), other_poses=np.zeros((1, 3))): global reg_poly if self.acq_mod == "split_path": if len(self.splitted_goals) > 0: new_pos = self.splitted_goals[0, :] self.splitted_goals = self.splitted_goals[1:, :] return np.append(new_pos, 0) _, reg = calc_voronoi(pose, other_poses, self.map_data) reg_poly = Polygon(reg) res = minimize(self.problem, self.algorithm, ("n_gen", 150), verbose=False) prev_min_dist = 10000 new_pos = pose[:2] for point in res.X: curr_dist = np.linalg.norm(np.subtract(point, pose[:2])) if curr_dist < prev_min_dist: new_pos = np.round(point).astype(np.int) prev_min_dist = curr_dist if True and len(self.train_inputs) > 1: # from pymoo.visualization.scatter import Scatter # plot = Scatter() # plot.add(res.F, color="red") # plot.show() plt.style.use("seaborn") # results = res.F # img_gen = [ # [0, 1], # [0, 2] # ] # for s in img_gen: # f1 = results[:, s[0]] # f4 = results[:, s[1]] # plt.figure() # plt.title("Objective Space", fontsize=20) # plt.plot(f1, f4, 'ob', label=f"Pareto Set: $\\alpha_{s[0] + 1}(x) \\;,\\; \\alpha_{s[1] + 1}(x)$") # plt.xlabel(f"$\\alpha_{s[0] + 1}(x)$", fontsize=20) # plt.ylabel(f"$\\alpha_{s[1] + 1}(x)$", fontsize=20) # plt.xticks(fontsize=20) # plt.yticks(fontsize=20) # plt.legend(loc='lower left', prop={'size': 17}, fancybox=True, shadow=True, frameon=True) xticks = np.arange(0, 1000, 200) yticks = np.arange(0, 1500, 200) xnticks = [str(format(num * 10, ',')) for num in xticks] ynticks = [str(format(num * 10, ',')) for num in yticks] surr = self.surrogate(keys=["s1"])[0] # mapz = np.full_like(self.map_data, np.nan) # for pos in enumerate(self.vector_pos): # mapz[pos[1][1], pos[1][0]] = surr[pos[0]] # mapz = np.power(np.subtract(mapz, lol), 2) plt.imshow(self.map_data, cmap="BuGn_r", origin='lower', zorder=8) # CS = plt.contour(mapz, colors='k', # alpha=0.6, linewidths=1.0, zorder=9) plt.grid(True, zorder=0, color="white") plt.gca().set_facecolor('#eaeaf2') # plt.clabel(CS, inline=1, fontsize=10) plt.xlabel("x (m)", fontsize=20) plt.ylabel("y (m)", fontsize=20) plt.xticks(xticks, labels=xnticks, fontsize=20) plt.yticks(yticks, labels=ynticks, fontsize=20) k = True # for point in self.train_inputs: # if k: # plt.plot(point[0], point[1], 'yo', zorder=10, label='Previous Locations') # k = False # else: # plt.plot(point[0], point[1], 'yo', zorder=10) plt.plot(pose[0], pose[1], 'ro', zorder=10, label='Current Location') # k = True # for pareto in res.X: # pareto = np.round(pareto).astype(np.int) # if self.map_data[pareto[1], pareto[0]] == 0: # if k: # plt.plot(pareto[0], pareto[1], 'Xb', zorder=10, label="Pareto Points") # k = False # else: # plt.plot(pareto[0], pareto[1], 'Xb', zorder=10) # plt.plot(new_pos[0], new_pos[1], 'Xg', zorder=10, label='Closest Pareto Point') plt.plot(np.append(reg[:, 0], reg[0, 0]), np.append(reg[:, 1], reg[0, 1]), '-b', zorder=10) # plt.show(block=True) if self.acq_mod == "split_path" or self.acq_mod == "truncated": beacons_splitted = [] vect_dist = np.subtract(new_pos, pose[:2]) ang = np.arctan2(vect_dist[1], vect_dist[0]) d = np.exp( np.min([ self.gps[key].kernel_.theta[0] for key in list(self.sensors) ])) * self.proportion for di in np.arange(0, np.linalg.norm(vect_dist), d)[1:]: mini_goal = np.array( [di * np.cos(ang) + pose[0], di * np.sin(ang) + pose[1]]).astype(np.int) if self.map_data[mini_goal[1], mini_goal[0]] == 0: beacons_splitted.append(mini_goal) beacons_splitted.append(np.array(new_pos)) self.splitted_goals = np.array(beacons_splitted) new_pos = self.splitted_goals[0, :] self.splitted_goals = self.splitted_goals[1:, :] if len(self.train_inputs) > 1: # plt.plot(new_pos[0], new_pos[1], 'Xk', zorder=10, label='Next Meas. Location') plt.legend(loc='lower left', prop={'size': 17}, fancybox=True, shadow=True, frameon=True) plt.show(block=True) new_pos = np.append(new_pos, 0) return new_pos
from pymoo.algorithms.univariate.golden import GoldenSectionSearch from pymoo.optimize import minimize from pymoo.problems.single import Sphere problem = Sphere(n_var=1) algorithm = GoldenSectionSearch() res = minimize(problem, algorithm, ("n_iter", 30)) print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
def search(self, data: Data, models: Collection[Model], tid: int, **kwargs) -> np.ndarray: kwargs = kwargs['kwargs'] # print ("SEARCH!") prob = SurrogateProblem(self.problem, self.computer, data, models, self.options, tid, self.models_transfer) prob_pymoo = MyProblemPyMoo(self.problem.DP, self.problem.DO, prob) if (kwargs['verbose']): print("prob: ", prob) bestX = [] if (self.problem.DO == 1): # single objective optimizer if ('ga' == kwargs['search_algo']): from pymoo.algorithms.soo.nonconvex.ga import GA from pymoo.optimize import minimize algo = GA(pop_size=kwargs["search_pop_size"]) elif ('pso' == kwargs['search_algo']): from pymoo.algorithms.soo.nonconvex.pso import PSO from pymoo.optimize import minimize algo = PSO(pop_size=kwargs["search_pop_size"]) else: raise Exception( f'Unknown optimization algorithm "{kwargs["search_algo"]}"' ) bestX = [] res = minimize(prob_pymoo, algo, verbose=kwargs['verbose'], seed=1) bestX.append(np.array(res.X).reshape(1, self.problem.DP)) else: # multi objective if ('nsga2' == kwargs['search_algo']): from pymoo.algorithms.moo.nsga2 import NSGA2 from pymoo.optimize import minimize algo = NSGA2(pop_size=kwargs["search_pop_size"]) elif ('moead' == kwargs['search_algo']): from pymoo.algorithms.moo.moead import MOEAD from pymoo.optimize import minimize from pymoo.factory import get_reference_directions ref_dirs = get_reference_directions("das-dennis", self.problem.DO, n_partitions=12) algo = MOEAD(ref_dirs, n_neighbors=15, prob_neighbor_mating=0.7) else: raise Exception( f'Unknown optimization algorithm "{kwargs["search_algo"]}"' ) bestX = [] res = minimize(prob_pymoo, algo, ("n_gen", kwargs["search_gen"]), verbose=kwargs['verbose'], seed=1) firstn = min(int(kwargs['search_more_samples']), np.shape(res.X)[0]) xss = res.X[0:firstn] bestX.append(xss) if (kwargs['verbose']): print(tid, 'OK' if cond else 'KO') sys.stdout.flush() print("bestX", bestX) return (tid, bestX)
pf = original_problem.pareto_front() problem = decompose(original_problem, decomp, weights ) for i in range(100): if i != 23: continue res = minimize(problem, get_algorithm("nelder-mead", n_max_restarts=10, adaptive=True), #scipy_minimize("Nelder-Mead"), #termination=("n_eval", 30000), seed=i, verbose=False) #print(res.X) F = ModifiedZDT1(n_var=n_var).evaluate(res.X, return_values_of="F") print(i, F) opt = decomp.do(pf, weights).argmin() print(pf[opt]) print(decomp.do(pf, weights).min())
# termination, # seed=1, # ) # # print("Traveling Time:", np.round(res.F[0], 3)) # print("Function Evaluations:", res.algorithm.evaluator.n_eval) ant = lambda: GraphAnt(alpha=0.1, beta=2.0, q0=0.9) nn_times = [] for k in range(10): _, time = solve_nearest_neighbor(problem, return_time=True) nn_times.append(time) time = min(nn_times) tau_init = (problem.n_var * time)**-1 pheromones = Pheromones(tau_init=tau_init, rho=0.1) for i in range(problem.n_var): for j in range(i + 1, problem.n_var): pheromones.initialize((i, j)) algorithm = ACO(ant, pheromones, n_ants=10, global_update="best", local_update=True) minimize(problem, algorithm, ("n_gen", 300), seed=1, verbose=True)
from pymoo.optimize import minimize from pymoo.vendor.vendor_scipy import LBFGSB class MySphere(Problem): def __init__(self, n_var=3): super().__init__(n_var=n_var, n_obj=1, n_constr=0, xl=-100, xu=5, type_var=np.double) def _evaluate(self, x, out, *args, **kwargs): out["F"] = np.sum(np.square(x + 10), axis=1) # for the local optimizer this is now a perfectly normalized problem problem = ZeroToOneProblem(MySphere()) algorithm = LBFGSB() res = minimize(problem, algorithm, seed=1, verbose=False) # map the solution back to the original space res.X = problem.denormalize(res.X) print( f"{algorithm.__class__.__name__}: Best solution found: X = {res.X} | F = {res.F} | CV = {res.F}" )
from pymoo.algorithms.so_pso import PSO from pymoo.factory import get_problem, Sphere from pymoo.optimize import minimize problem = get_problem("rastrigin", n_var=4) algorithm = PSO() ret = minimize(problem, algorithm, seed=1, save_history=True, verbose=True) print(ret.X) print("Optimal:", problem.pareto_front()[0]) print(ret.F) if False: with Video(File("pso.mp4")) as vid: for algorithm in ret.history: if algorithm.n_gen % 10 == 0: fl = FitnessLandscape(problem, _type="contour", kwargs_contour=dict(linestyles="solid", offset=-1, alpha=0.4)) fl.do() X = algorithm.pop.get("X") plt.scatter(X[:, 0], X[:, 1], marker="x") X = algorithm.opt.get("X")
# problems to be solved problem = HR(); # Using Genetic Algorithm algorithm = GA( pop_size=200, eliminate_duplicates=True ); start = time.time(); # Set up an optimiser res = minimize( problem, algorithm, termination=('n_gen', 200), seed=1, verbose=True ) end = time.time(); total_time = end-start; # Print best solution print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F)); number_of_angles = 22; number_of_distances = 2; best_angle = []; for a in range(number_of_angles): best_angle.append(res.X[a+number_of_distances])
from pymoo.algorithms.nsga2 import NSGA2 from pymoo.optimize import minimize from pymoo.problems.multi.srn import SRN from pymoo.visualization.scatter import Scatter problem = SRN() algorithm = NSGA2(pop_size=100) res = minimize( problem, algorithm, # ('n_gen', 1000), seed=1, verbose=True) plot = Scatter() plot.add(problem.pareto_set(), plot_type="line", color="black", alpha=0.7) plot.add(res.X, color="red") plot.show() plot = Scatter() plot.add(problem.pareto_front(), plot_type="line", color="black", alpha=0.7) plot.add(res.F, color="red") plot.show()
def test_singe_obj(problem, algorithm): res = minimize(problem, algorithm, seed=1, verbose=True) fmin = problem.pareto_front().flatten()[0] np.testing.assert_almost_equal(fmin, res.F[0], decimal=3)