def test_store_best_agent_only(): pso = PSO() n_iters = 10 target_fn = Function(lambda x: x**2) space = SearchSpace(lower_bound=[-10], upper_bound=[10], n_iterations=n_iters) history = Opytimizer(space, pso, target_fn).start(store_best_only=True) assert not hasattr(history, 'agents') assert hasattr(history, 'best_agent') assert len(history.best_agent) == n_iters
def test_store_all_agents(): pso = PSO() n_iters = 10 n_agents = 2 target_fn = Function(lambda x: x**2) space = SearchSpace(lower_bound=[-10], upper_bound=[10], n_iterations=n_iters, n_agents=n_agents) history = Opytimizer(space, pso, target_fn).start() assert hasattr(history, 'agents') # Ensuring that the amount of entries is the same as the amount of iterations and # that for each iteration all agents are kept assert len(history.agents) == n_iters assert all(len(iter_agents) == n_agents for iter_agents in history.agents) assert hasattr(history, 'best_agent') assert len(history.best_agent) == n_iters
def test_hook(): pso = PSO() n_iters = 10 counter = 0 target_fn = Function(lambda x: x**2) space = SearchSpace(lower_bound=[-10], upper_bound=[10], n_iterations=n_iters, n_agents=15) def eval_hook(arg_opt, arg_space, arg_target_fn): assert arg_opt is pso assert arg_space is space assert arg_target_fn is target_fn nonlocal counter counter += 1 Opytimizer(space, pso, target_fn).start(pre_evaluation_hook=eval_hook) # The hook is evaluated for each iteration plus initialization assert counter == n_iters + 1
# Number of decision variables n_variables = 1 # Number of running iterations n_iterations = 100 # Lower and upper bounds (has to be the same size as n_variables) lower_bound = [0.00001] upper_bound = [10] # Creating the SearchSpace class s = SearchSpace(n_agents=n_agents, n_iterations=n_iterations, n_variables=n_variables, lower_bound=lower_bound, upper_bound=upper_bound) # Hyperparameters for the optimizer hyperparams = { 'w': 0.7, 'c1': 1.7, 'c2': 1.7 } # Creating PSO's optimizer p = PSO(hyperparams=hyperparams) # Finally, we can create an Opytimizer class o = Opytimizer(space=s, optimizer=p, function=f) # Running the optimization task history = o.start()