Exemplo n.º 1
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)
Exemplo n.º 2
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
Exemplo n.º 3
0
def plot_particle_position(pos_history, gbest, animation_path, limits, label):
    designer = Designer(limits=limits, label=label)

    animator = Animator(repeat=False, interval=200)

    rc('animation', html='html5')
    anim = plot_contour(pos_history=pos_history,
                        designer=designer,
                        animator=animator,
                        mark=gbest)
    anim.save(animation_path)
    plt.close('all')
Exemplo n.º 4
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()
Exemplo n.º 5
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
Exemplo n.º 6
0
                d] == 'max_depth':  #d==0 means max_depth, which is normalized
            y_plot[d, i * n_particles:(i + 1) * n_particles] = a[:, d] * 7 + 2
        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")
Exemplo n.º 7
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)

plt.show()
Exemplo n.º 8
0
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
animation3d = plot_surface(pos_history=pos_history_3d, # Use the cost_history we computed
                           mesher=m, designer=d,       # Customizations
                           mark=(0,0,0))               # Mark minima

# Enables us to view it in a Jupyter notebook
animation3d.save('plot1.gif', writer='imagemagick', fps=10)
Image(url='plot1.gif')
Exemplo n.º 9
0
                                    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()

# # Plot the cost
# plot_cost_history(optimizer.cost_history)
    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")
pos_history_3d = m.compute_history_3d(optimizer.pos_history)  # preprocessing
animation3d = plot_surface(pos_history=pos_history_3d,
                           mesher=m,