예제 #1
0
def plot3D(optimizer, xValues, yValues, zValues):
    '''

    :param optimizer: optimizer object returned in the application/definition of PSO
    :param xValues: numpy array : 2d (minValue, maxValue) axis
    :param yValues: numpy array : 2d (minValue, maxValue) axis
    :param zValues: numpy array : 2d (minValue, maxValue) axis
    :return: matplotlib object --> position particles 3d plot
    '''

    try:

        #Obtain a position-fitness matrix using the Mesher.compute_history_3d() method.
        positionHistory_3d = Mesher.compute_history_3d(optimizer.pos_history)

        d = Designer(limits=[xValues, yValues, zValues],
                     label=['x-axis', 'y-axis', 'z-axis'])

        plot3d = plot_surface(
            pos_history=positionHistory_3d,
            mesher=Mesher,
            designer=d,
            mark=(1, 1,
                  zValues[0]))  #BEST POSSIBLE POSITION MARK (* --> IN GRAPHIC)

        return plot3d

    except:
        raise
예제 #2
0
def plot_show(func):

    if func == "Sphere":

        m = Mesher(func=fx.sphere, limits=[(-1, 1), (-1, 1)])
    elif func == "Ackley's":

        m = Mesher(func=fx.ackley, limits=[(-1.5, 1.5), (-1.5, 1.5)])

    d = Designer(limits=[(-1, 1), (-1, 1), (-0.1, 1)],
                 label=['x-axis', 'y-axis', 'z-axis'])

    pos_history_3d = m.compute_history_3d(
        optimizer.pos_history)  # preprocessing
    animation3d = plot_surface(pos_history=pos_history_3d,
                               mesher=m,
                               designer=d,
                               mark=(0, 0, 0))
    plt.show()
#Hyperparameters (cognitive, social and inertia weight)
opt = {"c1": 0.5, "c2": 0.3, "w": 0.9}

#The optimizer for sphere function:
optimizer = ps.single.GlobalBestPSO(n_particles=50, dimensions=2, options=opt)
optimizer.optimize(fx.sphere, iters=100)

#history of particle positions for animation
hist = optimizer.pos_history

#This can plot the cost history, not needed for the assignment:
#plot_cost_history(optimizer.cost_history)

#Mesh for the plot:
m = Mesher(func=fx.sphere, limits=[(-1, 1), (-1, 1)])

#This can be used for designing the animation
#but the defaults are enough for this task
#d = Designer(limits=[(-1,1),(-1,1),(-0.1,1)],
#           label=["x-axis","y-axis","z-azis"])

animation = plot_contour(pos_history=hist, mesher=m, mark=(0, 0))

#3D version for fun:
#pos_his_3D = m.compute_history_3d(hist)
#            anim3D = plot_surface(pos_history=pos_his_3D,
#            mesher=m, mark=(0,0,0))

#Shows the sphere animation, the code continues after the animation is closed:
plt.show()
예제 #4
0
#Hyperparameters (cognitive, social and inertia weight)
opt = {"c1": 0.5, "c2": 0.3, "w": 0.9}

#The optimizer for sphere function:
optimizer = ps.single.GlobalBestPSO(n_particles=50, dimensions=2, options=opt)
optimizer.optimize(fx.schaffer2, iters=100)
best_cost, best_pos = optimizer.optimize(fx.schaffer2, iters=100)

#history of particle positions for animation
hist = optimizer.pos_history

#This can plot the cost history, not needed for the assignment:
#plot_cost_history(optimizer.cost_history)

#Mesh for the plot:
m = Mesher(func=fx.schaffer2, limits=[(-1, 1), (-1, 1)])

#This can be used for designing the animation
#but the defaults are enough for this task
#d = Designer(limits=[(-1,1),(-1,1),(-0.1,1)],
#           label=["x-axis","y-axis","z-azis"])

#animation = plot_contour(pos_history=hist, mesher=m,mark=(0,0))
#animation.save("Plot.mp4", writer="imagemagick", fps=10)

#3D version for fun:
pos_his_3D = m.compute_history_3d(hist)
anim3D = plot_surface(pos_history=pos_his_3D, mesher=m, mark=(0, 0, 0))

#Makes the animation a HTML5 video for playing in Jupyter Notebooks!
#HTML(anim3D.to_html5_video())
예제 #5
0
x_max = 2 * np.ones(D)
x_min = -1 * np.ones(D)
bounds = (x_min, x_max)
options = {'c1': 0.3, 'c2': 0.1, 'w': 0.9}

optimizer = ps.single.GlobalBestPSO(n_particles=10,
                                    dimensions=D,
                                    options=options,
                                    bounds=bounds)

# now run the optimization
cost, pos = optimizer.optimize(fx.rosenbrock, 100)

# print(optimizer.pos_history)
m = Mesher(func=fx.rosenbrock, limits=[(-1, 2), (-1, 2)])
d = Designer(limits=[(-1, 2), (-1, 2)], label=['x-axis', 'y-axis'])
animation = plot_contour(pos_history=optimizer.pos_history,
                         mesher=m,
                         designer=d)
animation.save('plot0.gif', writer='imagemagick', fps=20)

# pos_history_3d = m.compute_history_3d(optimizer.pos_history)  # preprocessing
# animation = plot_surface(pos_history=pos_history_3d,
#                             mesher=m, designer=d,
#                             mark=(1, 1, 1))
# animation.save('plot0.gif', writer='imagemagick', fps=10)

# cost evolution vs iterations
plot_cost_history(cost_history=optimizer.cost_history)
예제 #6
0
# Import modules
import matplotlib.pyplot as plt
import numpy as np
from problema import *
# Import PySwarms
import pyswarms as ps
from pyswarms.utils.functions import single_obj as fx
from pyswarms.utils.plotters import (plot_cost_history, plot_contour,
                                     plot_surface)

options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
optimizer = ps.single.GlobalBestPSO(n_particles=50,
                                    dimensions=2,
                                    options=options)
cost, pos = optimizer.optimize(funcao_objetivo, iters=100)

from pyswarms.utils.plotters.formatters import Mesher

m = Mesher(func=fx.sphere)

animation = plot_contour(pos_history=optimizer.pos_history,
                         mesher=m,
                         mark=(0, 0))

animation.save('plot0.gif', writer='imagemagick', fps=10)
예제 #7
0
# https://pyswarms.readthedocs.io/en/latest/features.html#continuous
# https://pyswarms.readthedocs.io/en/latest/api/pyswarms.single.html
optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=2, options=options)

# Perform optimization of the sphere function
# https://pyswarms.readthedocs.io/en/latest/api/pyswarms.utils.functions.html
cost, pos = optimizer.optimize(fx.sphere, iters=100)

# Plot the cost history
from pyswarms.utils.plotters import (plot_cost_history, plot_contour, plot_surface)
plot_cost_history(cost_history=optimizer.cost_history)
plt.show()

# Initialize mesher with sphere function
from pyswarms.utils.plotters.formatters import Mesher
m = Mesher(func=fx.sphere)

# Make animation
animation2d = plot_contour(pos_history=optimizer.pos_history,  # Use the cost_history we computed
                           mesher=m,                           # Customizations
                           mark=(0,0))                         # Mark minima

# Enables us to view it in a Jupyter notebook
animation2d.save('plot0.gif', writer='imagemagick', fps=10)
Image(url='plot0.gif')

# Obtain a position-fitness matrix using the Mesher.compute_history_3d()
# method. It requires a cost history obtainable from the optimizer class
pos_history_3d = m.compute_history_3d(optimizer.pos_history)

# Make a designer and set the x,y,z limits to (-1,1), (-1,1) and (-0.1,1) respectively
예제 #8
0
                                    dimensions=2,
                                    options=options,
                                    bounds=bounds)

# Run optimizer
function = sphere
cost, pos = optimizer.optimize(function, 1000)
limits = [(-4, 4), (-4, 4), (0, 16)]

##########################
# Animate
##########################

# Constants
m = Mesher(
    func=function,
    limits=limits[0:2])  # get the sphere function's mesh (for better plots)
d = Designer(limits=limits, label=['x-axis', 'y-axis',
                                   'z-axis'])  # Adjust figure limits

# Animate in 3D
pos_history_3d = m.compute_history_3d(optimizer.pos_history)  # preprocessing
animation3d = plot_surface(pos_history=pos_history_3d,
                           mesher=m,
                           designer=d,
                           mark=(0, 0, 0))
plt.show()

# # Animate swarm in 2D (contour plot)
# plot_contour(pos_history=optimizer.pos_history, mesher=m, designer=d, mark=(0,0))
# plt.show()
예제 #9
0
파일: conftest.py 프로젝트: dfhljf/pyswarms
def mesher():
    """A Mesher instance with sphere function and delta=0.1"""
    return Mesher(func=sphere, delta=0.1)
예제 #10
0
 def plot3d(self):
     # Prepare position history
     m = Mesher(func=self.model.getCumReturnsError)
     pos_history_3d = m.compute_history_3d(self.optimizer.pos_history)
     plot_surface(pos_history_3d)
    Returns
    ----------
    numpy.ndarray
        computed cost of size :code:`(n_particles, )`
    """
    #min = np.zeros(b.shape)
    #max = 10 * np.ones(b.shape)
    #b = np.minimum(np.maximum(b, min), max)
    cost = -(np.sin(b[:, 0] - b[:, 1])**2) * (
        np.sin(b[:, 0] + b[:, 1])**2) / np.sqrt(b[:, 0]**2 + b[:, 1]**2)

    return cost


# Plot the sphere function's mesh for better plots
m = Mesher(func=fct_3, limits=[(-20, 5), (-20, 5)], levels=20, delta=0.2)
# Adjust figure limits
d = Designer(limits=[(-20, 5), (-20, 5), (-1.1, 0.1)],
             label=['x-axis', 'y-axis', 'z-axis'])

options = {'c1': 1.2, 'c2': 0.3, 'w': 0.9}
optimizer = ps.single.GlobalBestPSO(n_particles=25,
                                    dimensions=2,
                                    options=options,
                                    init_pos=np.random.random((25, 2)) - 20)
optimizer.optimize(fct_3, iters=300)
# Plot the cost
#plot_cost_history(optimizer.cost_history)
#plt.show()
#plot_contour(pos_history=optimizer.pos_history, mesher=m, designer=d, mark=(0,1.39))
print("hi")