From 621aabc4964a481226dd899e02cfcf08d7c386cc Mon Sep 17 00:00:00 2001 From: ljvmiranda921 Date: Fri, 28 Jul 2017 20:07:18 +0900 Subject: [PATCH] Update Python versions in CONTRIBUTING.rst (#16) Unless the world really needs to, this package will only support Python 3.X versions. Author: ljvmiranda921 --- AUTHORS.rst | 7 ++- CONTRIBUTING.rst | 2 +- README.rst | 9 ++-- docs/_static/theme_load.css | 17 +++++++ docs/api/pyswarms.base.rst | 19 +++++++ docs/api/pyswarms.rst | 30 +++++++++++ docs/api/pyswarms.single.rst | 26 ++++++++++ docs/api/pyswarms.utils.functions.rst | 19 +++++++ docs/conf.py | 23 ++++++--- docs/index.rst | 11 ++-- docs/usage.rst | 25 +++++++++- pyswarms/__init__.py | 12 ++++- pyswarms/base/__init__.py | 9 +++- pyswarms/base/bs.py | 72 +++++++++++++-------------- pyswarms/single/__init__.py | 11 +++- pyswarms/single/gb.py | 22 ++++---- pyswarms/single/lb.py | 29 ++++++----- pyswarms/utils/functions/__init__.py | 7 ++- 18 files changed, 258 insertions(+), 92 deletions(-) create mode 100644 docs/_static/theme_load.css create mode 100644 docs/api/pyswarms.base.rst create mode 100644 docs/api/pyswarms.rst create mode 100644 docs/api/pyswarms.single.rst create mode 100644 docs/api/pyswarms.utils.functions.rst diff --git a/AUTHORS.rst b/AUTHORS.rst index 02523562..8688e2ee 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -5,9 +5,12 @@ Credits Development Lead ---------------- -* Lester James V. Miranda +* Lester James V. Miranda Contributors ------------ -None yet. Why not be the first? +* `@Carl-K`_ + + +.. _`@Carl-K`: https://github.com/Carl-K diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 208e2f7a..813bba47 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -102,7 +102,7 @@ Before you submit a pull request, check that it meets these guidelines: 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. -3. The pull request should work for Python 2.6, 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check +3. The pull request should work for Python 3.4, 3.5, and above. Check https://travis-ci.org/ljvmiranda921/pyswarms/pull_requests and make sure that the tests pass for all supported Python versions. diff --git a/README.rst b/README.rst index 1982365e..8c5c8012 100644 --- a/README.rst +++ b/README.rst @@ -18,7 +18,7 @@ PySwarms :alt: Updates -PySwarms is a simple, Python-based, Particle Swarm Optimization (PSO) library. +PySwarms is a simple, Python-based, Particle Swarm Optimization (PSO) library. * Free software: MIT license * Documentation: https://pyswarms.readthedocs.io. @@ -52,26 +52,25 @@ To use PySwarms in your project, .. code-block:: python - import pyswarms + import pyswarms as ps Suppose you want to find the minima of :math:`f(x) = x^2` using global best PSO, simply import the built-in sphere function, :code:`pyswarms.utils.functions.sphere_func()`, and the necessary optimizer: .. code-block:: python - from pyswarms.single import GBestPSO + import pyswarms as ps from pyswarms.utils.functions import sphere_func # Set-up hyperparameters options = {'c1': 0.5, 'c2': 0.3, 'm':0.9} # Call instance of PSO - optimizer = GBestPSO(n_particles=10, dims=2, **options) + optimizer = ps.GBestPSO(n_particles=10, dims=2, **options) # Perform optimization stats = optimizer.optimize(sphere_func, iters=100) -More examples can be seen in the :code:`./examples` folder. Credits --------- diff --git a/docs/_static/theme_load.css b/docs/_static/theme_load.css new file mode 100644 index 00000000..0e4da362 --- /dev/null +++ b/docs/_static/theme_load.css @@ -0,0 +1,17 @@ +.wy-menu-vertical header, .wy-menu-vertical p.caption { + color: gold; +} + +.wy-menu-vertical a { + color: white; +} + +.wy-side-nav-search +{ + color: #cacaca; + background: #074E68 +} + +.wy-side-nav-search input[type=text] { + border-color: rgba(7, 78, 104, 0.83); +} \ No newline at end of file diff --git a/docs/api/pyswarms.base.rst b/docs/api/pyswarms.base.rst new file mode 100644 index 00000000..27a01c13 --- /dev/null +++ b/docs/api/pyswarms.base.rst @@ -0,0 +1,19 @@ +pyswarms.base package +===================== + +.. automodule:: pyswarms.base + + +Submodules +---------- + +pyswarms.base.bs module +------------------------ + +.. automodule:: pyswarms.base.bs + :members: + :undoc-members: + :show-inheritance: + :private-members: + :special-members: __init__ + diff --git a/docs/api/pyswarms.rst b/docs/api/pyswarms.rst new file mode 100644 index 00000000..08f8f372 --- /dev/null +++ b/docs/api/pyswarms.rst @@ -0,0 +1,30 @@ +PySwarms package +================= + +.. automodule:: pyswarms + :members: + :undoc-members: + :show-inheritance: + +Base Classes +------------ + +.. toctree:: + + pyswarms.base + + +Optimizers +----------- + +.. toctree:: + + pyswarms.single + + +Utilities +---------- + +.. toctree:: + + pyswarms.utils.functions \ No newline at end of file diff --git a/docs/api/pyswarms.single.rst b/docs/api/pyswarms.single.rst new file mode 100644 index 00000000..5fe41d5d --- /dev/null +++ b/docs/api/pyswarms.single.rst @@ -0,0 +1,26 @@ +pyswarms.single package +======================= + +.. automodule:: pyswarms.single + +Submodules +---------- + +pyswarms.single.gb module +-------------------------- + +.. automodule:: pyswarms.single.gb + :members: + :undoc-members: + :show-inheritance: + :special-members: __init__ + +pyswarms.single.lb module +-------------------------- + +.. automodule:: pyswarms.single.lb + :members: + :undoc-members: + :show-inheritance: + :private-members: + :special-members: __init__ \ No newline at end of file diff --git a/docs/api/pyswarms.utils.functions.rst b/docs/api/pyswarms.utils.functions.rst new file mode 100644 index 00000000..f44ff0b7 --- /dev/null +++ b/docs/api/pyswarms.utils.functions.rst @@ -0,0 +1,19 @@ +pyswarms.utils.functions package +================================ + +.. automodule:: pyswarms.utils.functions + :members: + :undoc-members: + :show-inheritance: + +Submodules +---------- + +pyswarms.utils.functions.single_obj module +------------------------------------------- + +.. automodule:: pyswarms.utils.functions.single_obj + :members: + :undoc-members: + :show-inheritance: + :special-members: \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index 8bfbf09d..bac121a8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -23,13 +23,14 @@ #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this -cwd = os.getcwd() -project_root = os.path.dirname(cwd) +#cwd = os.getcwd() +#project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. -sys.path.insert(0, project_root) +#sys.path.insert(0, project_root) +sys.path.insert(0, os.path.abspath('../')) import pyswarms @@ -40,7 +41,7 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'sphinx.ext.mathjax'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -144,9 +145,15 @@ # "default.css". html_static_path = ['_static'] +html_context = { + 'css_files': [ + '_static/theme_overrides.css', # overrides for wide tables in RTD theme + ], + } + # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. @@ -195,7 +202,7 @@ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). - #'papersize': 'letterpaper', + 'papersize': 'a4paper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', @@ -258,8 +265,8 @@ u'PySwarms Documentation', u'Lester James V. Miranda', 'pyswarms', - 'One line description of project.', - 'Miscellaneous'), + 'PySwarms is a simple, Python-based, Particle Swarm Optimization (PSO) library.', + 'Research'), ] # Documents to append as an appendix to all manuals. diff --git a/docs/index.rst b/docs/index.rst index 12d74e90..8b6eaeed 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -5,15 +5,20 @@ Contents: .. toctree:: :maxdepth: 2 + :caption: General readme installation - usage - modules - contributing authors history +.. toctree:: + :maxdepth: 2 + :caption: Developer's Guide + + contributing + API Documentation + Indices and tables ================== diff --git a/docs/usage.rst b/docs/usage.rst index 1e7b572d..2aef17f9 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -2,6 +2,27 @@ Usage ===== -To use PySwarms in a project:: +To use PySwarms in your project, - import pyswarms +.. code-block:: python + + import pyswarms as ps + +Optimizing a function +---------------------- +Suppose you want to find the minima of :math:`f(x) = x^2` using global best PSO, simply import the +built-in sphere function, :code:`pyswarms.utils.functions.sphere_func()`, and the necessary optimizer: + +.. code-block:: python + + import pyswarms as ps + from pyswarms.utils.functions import sphere_func + + # Set-up hyperparameters + options = {'c1': 0.5, 'c2': 0.3, 'm':0.9} + + # Call instance of PSO + optimizer = ps.GBestPSO(n_particles=10, dims=2, **options) + + # Perform optimization + stats = optimizer.optimize(sphere_func, iters=100) diff --git a/pyswarms/__init__.py b/pyswarms/__init__.py index 6f324244..831ad00c 100644 --- a/pyswarms/__init__.py +++ b/pyswarms/__init__.py @@ -1,7 +1,15 @@ # -*- coding: utf-8 -*- -"""Top-level package for PySwarms.""" +""" +Particle Swarm Optimization (PSO) toolkit +========================================= +PySwarms is a particle swarm optimization (PSO) toolkit that enables +researchers to test variants of the PSO technique in different contexts. +Users can define their own function, or use one of the benchmark functions +in the library. It is built on top of :code:`numpy` and :code:`scipy`, and +is very extensible to accommodate other PSO variations. +""" __author__ = """Lester James V. Miranda""" __email__ = 'ljvmiranda@gmail.com' -__version__ = '0.1.0' +__version__ = '0.1.1' \ No newline at end of file diff --git a/pyswarms/base/__init__.py b/pyswarms/base/__init__.py index 6e80f182..bc2e1b85 100644 --- a/pyswarms/base/__init__.py +++ b/pyswarms/base/__init__.py @@ -1,3 +1,8 @@ -""" Base package for `pyswarms` """ +""" +The :mod:`pyswarms.base` module implements base +swarm classes to implement variants of particle swarm optimization. +""" -from .bs import SwarmBase \ No newline at end of file +from .bs import SwarmBase + +__all__ = ["SwarmBase"] \ No newline at end of file diff --git a/pyswarms/base/bs.py b/pyswarms/base/bs.py index c42c4cd8..e6c31490 100644 --- a/pyswarms/base/bs.py +++ b/pyswarms/base/bs.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -""" bs.py: base class for single-objective PSO """ +""" :code:`bs.py`: base class for single-objective PSO """ import numpy as np @@ -9,35 +9,32 @@ class SwarmBase(object): """Base class for single-objective Particle Swarm Optimization implementations. - Note that all methods here are abstract and raises a - NotImplementedError when not used. When defining your own swarm, + All methods here are abstract and raises a :code:`NotImplementedError` + when not used. When defining your own swarm implementation, create another class, >>> class MySwarm(SwarmBaseClass): >>> def __init__(self): >>> super(MySwarm, self).__init__() - and define all the necessary methods needed for your - implementation. + and define all the necessary methods needed. - Take note that there is no velocity nor position update in this - base class. This enables this class to accommodate any variation - of the position or velocity update, without enforcing a specific - structure. - - If you wish to pattern your update rules to the original PSO by - Eberhant et al., simply check the global best and local best + Take note that there is no velocity nor position update in this + base class. This enables this class to accommodate any variation + of the position or velocity update, without enforcing a specific + structure. As a guide, check the global best and local best implementations in this package. - .. note:: Regarding `**kwargs`, it is highly recommended to include - parameters used in position and velocity updates as keyword - arguments. For parameters that affect the topology of the swarm, - it may be much better to have them as positional arguments. + .. note:: Regarding :code:`**kwargs`, it is highly recommended to + include parameters used in position and velocity updates as + keyword arguments. For parameters that affect the topology of + the swarm, it may be much better to have them as positional + arguments. See Also -------- - swarms.standard.pso.GBestPSO: global-best PSO implementation - swarms.standard.pso.LBestPSO: local-best PSO implementation + :mod:`pyswarms.single.gb`: global-best PSO implementation + :mod:`pyswarms.single.lb`: local-best PSO implementation """ def assertions(self): """Assertion method to check various inputs. @@ -45,13 +42,14 @@ def assertions(self): Raises ------ TypeError - When the `bounds` is not of type tuple + When the :code:`bounds` is not of type tuple IndexError - When the `bounds` is not of size 2. - When the arrays in `bounds` is not of equal size. - When the shape of `bounds` is not the same as `dims`. + When the :code:`bounds` is not of size 2. + When the arrays in :code:`bounds` is not of equal size. + When the shape of :code:`bounds` is not the same as `dims`. ValueError - When the value of `bounds[1]` is less than `bounds[0]`. + When the value of :code:`bounds[1]` is less than + :code:`bounds[0]`. """ # Check setting of bounds @@ -70,10 +68,10 @@ def assertions(self): def __init__(self, n_particles, dims, bounds=None, **kwargs): """Initializes the swarm. - Creates a numpy.ndarray of positions depending on the number - of particles needed and the number of dimensions. The initial - positions of the particles are sampled from a uniform - distribution. + Creates a :code:`numpy.ndarray` of positions depending on the + number of particles needed and the number of dimensions. + The initial positions of the particles are sampled from a + uniform distribution. Attributes ---------- @@ -84,10 +82,10 @@ def __init__(self, n_particles, dims, bounds=None, **kwargs): bounds : tuple of numpy.ndarray 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 (dims,). + be of shape :code:`(dims,)`. **kwargs: dict - a dictionary containing various kwargs for a specific - optimization technique + a dictionary containing various keyword arguments for a + specific optimization technique """ # Initialize primary swarm attributes self.n_particles = n_particles @@ -106,7 +104,7 @@ def optimize(self, f, iters, print_step=1, verbose=1): """Optimizes the swarm for a number of iterations. Performs the optimization to evaluate the objective - function `f` for a number of iterations `iter.` + function :code:`f` for a number of iterations :code:`iter.` Parameters ---------- @@ -130,18 +128,18 @@ def reset(self): """Resets the attributes of the optimizer. All variables/atributes that will be re-initialized when this - method is called should be defined here. Note that this method + method is defined here. Note that this method can be called twice: (1) during initialization, and (2) when this is called from an instance. - It is recommended to keep the number resettable + It is good practice to keep the number of resettable attributes at a minimum. This is to prevent spamming the same object instance with various swarm definitions. - Normally, we would like to keep each swarm definitions as atomic - as possible, where each type of swarm is contained in its own - instance. Thus, the following attributes are the only ones - recommended to be resettable: + Normally, swarm definitions are as atomic as possible, where + each type of swarm is contained in its own instance. Thus, the + following attributes are the only ones recommended to be + resettable: * Swarm position matrix (self.pos) * Velocity matrix (self.pos) * Best scores and positions (gbest_cost, gbest_pos, etc.) diff --git a/pyswarms/single/__init__.py b/pyswarms/single/__init__.py index 55ba2468..a279aac2 100644 --- a/pyswarms/single/__init__.py +++ b/pyswarms/single/__init__.py @@ -1,4 +1,11 @@ -""" Single-objective optimization package for `pyswarms` """ +""" +The :mod:`pyswarms.single` module implements various techniques in +continuous single-objective optimization. These require only one +objective function that can be optimized in a continuous space. +""" from .gb import GBestPSO -from .lb import LBestPSO \ No newline at end of file +from .lb import LBestPSO + +__all__ = ["GBestPSO", + "LBestPSO"] \ No newline at end of file diff --git a/pyswarms/single/gb.py b/pyswarms/single/gb.py index 6fc65dd8..e55f5476 100644 --- a/pyswarms/single/gb.py +++ b/pyswarms/single/gb.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -""" gb.py: global-best partical swarm optimization algorithm """ +""" gb.py: global-best particle swarm optimization algorithm """ # Import modules import numpy as np @@ -17,8 +17,8 @@ class GBestPSO(SwarmBase): star-topology where each particle is attracted to the best performing particle. - .. note:: This algorithm was adapted from the earlier works of J. - Kennedy and R.C. Eberhart in Particle Swarm Optimization [1]_ + This algorithm was adapted from the earlier works of J. Kennedy and + R.C. Eberhart in Particle Swarm Optimization [1]_ .. [1] J. Kennedy and R.C. Eberhart, "Particle Swarm Optimization," Proceedings of the IEEE International Joint Conference on Neural @@ -45,9 +45,9 @@ def assertions(self): def __init__(self, n_particles, dims, bounds=None, **kwargs): """Initializes the swarm. - Takes the same attributes as SwarmBase, but also + Takes the same attributes as :code:`SwarmBase`, but also initializes a velocity component by sampling from a random - distribution with range [0,1]. + distribution with range :code:`[0,1]`. Attributes ---------- @@ -55,10 +55,10 @@ def __init__(self, n_particles, dims, bounds=None, **kwargs): number of particles in the swarm. dims : int number of dimensions in the space. - bounds : tuple of np.ndarray, optional (default is None) + bounds : tuple of np.ndarray, optional (default is :code:`None`) 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 (dims,). + be of shape :code:`(dims,)`. **kwargs : dict Keyword argument that must contain the following dictionary keys: @@ -80,7 +80,7 @@ def optimize(self, f, iters, print_step=1, verbose=1): """Optimizes the swarm for a number of iterations. Performs the optimization to evaluate the objective - function `f` for a number of iterations `iter.` + function :code:`f` for a number of iterations :code:`iter.` Parameters ---------- @@ -145,9 +145,9 @@ def reset(self): def _update_velocity_position(self): """Updates the velocity and position of the swarm. - Specifically, it updates the attributes self.velocity and - self.pos. This function is being called by the - self.optimize() method + Specifically, it updates the attributes :code:`self.velocity` + and :code:`self.pos`. This function is being called by the + :code:`self.optimize()` method """ # Define the hyperparameters from kwargs dictionary c1, c2, m = self.kwargs['c1'], self.kwargs['c2'], self.kwargs['m'] diff --git a/pyswarms/single/lb.py b/pyswarms/single/lb.py index f73158b7..45b2e073 100644 --- a/pyswarms/single/lb.py +++ b/pyswarms/single/lb.py @@ -19,13 +19,12 @@ class LBestPSO(SwarmBase): attracted to its corresponding neighborhood. In this implementation, a neighbor is selected via a k-D tree - imported from scipy. Distance are computed with either + imported from :code:`scipy`. Distance are computed with either the L1 or L2 distance. The nearest-neighbours are then queried from this k-D tree. - .. note:: This algorithm was adapted from one of the earlier works - of J. Kennedy and R.C. Eberhart in Particle Swarm Optimization - [1]_ [2]_ + This algorithm was adapted from one of the earlier works of + J. Kennedy and R.C. Eberhart in Particle Swarm Optimization [1]_ [2]_ .. [1] J. Kennedy and R.C. Eberhart, "Particle Swarm Optimization," Proceedings of the IEEE International Joint Conference on Neural @@ -44,8 +43,8 @@ def assertions(self): When one of the required dictionary keys is missing. ValueError When the number of neighbors is not within the range - [0, n_particles]. - When the p-value is not in the list of values [1,2]. + :code:`[0, n_particles]`. + When the p-value is not in the list of values :code:`[1,2]`. """ super(LBestPSO, self).assertions() @@ -67,7 +66,7 @@ def __init__(self, n_particles, dims, bounds=None, Takes the same attributes as SwarmBase, but also initializes a velocity component by sampling from a random distribution - with range [0,1]. + with range :code:`[0,1]`. Attributes ---------- @@ -78,8 +77,8 @@ def __init__(self, n_particles, dims, bounds=None, bounds : tuple of np.ndarray, optional (default is None) 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 (dims,). - k: int (default is 1, must be less than n_particles) + be of shape :code:`(dims,)`. + k: int (default is 1, must be less than :code:`n_particles`) number of neighbors to be considered. p: int {1,2} (default is 2) the Minkowski p-norm to use. 1 is the sum-of-absolute values @@ -110,7 +109,7 @@ def optimize(self, f, iters, print_step=1, verbose=1): """Optimizes the swarm for a number of iterations. Performs the optimization to evaluate the objective - function `f` for a number of iterations `iter.` + function :code:`f` for a number of iterations :code:`iter.` Parameters ---------- @@ -160,8 +159,8 @@ def optimize(self, f, iters, print_step=1, verbose=1): def _get_neighbors(self, current_cost): """Helper function to obtain the best position found in the - neighborhood. This uses the cKDTree method from scipy to ob- - tain the nearest neighbours + neighborhood. This uses the cKDTree method from :code:`scipy` + to obtain the nearest neighbours Parameters ---------- @@ -208,9 +207,9 @@ def reset(self): def _update_velocity_position(self): """Updates the velocity and position of the swarm. - Specifically, it updates the attributes self.velocity and - self.pos. This function is being called by the - self.optimize() method + Specifically, it updates the attributes :code:`self.velocity` + and :code:`self.pos`. This function is being called by the + :code:`self.optimize()` method """ # Define the hyperparameters from kwargs dictionary c1, c2, m = self.kwargs['c1'], self.kwargs['c2'], self.kwargs['m'] diff --git a/pyswarms/utils/functions/__init__.py b/pyswarms/utils/functions/__init__.py index 027d7e6a..8bcd8328 100644 --- a/pyswarms/utils/functions/__init__.py +++ b/pyswarms/utils/functions/__init__.py @@ -1,2 +1,5 @@ -""" Package for various objective functions """ -from .single_obj import * +""" +The `pyswarms.utils.functions` module implements various test functions +for optimization. +""" +