def test_compute_position_return_values(swarm, bounds, static): """Test if compute_position() gives the expected shape and range""" topology = Random(static=static) p = topology.compute_position(swarm, bounds) assert p.shape == swarm.velocity.shape if bounds is not None: assert (bounds[0] <= p).all() and (bounds[1] >= p).all()
def test_compute_velocity_return_values(swarm, clamp, static): """Test if compute_velocity() gives the expected shape and range""" topology = Random(static=static) v = topology.compute_velocity(swarm, clamp) assert v.shape == swarm.position.shape if clamp is not None: assert (clamp[0] <= v).all() and (clamp[1] >= v).all()
def test_update_gbest_neighborhood(swarm, k, static): """Test if update_gbest_neighborhood gives the expected return values""" topology = Random(static=static) pos, cost = topology.compute_gbest(swarm, k=k) expected_pos = np.array([9.90438476e-01, 2.50379538e-03, 1.87405987e-05]) expected_cost = 1.0002528364353296 assert cost == pytest.approx(expected_cost) assert pos == pytest.approx(expected_pos)
def test_compute_neighbors_adjacency_matrix(swarm, k, static): """Test if __compute_neighbors() gives the expected matrix""" np.random.seed(1) topology = Random(static=static) adj_matrix = topology._Random__compute_neighbors(swarm, k) comparison_matrix = np.array([[1, 1, 1, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 1, 0, 1, 1], [0, 1, 1, 0, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 0, 1, 1, 1, 0], [1, 1, 1, 0, 1, 1, 1, 0, 0, 1]]) assert np.allclose(adj_matrix, comparison_matrix, atol=1e-8)
def __init__(self, num_params, c1=0.5 + np.log(2.0), c2=0.5 + np.log(2.0), w=0.5 / np.log(2.0), popsize=256, sigma_init=0.1, weight_decay=0.01, communication_topology='star'): self.num_params = num_params self.c1 = c1 self.c2 = c2 self.w = w self.popsize = popsize self.sigma_init = sigma_init self.weight_decay = weight_decay self.best_param = np.zeros(self.num_params) self.best_reward = 0 self.pop_params = np.random.randn(self.popsize, self.num_params) * self.sigma_init self.pbest_params = self.pop_params self.pbest_rewards = np.zeros(self.popsize) self.pop_vel = np.zeros((self.popsize, self.num_params)) self.pop_rewards = np.zeros(self.popsize) self.gbest_param = self.pop_params[np.argmax(self.pop_rewards)] self.gbest_reward = np.max(self.pop_rewards) self.first_iteration = True # Import backend modules l_lims = -np.ones(self.num_params) u_lims = np.ones(self.num_params) bounds = (l_lims, u_lims) import pyswarms.backend as P self.P = P # Global topology will always be used to compute gbest from pyswarms.backend.topology import Star self.global_topology = Star() self.communication_topology = communication_topology # Unless specified, use the star topology. if self.communication_topology == 'random': from pyswarms.backend.topology import Random self.topology = Random() # The Topology Class elif self.communication_topology == 'local': from pyswarms.backend.topology import Ring self.topology = Ring() # The Topology Class else: from pyswarms.backend.topology import Star self.topology = Star() # The Topology Class self.options = {'c1': self.c1, 'c2': self.c2, 'w': self.w} self.swarm = self.P.create_swarm(n_particles=self.popsize, dimensions=self.num_params, options=self.options, center=self.sigma_init, bounds=bounds)
def test_invalid_k_value(options, static): """Tests if exception is thrown when passing an invalid value for k when using a Random topology""" with pytest.raises(ValueError): GeneralOptimizerPSO(5, 2, options, Random(static=static))
def test_keyword_exception_random(options, static): """Tests if exceptions are thrown when keywords are missing and a Random topology is chosen""" with pytest.raises(KeyError): GeneralOptimizerPSO(5, 2, options, Random(static=static))
def test_neighbor_idx(swarm, k, static): """Test if the neighbor_idx attribute is assigned""" topology = Random(static=static) topology.compute_gbest(swarm, k) assert topology.neighbor_idx is not None
def test_compute_neighbors_return_values(swarm, k, static): """Test if __compute_neighbors() gives the expected shape and symmetry""" topology = Random(static=static) adj_matrix = topology._Random__compute_neighbors(swarm, k) assert adj_matrix.shape == (swarm.n_particles, swarm.n_particles) assert np.allclose(adj_matrix, adj_matrix.T, atol=1e-8) # Symmetry test
@pytest.fixture(scope="module") def binary_reset(): """Returns a BinaryPSO instance that has been run and reset to check default value""" pso = BinaryPSO(10, 2, {"c1": 0.5, "c2": 0.7, "w": 0.5, "k": 2, "p": 2}) pso.optimize(sphere_func, 10, verbose=0) pso.reset() return pso @pytest.fixture def options(): """Default options dictionary for most PSO use-cases""" options_ = {"c1": 0.5, "c2": 0.7, "w": 0.5, "k": 2, "p": 2, "r": 1} return options_ @pytest.fixture(params=[ Star(), Ring(static=False), Ring(static=True), Pyramid(static=False), Pyramid(static=True), Random(static=False), Random(static=True), VonNeumann() ]) def topology(request): """Parametrized topology parameter""" topology_ = request.param return topology_