def test_sphere(self): problem = Sphere() for algorithm in [NelderMead(), PatternSearch(), PSO(), GA()]: f, f_opt = test(problem, algorithm) self.assertAlmostEqual(f, f_opt, places=5) print(problem.__class__.__name__, algorithm.__class__.__name__, "Yes")
def test_ask_and_tell(self): # create the algorithm object to be used algorithm = GA(pop_size=100, eliminate_duplicates=True) # create the ask and tell interface object api = AskAndTell(algorithm, n_var=2, n_obj=1, n_constr=1, xl=-10, xu=10) # this loop runs always one step of the algorithm for gen in range(100): # ask the algorithm for values to be evaluated X = api.ask() # evaluate the values - here just some easy calculations F = np.sum(np.square(X), axis=1)[:, None] G = 1 - np.abs(X[:, 0])[:, None] # let the api objects know the objective and constraint values api.tell(F, G=G) print(api.get_population().get("F").min()) # retrieve the results form the api - here the whole population of the algorithm X, F, CV = api.result(only_optimum=False, return_values_of=["X", "F", "CV"]) self.assertTrue(np.allclose(CV, 0)) self.assertTrue(np.allclose(F[:10], 1, atol=1.e-5))
def __init__(self: object, optim: object = None, verbose: bool = False, infill: bool = False): self.eps = 2.22e-16 self.verbose = verbose self.optim = optim self.infill = infill self.n_feat = len(self.optim.var_min) // 2 if self.infill: self.param_objective = lambda params: self.__infill_objective( params) else: self.param_objective = lambda params: self.__parameters_objective( params) self.krigopt = KrigOptim(self.param_objective, optim) self.algorithm = GA( pop_size=optim.num_pop, eliminate_duplicates=True ) #DE(pop_size=optim.num_pop) #PSO(pop_size=optim.num_pop) # if self.verbose: print("Initialized Kriging object with : \n") self.__print_optim__()
def optimize(self, initial_suggest: pd.DataFrame = None, fix_input: dict = None) -> pd.DataFrame: lb = self.space.opt_lb.numpy() ub = self.space.opt_ub.numpy() prob = BOProblem(lb, ub, self.acq, self.space, fix_input) init_pop = self.get_init_pop(initial_suggest) mutation = self.get_mutation() crossover = self.get_crossover() if self.acq.num_obj > 1: algo = NSGA2(pop_size=self.pop, sampling=init_pop, mutation=mutation, crossover=crossover) else: algo = GA(pop_size=self.pop, sampling=init_pop, mutation=mutation, crossover=crossover) res = minimize(prob, algo, ('n_gen', self.iter), verbose=self.verbose) opt_x = res.X.reshape(-1, len(lb)).astype(float) opt_xcont = torch.from_numpy(opt_x[:, :self.space.num_numeric]) opt_xenum = torch.from_numpy(opt_x[:, self.space.num_numeric:]) df_opt = self.space.inverse_transform(opt_xcont, opt_xenum) if fix_input is not None: for k, v in fix_input.items(): df_opt[k] = v return df_opt
def test_sphere_with_constraints(self): problem = SphereWithConstraints() for algorithm in [GA(), NelderMead(), PatternSearch(), CuckooSearch()]: f, f_opt = test(problem, algorithm) self.assertAlmostEqual(f, f_opt, places=3) print(problem.__class__.__name__, algorithm.__class__.__name__, "Yes")
def genetic_algorithm(): algorithm = GA(population_size=100, individual_size=2, eliminate_duplicates=True) res = minimize(problem, algorithm, seed=1, verbose=False) print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
def _subset_selection(pop, nd_F, K): problem = SubsetProblem(pop.get("F")[:, 1], nd_F, K) algorithm = GA(pop_size=100, sampling=MySampling(), crossover=BinaryCrossover(), mutation=MyMutation(), eliminate_duplicates=True) res = minimize(problem, algorithm, ('n_gen', 60), verbose=False) return res.X
def test_crossover(self): for crossover in ['real_de', 'real_sbx', 'real_exp']: print(crossover) method = GA(pop_size=20, crossover=get_crossover(crossover, prob=0.95)) minimize(get_problem("sphere"), method, ("n_gen", 20)) for crossover in [ 'bin_ux', 'bin_hux', 'bin_one_point', 'bin_two_point' ]: print(crossover) method = NSGA2(pop_size=20, crossover=get_crossover(crossover, prob=0.95)) minimize(get_problem("zdt5"), method, ("n_gen", 20))
def solve(seq_length, problem, sampling=None): if sampling is None: sampling = LevelOrderSampling() subproblem = FixedNumberOfShipsProblem(problem, seq_length) termination = MyTermination(f_tol_abs=0.1) algorithm = GA(pop_size=100, sampling=sampling, crossover=BinaryCrossover(), mutation=MyMutation(), eliminate_duplicates=True) res = minimize( subproblem, algorithm, termination, # ('n_gen', 20), seed=1, verbose=False) return res
def run(cross=0.7, ag=None, mut=0.01): algorithm = GA( pop_size=100, sampling=get_sampling("real_random"), crossover=get_crossover("real_one_point", prob=cross), mutation=get_mutation("real_pm", eta=20, prob=mut), #bin_bitflip n_offsprings=ag, #ag=1 -> steady-state, ag=None -> geracional eliminate_duplicates=True) X, F = problem.evaluate(np.random.rand(100, 1), return_values_of=["X", "F"]) termination = get_termination("n_eval", 25000) res = minimize( problem, algorithm, ('n_gen', 200), termination, seed=10, # elitismo verbose=False) return X, F, res
def _do(self): pop_size, n_gen = self.pop_size, self.n_gen n_points, n_dim, = self.n_points, self.n_dim fun = self.fun class MyProblem(Problem): def __init__(self): self.n_points = n_points self.n_dim = n_dim self.n_partitions = get_partition_closest_to_points(n_points, n_dim) super().__init__(n_var=n_points * n_dim, n_obj=1, n_constr=0, xl=0.0, xu=1.0, elementwise_evaluation=True) def get_points(self, x): _x = x.reshape((self.n_points, self.n_dim)) ** 2 _x = _x / _x.sum(axis=1)[:, None] return _x def _evaluate(self, x, out, *args, **kwargs): out["F"] = fun(self.get_points(x)) problem = MyProblem() algorithm = GA(pop_size=pop_size, eliminate_duplicates=True) res = minimize(problem, algorithm, termination=('n_gen', n_gen), verbose=True) ref_dirs = problem.get_points(res.X) return ref_dirs
def run_singleJ(dict_t): # def run_multiJ(): mask = [ "real", "int", "real", "real", "int", "int", "int", "int", "int", "int", "int" ] sampling = MixedVariableSampling(mask, { "real": get_sampling("real_random"), "int": get_sampling("int_random") }) crossover = MixedVariableCrossover( mask, { "real": get_crossover("real_sbx", prob=0.2, eta=3.0), "int": get_crossover("int_sbx", prob=0.2, eta=3.0) }) mutation = MixedVariableMutation( mask, { "real": get_mutation("real_pm", eta=3.0, prob=0.02), "int": get_mutation("int_pm", eta=3.0, prob=0.02) }) #[V_gBurn,ng,Tdig,debt_level,V_cng_p,e_priceS,farm1,farm2,farm3,farm4,farm5,farm6,farm7] problem = BiogasSingleJ(dict_t) # problem = BiogasMultiJ() algorithm = GA( pop_size=dict_t['GA_pop'], sampling=sampling, crossover=crossover, n_offsprings=dict_t['GA_off'], mutation=mutation, eliminate_duplicates=True, ) res = minimize(problem, algorithm, ("n_gen", dict_t['GA_gen']), verbose=True, seed=1, save_history=True) return res
def optimize(self, initial_suggest: pd.DataFrame = None, fix_input: dict = None) -> pd.DataFrame: self.fix = fix_input lb = self.space.opt_lb.numpy() ub = self.space.opt_ub.numpy() prob = get_problem_from_func(self.pymoo_obj, xl=lb, xu=ub, n_var=len(lb)) init_pop = self.get_init_pop(initial_suggest) mutation = self.get_mutation() crossover = self.get_crossover() if self.num_obj > 1: algo = NSGA2(pop_size=self.pop, sampling=init_pop, mutation=mutation, crossover=crossover) else: algo = GA(pop_size=self.pop, sampling=init_pop, mutation=mutation, crossover=crossover) res = minimize(prob, algo, ('n_gen', self.iter), verbose=self.verbose) if res.X is None: # no feasible solution founc opt_x = np.array([ind.X for ind in res.pop]).astype(float) else: opt_x = res.X.reshape(-1, len(lb)).astype(float) opt_xcont = torch.from_numpy(opt_x[:, :self.space.num_numeric]) opt_xenum = torch.from_numpy(opt_x[:, self.space.num_numeric:]) df_opt = self.space.inverse_transform(opt_xcont, opt_xenum) if self.fix is not None: for k, v in self.fix.items(): df_opt[k] = v return df_opt
from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.factory import get_problem, get_termination from pymoo.optimize import minimize problem = get_problem("rastrigin") algorithm = GA(pop_size=100) termination = get_termination("f_tol_s") res = minimize(problem, algorithm, termination, pf=problem.pareto_front(), seed=1, verbose=True) print(res.opt.get("F")) print(res.algorithm.n_gen)
X = pop.get("X") I = np.where(X == 0)[1] for k in range(len(X)): i = I[k] x = X[k] _x = np.concatenate([x[i:], x[:i]]) pop[k].set("X", _x) return pop algorithm = GA( pop_size=20, sampling=RandomPermutationSampling(), mutation=InversionMutation(), # crossover=EdgeRecombinationCrossover(), crossover=OrderCrossover(), repair=StartFromZeroRepair(), eliminate_duplicates=True) # if the algorithm did not improve the last 200 generations then it will terminate (and disable the max generations) termination = SingleObjectiveDefaultTermination(n_last=200, n_max_gen=np.inf) res = minimize(problem, algorithm, termination, seed=1, verbose=False) print(res.F) print(res.algorithm.evaluator.n_eval) visualize(problem, res.X)
from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.operators.crossover.order_crossover import OrderCrossover from pymoo.operators.mutation.inversion_mutation import InversionMutation from pymoo.operators.sampling.random_permutation_sampling import RandomPermutationSampling from pymoo.optimize import minimize from pymoo.problems.single.flowshop_scheduling import visualize, create_random_flowshop_problem from pymoo.util.termination.default import SingleObjectiveDefaultTermination problem = create_random_flowshop_problem(n_machines=5, n_jobs=10, seed=1) algorithm = GA(pop_size=20, eliminate_duplicates=True, sampling=RandomPermutationSampling(), mutation=InversionMutation(), crossover=OrderCrossover()) # if the algorithm did not improve the last 200 generations then it will terminate termination = SingleObjectiveDefaultTermination(n_last=50, n_max_gen=10000) res = minimize(problem, algorithm, termination, seed=1, verbose=True) visualize(problem, res.X)
class MyMutation(Mutation): def _do(self, problem, X, **kwargs): for i in range(X.shape[0]): X[i, :] = X[i, :] is_false = np.where(np.logical_not(X[i, :]))[0] is_true = np.where(X[i, :])[0] X[i, np.random.choice(is_false)] = True X[i, np.random.choice(is_true)] = False return X from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.optimize import minimize algorithm = GA(pop_size=100, sampling=MySampling(), crossover=BinaryCrossover(), mutation=MyMutation(), eliminate_duplicates=True) res = minimize(problem, algorithm, ('n_gen', 75), seed=1, verbose=True) print("Function value: %s" % res.F[0]) print("Subset:", np.where(res.X)[0]) opt = np.sort(np.argsort(L)[:n_max]) print("Optimal Subset:", opt) print("Optimal Function Value: %s" % L[opt].sum())
def create_attack( initial_state, weight, model, scaler, encoder, n_gen, pop_size, n_offsprings, ): problem = VenusProblem(initial_state, weight, model, encoder, scaler) type_mask = [ "real", "int", "real", "real", "real", "real", "real", "real", "real", "real", "real", "int", "real", "real", "int", ] sampling = MixedVariableSampling( type_mask, { "real": get_sampling("real_random"), "int": get_sampling("int_random") }, ) # Default parameters for crossover (prob=0.9, eta=30) crossover = MixedVariableCrossover( type_mask, { "real": get_crossover("real_sbx", prob=0.9, eta=30), "int": get_crossover("int_sbx", prob=0.9, eta=30), }, ) # Default parameters for mutation (eta=20) mutation = MixedVariableMutation( type_mask, { "real": get_mutation("real_pm", eta=20), "int": get_mutation("int_pm", eta=20), }, ) algorithm = GA( pop_size=pop_size, n_offsprings=n_offsprings, sampling=sampling, crossover=crossover, mutation=mutation, eliminate_duplicates=True, return_least_infeasible=True, ) termination = get_termination("n_gen", n_gen) return problem, algorithm, termination
# bandwith) delta = [0.95]*670 # delta[0] = 5 ps = df['ps_score'].values incre_ps = (delta * ps) / (delta * ps + 1 - ps) policy_value = incre_ps.reshape(-1,1) cov_value = df[covariates].values # print(policy_value.shape, cov_value.shape) feature_value = np.concatenate([policy_value,cov_value], axis = 1) # print(policy_value) v_DR = problem.estimator_DR(df[treatment].values, df[outcome].values, df['ps_score'], incre_ps, feature_value, df['y_estimator'], bandwidth) print(v_DR) """Optimization""" algorithm = GA(pop_size=100, eliminate_duplicates=True) res = minimize(problem, algorithm, seed=1, verbose=False) print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
i = I[k] x = X[k] _x = np.concatenate([x[i:], x[:i]]) pop[k].set("X", _x) return pop from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.optimize import minimize from pymoo.factory import get_algorithm, get_crossover, get_mutation, get_sampling from pymoo.problems.single.traveling_salesman import create_random_tsp_problem from pymoo.util.termination.default import SingleObjectiveDefaultTermination algorithm = GA(pop_size=20, sampling=get_sampling("perm_random"), crossover=get_crossover("perm_erx"), mutation=get_mutation("perm_inv"), repair=StartFromZeroRepair(), eliminate_duplicates=True) # if the algorithm did not improve the last 200 generations then it will terminate (and disable the max generations) termination = SingleObjectiveDefaultTermination(n_last=200, n_max_gen=np.inf) # res = minimize( # problem, # algorithm, # termination, # seed=1, # ) # # print("Traveling Time:", np.round(res.F[0], 3))
import numpy as np from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.factory import get_problem from pymoo.model.evaluator import Evaluator from pymoo.model.population import Population from pymoo.optimize import minimize problem = get_problem("sphere") X = np.random.random((500, problem.n_var)) pop = Population(len(X)) pop.set("X", X) Evaluator().eval(problem, pop) algorithm = GA(sampling=pop) res = minimize(problem, algorithm, seed=1, verbose=False) print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
}), bounds=(problem.xl, problem.xu), labels=["$x_%s$" % k for k in range(problem.n_var)]) pcp.set_axis_style(color="grey", alpha=0.5) pcp.add(algorithm.pop.get("X"), color="black", alpha=0.8, linewidth=1.5) if algorithm.off is not None: pcp.add(algorithm.off.get("X"), color="blue", alpha=0.8, linewidth=0.5) pcp.add(algorithm.opt.get("X"), color="red", linewidth=4) pcp.do() self.video.record() problem = get_problem("rastrigin", n_var=10) algorithm = GA(pop_size=50, eliminate_duplicates=True, callback=MyCallback()) ret = minimize(problem, algorithm, termination=('n_gen', 50), seed=1, verbose=False)
off = super().do(problem, pop, n_offsprings, **kwargs) return off selections = [RandomSelection()] # define all the crossovers to be tried crossovers = [SimulatedBinaryCrossover(10.0), SimulatedBinaryCrossover(30.0), DifferentialEvolutionCrossover()] # COMMENT out this line to only use the SBX crossover with one eta value # crossovers = [SimulatedBinaryCrossover(30)] mutations = [NoMutation(), PolynomialMutation(10.0), PolynomialMutation(30.0)] repairs = [] ensemble = EnsembleMating(selections, crossovers, mutations, repairs) problem = Rastrigin(n_var=30) algorithm = GA( pop_size=100, mating=ensemble, eliminate_duplicates=True) res = minimize(problem, algorithm, seed=1, verbose=True) print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
# the packing plan for i z = Z[i] # while the maximum capacity violation holds while weights[i] > Q: # randomly select an item currently picked item_to_remove = np.random.choice(np.where(z)[0]) # and remove it z[item_to_remove] = False # adjust the weight weights[i] -= problem.W[item_to_remove] # set the design variables for the population pop.set("X", Z) return pop problem = create_random_knapsack_problem(30) algorithm = GA(pop_size=200, sampling=get_sampling("bin_random"), crossover=get_crossover("bin_hux"), mutation=get_mutation("bin_bitflip"), repair=ConsiderMaximumWeightRepair(), elimate_duplicates=True) res = minimize(problem, algorithm, termination=('n_gen', 10), disp=True)
from pymoo.algorithms.nsga2 import NSGA2 from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.factory import get_problem from pymoo.model.callback import Callback from pymoo.optimize import minimize import numpy as np import matplotlib.pyplot as plt class MyCallback(Callback): def __init__(self) -> None: super().__init__() self.data["best"] = [] def notify(self, algorithm): self.data["best"].append(algorithm.pop.get("F").min()) problem = get_problem("sphere") algorithm = GA(pop_size=100, callback=MyCallback()) res = minimize(problem, algorithm, ('n_gen', 20), seed=1, verbose=True) val = res.algorithm.callback.data["best"] plt.plot(np.arange(len(val)), val) plt.show()
from pymoo.algorithms.so_genetic_algorithm import GA from pymoo.optimize import minimize from pymoo.problems.single.mopta08 import MOPTA08 problem = MOPTA08("/Users/blankjul/Downloads/mopta_fortran_unix/exec") algorithm = GA(n_offsprings=20, return_least_infeasible=True) res = minimize(problem, algorithm, verbose=True) print(res.F, res.F)