def test_compute_position_return_values(swarm, bounds): """Test if compute_position() gives the expected shape and range""" topology = VonNeumann() 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): """Test if compute_velocity() gives the expected shape and range""" topology = VonNeumann() 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, p, r): """Test if update_gbest_neighborhood gives the expected return values""" topology = VonNeumann() pos, cost = topology.compute_gbest(swarm, p=p, r=r) 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_invalid_r_or_p_values(options): """Tests if exception is thrown when passing an invalid value for r or p when using a Von Neumann topology""" with pytest.raises(ValueError): GeneralOptimizerPSO(5, 2, options, VonNeumann())
def test_keyword_exception_vonneumann(options, static): """Tests if exceptions are thrown when keywords are missing and a VonNeumann topology is chosen""" with pytest.raises(KeyError): GeneralOptimizerPSO(5, 2, options, VonNeumann())
@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_
def test_neighbor_idx(swarm, p, r): """Test if the neighbor_idx attribute is assigned""" topology = VonNeumann() topology.compute_gbest(swarm, p=p, r=r) assert topology.neighbor_idx is not None