Exemple #1
0
def test_local_kwargs(func):
    """Tests if kwargs are passed properly to the objective function for when kwargs are present"""

    # setup optimizer
    options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9, 'k': 2, 'p': 2}

    x_max = 10 * np.ones(2)
    x_min = -1 * x_max
    bounds = (x_min, x_max)
    opt_ps = LocalBestPSO(n_particles=100,
                          dimensions=2,
                          options=options,
                          bounds=bounds)

    # run it
    cost, pos = opt_ps.optimize(func,
                                1000,
                                print_step=10,
                                verbose=3,
                                a=1,
                                b=100)

    assert np.isclose(cost, 0, rtol=1e-03)
    assert np.isclose(pos[0], 1.0, rtol=1e-03)
    assert np.isclose(pos[1], 1.0, rtol=1e-03)
 def test_ftol_effect(self):
     """Check if setting ftol breaks the optimization process
     accordingly."""
     # Perform a simple optimization
     optimizer = LocalBestPSO(10,2, options=self.options, ftol=1e-1)
     optimizer.optimize(sphere_func, 5000, verbose=0)
     cost_hist = optimizer.get_cost_history
     self.assertNotEqual(cost_hist.shape, (5000, ))
    def test_reset_best_pos_none(self):
        """Tests if best pos is set to NoneType when reset() is called"""
        # Perform a simple optimization
        optimizer = LocalBestPSO(5,2, options=self.options)
        optimizer.optimize(sphere_func, 100, verbose=0)

        optimizer.reset()
        self.assertIsNone(optimizer.best_pos)
    def test_reset_best_cost_inf(self):
        """Tests if best cost is set to infinity when reset() is called"""
        # Perform a simple optimization
        optimizer = LocalBestPSO(5,2, options=self.options)
        optimizer.optimize(sphere_func, 100, verbose=0)

        optimizer.reset()
        self.assertEqual(optimizer.best_cost, np.inf)
Exemple #5
0
 def test_ftol_effect(self):
     """Check if setting ftol breaks the optimization process
     accordingly."""
     # Perform a simple optimization
     optimizer = LocalBestPSO(10, 2, options=self.options, ftol=1e-1)
     optimizer.optimize(sphere_func, 5000, verbose=0)
     cost_hist = optimizer.get_cost_history
     self.assertNotEqual(cost_hist.shape, (5000, ))
 def test_local_correct_pos(self, options):
     """ Test to check local optimiser returns the correct position corresponding to the best cost """
     opt = LocalBestPSO(n_particles=10, dimensions=2, options=options)
     cost, pos = opt.optimize(sphere, iters=5)
     # find best pos from history
     min_cost_idx = np.argmin(opt.cost_history)
     min_pos_idx = np.argmin(sphere(opt.pos_history[min_cost_idx]))
     assert np.array_equal(opt.pos_history[min_cost_idx][min_pos_idx], pos)
Exemple #7
0
 def test_bound_maxmin_fail(self):
     """Tests if exception is thrown when min max of the bound is
     wrong."""
     bounds_1 = (np.array([5,5]), np.array([-5,-5]))
     bounds_2 = (np.array([5,-5]), np.array([-5,5]))
     with self.assertRaises(ValueError):
         optimizer = LocalBestPSO(5,2, bounds=bounds_1, options=self.options)
     with self.assertRaises(ValueError):
         optimizer = LocalBestPSO(5,2, bounds=bounds_2, options=self.options)
Exemple #8
0
    def test_k_fail(self):
        """Tests if exception is thrown when feeding an invalid k."""
        k_less_than_min = {'c1':0.5, 'c2':0.7, 'w':0.5, 'k':-1, 'p':2}
        k_more_than_max = {'c1':0.5, 'c2':0.7, 'w':0.5, 'k':6, 'p':2}

        with self.assertRaises(ValueError):
            optimizer = LocalBestPSO(5,2, bounds=self.safe_bounds, options=k_less_than_min)
        with self.assertRaises(ValueError):
            optimizer = LocalBestPSO(5,2, bounds=self.safe_bounds, options=k_more_than_max)
Exemple #9
0
 def test_vclamp_shape_fail(self):
     """Tests if exception is thrown when velocity_clamp is not equal to 2"""
     velocity_clamp = (1, 1, 1)
     with self.assertRaises(IndexError):
         optimizer = LocalBestPSO(5,
                                  2,
                                  velocity_clamp=velocity_clamp,
                                  options=self.options)
Exemple #10
0
 def test_keyword_check_fail(self):
     """Tests if exceptions are thrown when keywords are missing"""
     check_c1 = {'c2': 0.7, 'w': 0.5, 'k': 2, 'p': 2}
     check_c2 = {'c1': 0.5, 'w': 0.5, 'k': 2, 'p': 2}
     check_m = {'c1': 0.5, 'c2': 0.7, 'k': 2, 'p': 2}
     check_k = {'c1': 0.5, 'c2': 0.7, 'w': 0.5, 'p': 2}
     check_p = {'c1': 0.5, 'c2': 0.7, 'w': 0.5, 'k': 2}
     with self.assertRaises(KeyError):
         optimizer = LocalBestPSO(5, 2, options=check_c1)
     with self.assertRaises(KeyError):
         optimizer = LocalBestPSO(5, 2, options=check_c2)
     with self.assertRaises(KeyError):
         optimizer = LocalBestPSO(5, 2, options=check_m)
     with self.assertRaises(KeyError):
         optimizer = LocalBestPSO(5, 2, options=check_k)
     with self.assertRaises(KeyError):
         optimizer = LocalBestPSO(5, 2, options=check_p)
Exemple #11
0
 def test_init_pos_type_fail(self):
     """Tests if exception is thrown when init_pos is not a list."""
     init_pos = (0.1, 1.5)
     with self.assertRaises(TypeError):
         optimizer = LocalBestPSO(5,
                                  2,
                                  init_pos=init_pos,
                                  options=self.options)
Exemple #12
0
 def test_vclamp_minmax_fail(self):
     """Tests if exception is thrown when velocity_clamp's minmax is wrong"""
     velocity_clamp = (3, 2)
     with self.assertRaises(ValueError):
         optimizer = LocalBestPSO(5,
                                  2,
                                  velocity_clamp=velocity_clamp,
                                  options=self.options)
Exemple #13
0
 def test_vclamp_type_fail(self):
     """Tests if exception is thrown when velocity_clamp is not a tuple."""
     velocity_clamp = [1, 3]
     with self.assertRaises(TypeError):
         optimizer = LocalBestPSO(5,
                                  2,
                                  velocity_clamp=velocity_clamp,
                                  options=self.options)
def test_local_wrong_kwargs(func):
    """Tests kwargs are passed the objective function for when kwargs do not exist"""

    # setup optimizer
    options = {"c1": 0.5, "c2": 0.3, "w": 0.9, "k": 2, "p": 2}

    x_max = 10 * np.ones(2)
    x_min = -1 * x_max
    bounds = (x_min, x_max)
    opt_ps = LocalBestPSO(n_particles=100,
                          dimensions=2,
                          options=options,
                          bounds=bounds)

    # run it
    with pytest.raises(TypeError) as excinfo:
        cost, pos = opt_ps.optimize(func, 1000, print_step=10, c=1, d=100)
        assert "unexpected keyword" in str(excinfo.value)
Exemple #15
0
 def test_init_pos_shape_fail(self):
     """Tests if exception is thrown when init_pos dimension is not equal
     to dimensions"""
     init_pos = [1.5, 3.2, 2.5]
     with self.assertRaises(IndexError):
         optimizer = LocalBestPSO(5,
                                  2,
                                  init_pos=init_pos,
                                  options=self.options)
Exemple #16
0
def test_local_missed_kwargs(func):
    """Tests kwargs are passed the objective function for when kwargs do not exist"""

    # setup optimizer
    options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9, 'k': 2, 'p': 2}

    x_max = 10 * np.ones(2)
    x_min = -1 * x_max
    bounds = (x_min, x_max)
    opt_ps = LocalBestPSO(n_particles=100,
                          dimensions=2,
                          options=options,
                          bounds=bounds)

    # run it
    with pytest.raises(TypeError) as excinfo:
        cost, pos = opt_ps.optimize(func, 1000, print_step=10, verbose=3, a=1)
        assert 'missing 1 required positional argument' in str(excinfo.value)
def test_local_missed_kwargs(func):
    """Tests kwargs are passed the objective function for when kwargs do not exist"""

    # setup optimizer
    options = {"c1": 0.5, "c2": 0.3, "w": 0.9, "k": 2, "p": 2}

    x_max = 10 * np.ones(2)
    x_min = -1 * x_max
    bounds = (x_min, x_max)
    opt_ps = LocalBestPSO(n_particles=100,
                          dimensions=2,
                          options=options,
                          bounds=bounds)

    # run it
    with pytest.raises(TypeError) as excinfo:
        cost, pos = opt_ps.optimize(func, 1000, a=1)
        assert "missing 1 required positional argument" in str(excinfo.value)
def test_local_kwargs(func):
    """Tests if kwargs are passed properly to the objective function for when kwargs are present"""

    # setup optimizer
    options = {"c1": 0.5, "c2": 0.3, "w": 0.9, "k": 2, "p": 2}

    x_max = 10 * np.ones(2)
    x_min = -1 * x_max
    bounds = (x_min, x_max)
    opt_ps = LocalBestPSO(n_particles=100,
                          dimensions=2,
                          options=options,
                          bounds=bounds)

    # run it
    cost, pos = opt_ps.optimize(func, 1000, a=1, b=100)

    assert np.isclose(cost, 0, rtol=1e-03)
    assert np.isclose(pos[0], 1.0, rtol=1e-03)
    assert np.isclose(pos[1], 1.0, rtol=1e-03)
Exemple #19
0
def lbest_reset():
    """Returns a LocalBestPSO instance that has been run and reset to check
    default value"""
    pso = LocalBestPSO(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
Exemple #20
0
def lbest_reset():
    """Returns a LocalBestPSO instance that has been run and reset to check
    default value"""
    pso = LocalBestPSO(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
Exemple #21
0
    def test_reset_best_pos_none(self):
        """Tests if best pos is set to NoneType when reset() is called"""
        # Perform a simple optimization
        optimizer = LocalBestPSO(5, 2, options=self.options)
        optimizer.optimize(sphere_func, 100, verbose=0)

        optimizer.reset()
        self.assertIsNone(optimizer.best_pos)
Exemple #22
0
    def test_reset_best_cost_inf(self):
        """Tests if best cost is set to infinity when reset() is called"""
        # Perform a simple optimization
        optimizer = LocalBestPSO(5, 2, options=self.options)
        optimizer.optimize(sphere_func, 100, verbose=0)

        optimizer.reset()
        self.assertEqual(optimizer.best_cost, np.inf)
Exemple #23
0
 def test_reset(self):
     """Tests if the reset method resets the attributes required"""
     # Perform a simple optimization
     optimizer = LocalBestPSO(5,2, options=self.options)
     optimizer.optimize(sphere_func, 100, verbose=0)
     # Reset the attributes
     optimizer.reset()
     # Perform testing
     self.assertEqual(optimizer.best_cost, np.inf)
     self.assertIsNone(optimizer.best_pos)
Exemple #24
0
def test_ftol_effect(options):
    """Test if setting the ftol breaks the optimization process accodingly"""
    pso = LocalBestPSO(10, 2, options=options, ftol=1e-1)
    pso.optimize(sphere_func, 2000, verbose=0)
    assert np.array(pso.cost_history).shape != (2000,)
Exemple #25
0
 def optimizer_reset(self, options):
     opt = LocalBestPSO(10, 2, options)
     opt.optimize(sphere, 10)
     opt.reset()
     return opt
Exemple #26
0
def test_keyword_exception(options):
    """Tests if exceptions are thrown when keywords are missing"""
    with pytest.raises(KeyError):
        LocalBestPSO(5, 2, options)
Exemple #27
0
def test_vclamp_maxmin_exception(velocity_clamp, options):
    """Tests if the max velocity_clamp is less than min velocity_clamp and
    vice-versa"""
    with pytest.raises(ValueError):
        LocalBestPSO(5, 2, velocity_clamp=velocity_clamp, options=options)
Exemple #28
0
 def optimizer_history(self, options):
     opt = LocalBestPSO(10, 2, options)
     opt.optimize(sphere, 1000)
     return opt
Exemple #29
0
def test_vclamp_shape_exception(velocity_clamp, options):
    """Tests if exception is raised when velocity_clamp's size is not equal
    to 2"""
    with pytest.raises(IndexError):
        LocalBestPSO(5, 2, velocity_clamp=velocity_clamp, options=options)
Exemple #30
0
def test_bound_type_exception(bounds, options):
    """Tests if exception is raised when bound type is not a tuple"""
    with pytest.raises(TypeError):
        LocalBestPSO(5, 2, options=options, bounds=bounds)
Exemple #31
0
def test_bounds_maxmin_exception(bounds, options):
    """Tests if the max bounds is less than min bounds and vice-versa"""
    with pytest.raises(ValueError):
        LocalBestPSO(5, 2, options=options, bounds=bounds)
Exemple #32
0
def test_bounds_size_exception(bounds, options):
    """Tests if exceptions are raised when bound sizes are wrong"""
    with pytest.raises(IndexError):
        LocalBestPSO(5, 2, options=options, bounds=bounds)
Exemple #33
0
def test_invalid_k_or_p_values(options):
    """Tests if exception is thrown when passing
    an invalid value for k or p"""
    with pytest.raises(ValueError):
        LocalBestPSO(5, 2, options)