Esempio n. 1
0
    def contour(self, **kwargs):
        from pyswarms.utils import plotters
        plotters.plot_contour(
            pos_history=self.samples.points,
            **kwargs
        )

        self.output.to_figure(structure=None, auto_filename="contour")
        self.close()
Esempio n. 2
0
    def contour(self, **kwargs):

        plotters.plot_contour(
            pos_history=self.samples.points,
            **kwargs
        )

        self.output.to_figure(structure=None, auto_filename="contour")
        self.mat_plot_1d.figure.close()
Esempio n. 3
0
    def plotPositionHistory(self, optimizer, xLimits, yLimits, filename, xLabel, yLabel):

        '''
        :param optimizer: optimizer object returned in the application/definition of PSO
        :param xLimits: numpy array (minLimit, maxLimit) of x Axis
        :param yLimits: numpy array (minLimit, maxLimit) of y Axis
        :param filename: name of filename returned by plot_contour (html gif)
        :param xLabel: name of X axis
        :param yLabel: name of Y axis
        '''

        try:

            ##code ref: https://www.tutorialfor.com/questions-83899.htm
            d = Designer(limits=[xLimits, yLimits], label=[xLabel, yLabel])
            pos = []
            for i in range(config.ITERATIONS):
                pos.append(optimizer.pos_history[i][:, 0:2])
            animation = plot_contour(pos_history=pos,
                                     designer=d)

            plt.close(animation._fig)
            html_file = animation.to_jshtml()
            with open(filename, 'w') as f:
                f.write(html_file)

        except:
            raise CustomError.ErrorCreationModel(config.ERROR_ON_PLOTTING)
Esempio n. 4
0
def plotPositionHistory(optimizer, xLimits, yLimits, filename, xLabel, yLabel):
    '''

    :param optimizer: optimizer object returned in the application/definition of PSO
    :param xLimits: numpy array (minLimit, maxLimit) of x Axis
    :param yLimits: numpy array (minLimit, maxLimit) of y Axis
    :param filename: name of filename returned by plot_contour (html gif)
    :param xLabel: name of X axis
    :param yLabel: name of Y axis
    '''

    try:

        d = Designer(limits=[xLimits, yLimits], label=[xLabel, yLabel])
        animation = plot_contour(pos_history=optimizer.pos_history, designer=d)

        animation.save(filename, writer='ffmpeg', fps=10)
        Image(url=filename)

        plt.show()
    except:
        raise
#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()

#Same for a more interesting function Schaffer N.2 Objective function
optimizer2 = ps.single.GlobalBestPSO(n_particles=50, dimensions=2, options=opt)
optimizer2.optimize(fx.schaffer2, iters=100)

hist2 = optimizer2.pos_history
Esempio n. 6
0
def test_plot_contour_return_type(pos_history):
    """Tests if the animation function returns the expected type"""
    assert isinstance(plot_contour(pos_history), FuncAnimation)
Esempio n. 7
0
        else:
            y_plot[d, i * n_particles:(i + 1) * n_particles] = a[:, d]
for nd in range(0, n_dimensions):
    if parameter_name[nd] == 'max_depth':
        plt.scatter(x_plot[nd, :], (y_plot[nd, :] * 7 + 2))
    else:
        plt.scatter(x_plot[nd, :], y_plot[nd, :])
    plt.title(parameter_name[nd])
    plt.savefig("{}.png".format(parameter_name[nd]))
    plt.close()
    print("{0} saved as {1}.png".format(parameter_name[nd],
                                        parameter_name[nd]))

d = Designer(limits=[(0, 50), (0, 5), (0, 1)], label=param_name)
#FFwriter = animation.FFMpegWriter()
anim = plot_contour(pos_history=optimizer.pos_history, designer=d)
anim.save('animation.html', fps=1)
#anim.save('animation.gif', writer='imagemagick', fps=1)
print("animation saved")

if (args.heatmap):
    makeHeatMap("allIter", 0, n_iters, parameter_name, param_max_list,
                optimizer.pos_history)
    makeHeatMap("FirstTenIter", 0, 10, parameter_name, param_max_list,
                optimizer.pos_history)
    makeHeatMap("LastTenIter", n_iters - 10, n_iters, parameter_name,
                param_max_list, optimizer.pos_history)
f_result = open("result.csv", "w")
keys = "{0},{1},{2},{3}".format("c1", "c2", "w", "cost")
for pos_name in param_name:
    keys = keys + ",{}".format(pos_name)
Esempio n. 8
0
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)

plt.show()
Esempio n. 9
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)
Esempio n. 10
0
# 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
from pyswarms.utils.plotters.formatters import Designer
d = Designer(limits=[(-1,1), (-1,1), (-0.1,1)], label=['x-axis', 'y-axis', 'z-axis'])

# Make animation