pyswarms.utils.plotters package

The mod:pyswarms.utils.plotters module implements various visualization capabilities to interact with your swarm. Here, ou can plot cost history and animate your swarm in both 2D or 3D spaces.

pyswarms.utils.plotters.plotters module

Plotting tool for Optimizer Analysis

This module is built on top of matplotlib to render quick and easy plots for your optimizer. It can plot the best cost for each iteration, and show animations of the particles in 2-D and 3-D space. Furthermore, because it has matplotlib running under the hood, the plots are easily customizable.

For example, if we want to plot the cost, simply run the optimizer, get the cost history from the optimizer instance, and pass it to the plot_cost_history() method

import pyswarms as ps
from pyswarms.utils.functions.single_obj import sphere
from pyswarms.utils.plotters import plot_cost_history

# Set up optimizer
options = {'c1':0.5, 'c2':0.3, 'w':0.9}
optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=2,
                                    options=options)

# Obtain cost history from optimizer instance
cost_history = optimizer.cost_history

# Plot!
plot_cost_history(cost_history)
plt.show()

In case you want to plot the particle movement, it is important that either one of the matplotlib animation Writers is installed. These doesn’t come out of the box for pyswarms, and must be installed separately. For example, in a Linux or Windows distribution, you can install ffmpeg as

>>> conda install -c conda-forge ffmpeg

Now, if you want to plot your particles in a 2-D environment, simply pass the position history of your swarm (obtainable from swarm instance):

import pyswarms as ps
from pyswarms.utils.functions.single_obj import sphere
from pyswarms.utils.plotters import plot_cost_history

# Set up optimizer
options = {'c1':0.5, 'c2':0.3, 'w':0.9}
optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=2,
                                    options=options)

# Obtain pos history from optimizer instance
pos_history = optimizer.pos_history

# Plot!
plot_contour(pos_history)

You can also supply various arguments in this method: the indices of the specific dimensions to be used, the limits of the axes, and the interval/ speed of animation.

pyswarms.utils.plotters.plotters.plot_contour(pos_history, canvas=None, title='Trajectory', mark=None, designer=None, mesher=None, animator=None, **kwargs)[source]

Draw a 2D contour map for particle trajectories

Here, the space is represented as a flat plane. The contours indicate the elevation with respect to the objective function. This works best with 2-dimensional swarms with their fitness in z-space.

Parameters:
  • pos_history (numpy.ndarray or list) – Position history of the swarm with shape (iteration, n_particles, dimensions)
  • canvas ((matplotlib.figure.Figure, matplotlib.axes.Axes),) – The (figure, axis) where all the events will be draw. If None is supplied, then plot will be drawn to a fresh set of canvas.
  • title (str, optional) – The title of the plotted graph. Default is Trajectory
  • mark (tuple, optional) – Marks a particular point with a red crossmark. Useful for marking the optima.
  • designer (pyswarms.utils.formatters.Designer, optional) – Designer class for custom attributes
  • mesher (pyswarms.utils.formatters.Mesher, optional) – Mesher class for mesh plots
  • animator (pyswarms.utils.formatters.Animator, optional) – Animator class for custom animation
  • **kwargs (dict) – Keyword arguments that are passed as a keyword argument to matplotlib.axes.Axes plotting function
Returns:

The drawn animation that can be saved to mp4 or other third-party tools

Return type:

matplotlib.animation.FuncAnimation

pyswarms.utils.plotters.plotters.plot_cost_history(cost_history, ax=None, title='Cost History', designer=None, **kwargs)[source]

Create a simple line plot with the cost in the y-axis and the iteration at the x-axis

Parameters:
  • cost_history (array_like) – Cost history of shape (iters, ) or length iters where each element contains the cost for the given iteration.
  • ax (matplotlib.axes.Axes, optional) – The axes where the plot is to be drawn. If None is passed, then the plot will be drawn to a new set of axes.
  • title (str, optional) – The title of the plotted graph. Default is Cost History
  • designer (pyswarms.utils.formatters.Designer, optional) – Designer class for custom attributes
  • **kwargs (dict) – Keyword arguments that are passed as a keyword argument to matplotlib.axes.Axes
Returns:

The axes on which the plot was drawn.

Return type:

matplotlib.axes._subplots.AxesSubplot

pyswarms.utils.plotters.plotters.plot_surface(pos_history, canvas=None, title='Trajectory', designer=None, mesher=None, animator=None, mark=None, **kwargs)[source]

Plot a swarm’s trajectory in 3D

This is useful for plotting the swarm’s 2-dimensional position with respect to the objective function. The value in the z-axis is the fitness of the 2D particle when passed to the objective function. When preparing the position history, make sure that the:

  • first column is the position in the x-axis,
  • second column is the position in the y-axis; and
  • third column is the fitness of the 2D particle

The pyswarms.utils.plotters.formatters.Mesher class provides a method that prepares this history given a 2D pos history from any optimizer.

import pyswarms as ps
from pyswarms.utils.functions.single_obj import sphere
from pyswarms.utils.plotters import plot_surface
from pyswarms.utils.plotters.formatters import Mesher

# Run optimizer
options = {'c1':0.5, 'c2':0.3, 'w':0.9}
optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=2, options)

# Prepare position history
m = Mesher(func=sphere)
pos_history_3d = m.compute_history_3d(optimizer.pos_history)

# Plot!
plot_surface(pos_history_3d)
Parameters:
  • pos_history (numpy.ndarray) – Position history of the swarm with shape (iteration, n_particles, 3)
  • objective_func (callable) – The objective function that takes a swarm of shape (n_particles, 2) and returns a fitness array of (n_particles, )
  • canvas ((matplotlib.figure.Figure, matplotlib.axes.Axes),) – The (figure, axis) where all the events will be draw. If None is supplied, then plot will be drawn to a fresh set of canvas.
  • title (str, optional) – The title of the plotted graph. Default is Trajectory
  • mark (tuple, optional) – Marks a particular point with a red crossmark. Useful for marking the optima.
  • designer (pyswarms.utils.formatters.Designer, optional) – Designer class for custom attributes
  • mesher (pyswarms.utils.formatters.Mesher, optional) – Mesher class for mesh plots
  • animator (pyswarms.utils.formatters.Animator, optional) – Animator class for custom animation
  • **kwargs (dict) – Keyword arguments that are passed as a keyword argument to matplotlib.axes.Axes plotting function
Returns:

The drawn animation that can be saved to mp4 or other third-party tools

Return type:

matplotlib.animation.FuncAnimation

pyswarms.utils.plotters.formatters module

Plot Formatters

This module implements helpful classes to format your plots or create meshes.

class pyswarms.utils.plotters.formatters.Animator(interval: int = 80, repeat_delay=None, repeat: bool = True)[source]

Bases: object

Animator class for specifying animation behavior

You can use this class to modify options on how the animation will be run in the pyswarms.utils.plotters.plot_contour() and pyswarms.utils.plotters.plot_surface() methods.

from pyswarms.utils.plotters import plot_contour
from pyswarms.utils.plotters.formatters import Animator

# Do not repeat animation
my_animator = Animator(repeat=False)

# Assuming we already had an optimizer ready
plot_contour(pos_history, animator=my_animator)
interval

int – Sets the interval or speed into which the animation is played. Default is 80

repeat_delay

int or float, optional – Sets the delay before repeating the animation again.

repeat

bool, optional – Pass False if you don’t want to repeat the animation. Default is True

class pyswarms.utils.plotters.formatters.Designer(figsize: tuple = (10, 8), title_fontsize='large', text_fontsize='medium', legend='Cost', label=['x-axis', 'y-axis', 'z-axis'], limits=[(-1, 1), (-1, 1), (-1, 1)], colormap=<matplotlib.colors.ListedColormap object>)[source]

Bases: object

Designer class for specifying a plot’s formatting and design

You can use this class for specifying design-related customizations to your plot. This can be passed in various functions found in the pyswarms.utils.plotters module.

from pyswarms.utils.plotters import plot_cost_history
from pyswarms.utils.plotters.formatters import Designer

# Set title_fontsize into 20
my_designer = Designer(title_fontsize=20)

# Assuming we already had an optimizer ready
plot_cost_history(cost_history, designer=my_designer)
figsize

tuple – Overall figure size. Default is (10, 8)

title_fontsize

str, int, or float – Size of the plot’s title. Default is large

text_fontsize

str, int, or float – Size of the plot’s labels and legend. Default is medium

legend

str – Label to show in the legend. For cost histories, it states the label of the line plot. Default is Cost

label

array_like – Label to show in the x, y, or z-axis. For a 3D plot, please pass an iterable with three elements. Default is ['x-axis', 'y-axis', 'z-axis']

limits

list – The x-, y-, z- limits of the axes. Pass an iterable with the number of elements representing the number of axes. Default is [(-1, 1), (-1, 1), (-1, 1)]

colormap

matplotlib.cm.Colormap – Colormap for contour plots. Default is cm.viridis

class pyswarms.utils.plotters.formatters.Mesher(func, delta: float = 0.001, limits=[(-1, 1), (-1, 1)], levels: list = array([-2. , -1.93, -1.86, -1.79, -1.72, -1.65, -1.58, -1.51, -1.44, -1.37, -1.3 , -1.23, -1.16, -1.09, -1.02, -0.95, -0.88, -0.81, -0.74, -0.67, -0.6 , -0.53, -0.46, -0.39, -0.32, -0.25, -0.18, -0.11, -0.04, 0.03, 0.1 , 0.17, 0.24, 0.31, 0.38, 0.45, 0.52, 0.59, 0.66, 0.73, 0.8 , 0.87, 0.94, 1.01, 1.08, 1.15, 1.22, 1.29, 1.36, 1.43, 1.5 , 1.57, 1.64, 1.71, 1.78, 1.85, 1.92, 1.99]), alpha: float = 0.3)[source]

Bases: object

Mesher class for plotting contours of objective functions

This class enables drawing a surface plot of a given objective function. You can customize how this plot is drawn with this class. Pass an instance of this class to enable meshing.

from pyswarms.utils.plotters import plot_surface
from pyswarms.utils.plotters.formatters import Mesher
from pyswarms.utils.functions import single_obj as fx

# Use sphere function
my_mesher = Mesher(func=fx.sphere)

# Assuming we already had an optimizer ready
plot_surface(pos_history, mesher=my_mesher)
func

callable – Objective function to plot a surface of.

delta

float – Number of steps when generating the surface plot Default is 0.001

limits

list or tuple – The range, in each axis, where the mesh will be drawn. Default is [(-1,1), (-1,1)]

levels

list or int, optional – Levels on which the contours are shown. If int is passed, then matplotlib automatically computes for the level positions. Default is numpy.arange(-2.0, 2.0, 0.070)

alpha

float, optional – Transparency of the surface plot. Default is 0.3

limits

list, optional – The x-, y-, z- limits of the axes. Pass an iterable with the number of elements representing the number of axes. Default is [(-1, 1), (-1, 1)]

compute_history_3d(pos_history)[source]

Compute a 3D position matrix

The first two columns are the 2D position in the x and y axes respectively, while the third column is the fitness on that given position.

Parameters:pos_history (numpy.ndarray) – Two-dimensional position matrix history of shape (iterations, n_particles, 2)
Returns:3D position matrix of shape (iterations, n_particles, 3)
Return type:numpy.ndarray