Skip to content

Commit

Permalink
Change init_pos to center
Browse files Browse the repository at this point in the history
Reference: #119

The name init_pos tends to be confusing. We're not really setting
the initial positions here. Instead, we're just defining where the
center is whenever the swarm is generated. Next, we'll set an
init_pos variable so that we can explicitly set the center

Signed-off-by: Lester James V. Miranda <[email protected]>
  • Loading branch information
ljvmiranda921 committed Jun 7, 2018
1 parent 948e727 commit c8562cb
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 36 deletions.
14 changes: 7 additions & 7 deletions pyswarms/backend/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from .swarms import Swarm


def generate_swarm(n_particles, dimensions, bounds=None, init_pos=1.00):
def generate_swarm(n_particles, dimensions, bounds=None, center=1.00):
"""Generates a swarm
Parameters
Expand All @@ -29,8 +29,8 @@ def generate_swarm(n_particles, dimensions, bounds=None, init_pos=1.00):
a tuple of size 2 where the first entry is the minimum bound while
the second entry is the maximum bound. Each array must be of shape
:code:`(dimensions,)`.
init_pos : :code:`numpy.ndarrray` (default is :code:`1`)
a list of initial positions for generating the swarm
center : :code:`numpy.ndarray` or :code:`float` (default is :code:`1`)
controls the mean or center whenever the swarm is generated randomly.
Returns
-------
Expand All @@ -43,7 +43,7 @@ def generate_swarm(n_particles, dimensions, bounds=None, init_pos=1.00):
lb, ub = bounds
min_bounds = np.repeat(np.array(lb)[np.newaxis, :], n_particles, axis=0)
max_bounds = np.repeat(np.array(ub)[np.newaxis, :], n_particles, axis=0)
pos = init_pos * np.random.uniform(low=min_bounds, high=max_bounds,
pos = center * np.random.uniform(low=min_bounds, high=max_bounds,
size=(n_particles, dimensions))
except ValueError:
raise
Expand Down Expand Up @@ -79,7 +79,7 @@ def generate_velocity(n_particles, dimensions, clamp=None):
else:
return velocity

def create_swarm(n_particles, dimensions, behavior=None, bounds=None, init_pos=1.0, clamp=None):
def create_swarm(n_particles, dimensions, behavior=None, bounds=None, center=1.0, clamp=None):
"""Abstracts the generate_swarm() and generate_velocity() methods
Parameters
Expand All @@ -94,7 +94,7 @@ def create_swarm(n_particles, dimensions, behavior=None, bounds=None, init_pos=1
a tuple of size 2 where the first entry is the minimum bound while
the second entry is the maximum bound. Each array must be of shape
:code:`(dimensions,)`.
init_pos : :code:`numpy.ndarrray` (default is :code:`1`)
center : :code:`numpy.ndarrray` (default is :code:`1`)
a list of initial positions for generating the swarm
clamp : tuple of floats (default is :code:`None`)
a tuple of size 2 where the first entry is the minimum velocity
Expand All @@ -106,6 +106,6 @@ def create_swarm(n_particles, dimensions, behavior=None, bounds=None, init_pos=1
pyswarms.backend.swarms.Swarm
a Swarm class
"""
position = generate_swarm(n_particles, dimensions, bounds, init_pos)
position = generate_swarm(n_particles, dimensions, bounds, center)
velocity = generate_velocity(n_particles, dimensions, clamp)
return Swarm(position, velocity, behavior=behavior)
20 changes: 10 additions & 10 deletions pyswarms/base/base_single.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,13 @@ def assertions(self):
raise ValueError('Make sure that velocity_clamp is in the '
'form (min, max)')

# Check setting of init_pos
if isinstance(self.init_pos, (list, np.ndarray)):
if not len(self.init_pos) == self.dimensions:
raise IndexError('Parameter `init_pos` must be the same shape '
# Check setting of center
if isinstance(self.center, (list, np.ndarray)):
if not len(self.center) == self.dimensions:
raise IndexError('Parameter `center` must be the same shape '
'as dimensions.')
if isinstance(self.init_pos, np.ndarray) and self.init_pos.ndim != 1:
raise ValueError('Parameter `init_pos` must have a 1d array')
if isinstance(self.center, np.ndarray) and self.center.ndim != 1:
raise ValueError('Parameter `center` must have a 1d array')


# Required keys in options argument
Expand Down Expand Up @@ -120,7 +120,7 @@ def setup_logging(self, default_path='./config/logging.yaml',
logging.basicConfig(level=default_level)

def __init__(self, n_particles, dimensions, options,
bounds=None, velocity_clamp=None, init_pos=1.0, ftol=-np.inf):
bounds=None, velocity_clamp=None, center=1.0, ftol=-np.inf):
"""Initializes the swarm.
Creates a Swarm class depending on the values initialized
Expand Down Expand Up @@ -148,7 +148,7 @@ def __init__(self, n_particles, dimensions, options,
a tuple of size 2 where the first entry is the minimum velocity
and the second entry is the maximum velocity. It
sets the limits for velocity clamping.
init_pos : list (default is :code:`None`)
center : list (default is :code:`None`)
an array of size :code:`dimensions`
ftol : float
relative error in objective_func(best_pos) acceptable for convergence
Expand All @@ -161,7 +161,7 @@ def __init__(self, n_particles, dimensions, options,
self.velocity_clamp = velocity_clamp
self.swarm_size = (n_particles, dimensions)
self.options = options
self.init_pos = init_pos
self.center = center
self.ftol = ftol
# Initialize named tuple for populating the history list
self.ToHistory = namedtuple('ToHistory',
Expand Down Expand Up @@ -275,5 +275,5 @@ def reset(self):
# Initialize the swarm
self.swarm = create_swarm(n_particles=self.n_particles,
dimensions=self.dimensions,
bounds=self.bounds, init_pos=self.init_pos,
bounds=self.bounds, center=self.center,
clamp=self.velocity_clamp, behavior=self.options)
6 changes: 3 additions & 3 deletions pyswarms/single/global_best.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
class GlobalBestPSO(SwarmOptimizer):

def __init__(self, n_particles, dimensions, options,
bounds=None, velocity_clamp=None, init_pos=1.00, ftol=-np.inf):
bounds=None, velocity_clamp=None, center=1.00, ftol=-np.inf):
"""Initializes the swarm.
Attributes
Expand All @@ -97,15 +97,15 @@ def __init__(self, n_particles, dimensions, options,
a tuple of size 2 where the first entry is the minimum velocity
and the second entry is the maximum velocity. It
sets the limits for velocity clamping.
init_pos : list (default is :code:`None`)
center : list (default is :code:`None`)
an array of size :code:`dimensions`
ftol : float
relative error in objective_func(best_pos) acceptable for
convergence
"""
super(GlobalBestPSO, self).__init__(n_particles, dimensions, options,
bounds, velocity_clamp,
init_pos, ftol)
center, ftol)

# Initialize logger
self.logger = logging.getLogger(__name__)
Expand Down
6 changes: 3 additions & 3 deletions pyswarms/single/local_best.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def assertions(self):
'or 2 (for L2/Euclidean).')

def __init__(self, n_particles, dimensions, options, bounds=None,
velocity_clamp=None, init_pos=1.00, ftol=-np.inf):
velocity_clamp=None, center=1.00, ftol=-np.inf):
"""Initializes the swarm.
Attributes
Expand All @@ -120,7 +120,7 @@ def __init__(self, n_particles, dimensions, options, bounds=None,
a tuple of size 2 where the first entry is the minimum velocity
and the second entry is the maximum velocity. It
sets the limits for velocity clamping.
init_pos : list (default is :code:`None`)
center : list (default is :code:`None`)
an array of size :code:`dimensions`
ftol : float
relative error in objective_func(best_pos) acceptable for
Expand Down Expand Up @@ -148,7 +148,7 @@ def __init__(self, n_particles, dimensions, options, bounds=None,
self.k, self.p = options['k'], options['p']
# Initialize parent class
super(LocalBestPSO, self).__init__(n_particles, dimensions, options,
bounds, velocity_clamp, init_pos, ftol)
bounds, velocity_clamp, center, ftol)
# Invoke assertions
self.assertions()
# Initialize the resettable attributes
Expand Down
10 changes: 5 additions & 5 deletions tests/backend/test_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@


@pytest.mark.parametrize('bounds', [None, ([2,2,2], [5,5,5]), ([-1,-1,0], [2,2,5])])
@pytest.mark.parametrize('init_pos', [1, [3,3,3], [0.2,0.2,0.1]])
def test_generate_swarm_return_values(bounds, init_pos):
@pytest.mark.parametrize('center', [1, [3,3,3], [0.2,0.2,0.1]])
def test_generate_swarm_return_values(bounds, center):
"""Tests if generate_swarm() returns expected values"""
pos = P.generate_swarm(n_particles=2, dimensions=3, bounds=bounds,
init_pos=init_pos)
center=center)
if bounds is None:
min_bounds, max_bounds = (0.0, 1.00)
else:
min_bounds, max_bounds = bounds
lower_bound = init_pos * np.array(min_bounds)
upper_bound = init_pos * np.array(max_bounds)
lower_bound = center * np.array(min_bounds)
upper_bound = center * np.array(max_bounds)
assert (pos <= upper_bound).all() and (pos >= lower_bound).all()

@pytest.mark.parametrize('clamp', [None, (0,1), (2,5), (1,6)])
Expand Down
8 changes: 4 additions & 4 deletions tests/optimizers/test_global_best.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ def test_vclamp_maxmin_exception(velocity_clamp, options):
with pytest.raises(ValueError):
GlobalBestPSO(5, 2, velocity_clamp=velocity_clamp, options=options)

@pytest.mark.parametrize('err, init_pos',
@pytest.mark.parametrize('err, center',
[(IndexError, [1.5, 3.2, 2.5])])
def test_init_pos_exception(err, init_pos, options):
"""Tests if exception is thrown when init_pos is not a list or of different shape"""
def test_center_exception(err, center, options):
"""Tests if exception is thrown when center is not a list or of different shape"""
with pytest.raises(err):
GlobalBestPSO(5, 2, init_pos=init_pos, options=options)
GlobalBestPSO(5, 2, center=center, options=options)

def test_reset_default_values(gbest_reset):
"""Tests if best cost and best pos are set properly when the reset()
Expand Down
8 changes: 4 additions & 4 deletions tests/optimizers/test_local_best.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ def test_vclamp_maxmin_exception(velocity_clamp, options):
with pytest.raises(ValueError):
LocalBestPSO(5, 2, velocity_clamp=velocity_clamp, options=options)

@pytest.mark.parametrize('err, init_pos',
@pytest.mark.parametrize('err, center',
[(IndexError, [1.5, 3.2, 2.5])])
def test_init_pos_exception(err, init_pos, options):
"""Tests if exception is thrown when init_pos is not a list or of different shape"""
def test_center_exception(err, center, options):
"""Tests if exception is thrown when center is not a list or of different shape"""
with pytest.raises(err):
LocalBestPSO(5, 2, init_pos=init_pos, options=options)
LocalBestPSO(5, 2, center=center, options=options)

def test_reset_default_values(lbest_reset):
"""Tests if best cost and best pos are set properly when the reset()
Expand Down

0 comments on commit c8562cb

Please sign in to comment.