Example #1
0
    def cost_history(self, **kwargs):
        from pyswarms.utils import plotters
        plotters.plot_cost_history(
            cost_history=self.samples.log_posterior_list,
            **kwargs
        )

        self.output.to_figure(structure=None, auto_filename="cost_history")
        self.close()
Example #2
0
    def cost_history(self, **kwargs):

        plotters.plot_cost_history(
            cost_history=self.samples.log_posterior_list,
            **kwargs
        )

        self.output.to_figure(structure=None, auto_filename="cost_history")
        self.mat_plot_1d.figure.close()
Example #3
0
 def swarm(self):
     circuit_swarm = GlobalBestPSO(n_particles=self.particles,
                                   dimensions=self.dimensions,
                                   options=self.options,
                                   bounds=self.bounds)
     cost, pos = circuit_swarm.optimize(self.swarm_cost,
                                        iters=self.loops,
                                        n_processes=self.processes)
     plot_cost_history(circuit_swarm.cost_history)
     plt.show()
     return cost, pos
Example #4
0
def plotCostHistory(optimizer):
    '''

    :param optimizer: optimizer object returned in the application/definition of PSO
    '''

    try:

        plot_cost_history(cost_history=optimizer.cost_history)

        plt.show()
    except:
        raise
    def plotCostHistory(self, optimizer):
        '''
        :param optimizer: optimizer object returned in the application/definition of PSO
        '''

        try:

            plot_cost_history(cost_history=optimizer.cost_history)

            plt.show()

        except:
            raise CustomError.ErrorCreationModel(config.ERROR_ON_PLOTTING)
Example #6
0
def PSO():
    # Set-up hyperparameters
    options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
    # Call instance of PSO
    optimizer = ps.single.GlobalBestPSO(
        n_particles=15,
        dimensions=len(params),
        options=options,
        bounds=([params[i][1] for i in range(len(params))],
                [params[i][2] for i in range(len(params))]))
    # Perform optimization
    best_cost, best_pos = optimizer.optimize(obj_func_many, iters=1000)
    plot_cost_history(optimizer.cost_history)
    plt.show()
Example #7
0
def pso(c1,
        c2,
        w,
        k=2,
        p=2,
        n_particles=100,
        epochs=100,
        mode="gbest",
        verbose=0,
        visualize=0):
    options = {'c1': c1, 'c2': c2, 'w': w}

    # bound
    max_value = 1.0 * np.ones(DIMENSIONS)
    min_value = -1.0 * np.ones(DIMENSIONS)
    bounds = (min_value, max_value)

    # create pso optimizer
    if mode == "gbest":
        from pyswarms.single.global_best import GlobalBestPSO
        optimizer = GlobalBestPSO(n_particles=n_particles,
                                  dimensions=DIMENSIONS,
                                  options=options,
                                  bounds=bounds)
    elif mode == "lbest":
        from pyswarms.single.local_best import LocalBestPSO
        options.update({"k": k, "p": p})
        optimizer = LocalBestPSO(n_particles=n_particles,
                                 dimensions=DIMENSIONS,
                                 options=options,
                                 bounds=bounds)
    else:
        raise NotImplementedError("Mode %s not support." % mode)

    # optimize
    cost, params = optimizer.optimize(f, epochs, verbose=verbose)

    if verbose:
        print("Accuracy: ", (predict(X_test, params) == Y_test).mean())

    if visualize:
        import matplotlib.pyplot as plt
        from pyswarms.utils.plotters import plot_cost_history
        plot_cost_history(cost_history=optimizer.cost_history)
        plt.show()

    # for bayesian optimization
    return -cost
Example #8
0
    def runOptimization(self):
        ''' Run the Optimization and show convergence history '''
        if self.parallel:
            import ray
            ray.init()
            cost, pos = self.optimizer.optimize(self._computeCostFunctionValues_Parallel, iters=self.nIterations)
            ray.shutdown()
        
        else:                
            cost, pos = self.optimizer.optimize(self._computeCostFunctionValues_SingleThreaded, iters=self.nIterations)

        self._createContinuationFile(self.optimizer.swarm.position, pos, cost)

        if self.showConvergence:
            print("Showing optimization convergence plot")

            # Show optimization history
            from pyswarms.utils.plotters import plot_cost_history
            plot_cost_history(self.optimizer.cost_history)
            plt.show()

        return cost, pos
Example #9
0
def particleswarm(objfcn,
                  dimensions,
                  args={},
                  use_bnds=True,
                  bounds=(None, None),
                  iters=100,
                  n_particles=10,
                  ftol=-np.inf,
                  options={
                      'c1': 0.5,
                      'c2': 0.3,
                      'w': 0.9
                  },
                  verbosity=1,
                  **kwargs):
    """
    Global minimization function using particle swarms (wrapper around pyswarms.single.GlobalBestPSO)
    
    Args:
        :objfcn:
            | objective function
            | Should output a vector with cost values for each of the particles.
        :dimensions: 
            | Number of parameter values for the objective function. 
        :args:
            | Dict with objfcn input parameters (except the to be optimized x)
        :use_bnd:
            | True, optional
            | False: omits bounds and defaults to regular minimize function.
        :bounds:
            | (lower, upper), optional
            | Tuple of lists or dicts (x0_keys is None) of lower and upper bounds 
              for each of the parameters values.
        :iters:
            | 100, optional
            | Number of swarm iterations
        :n_particles:
            | 10, optional
            | Number of particles in swarm
        :ftol:
            | -np.inf, optional
            | Relative error in objective_func(best_pos) acceptable for
            | convergence. Default is :code:`-np.inf`
        options:
            | {'c1': 0.5, 'c2': 0.3, 'w':0.9}, optional
            | dict with keys {'c1', 'c2', 'w'}
            | A dictionary containing the parameters for the specific
            | optimization technique.
            |  - 'c1' : float, cognitive parameter
            |  - 'c2' : float, social parameter
            |  - 'w' : float, inertia parameter
        :verbosity:
            | 1, optional
            | If > 0: plot the cost history (see pyswarms's plot_cost_history function)
        :kwargs: 
            | allows input for other type of arguments for GlobalBestPSO
         
    Note:
        For more info on other input arguments, see 'ps.single.GlobalBestPSO?'
         
    Returns:
        :res: 
            | dict with output of minimization:
            | keys():
            |   - 'x_final': final solution x
            |   - 'cost': final function value of obj_fcn()
            |   - and some of the input arguments characterizing the 
            |       minimization, such as n_particles, bounds, ftol, options, optimizer.

    Reference:
        1. pyswarms documentation: https://pyswarms.readthedocs.io/
    """

    if (bounds[0] is None) & (bounds[1] is None):
        use_bnds = False
    if use_bnds == True:
        kwargs['bounds'] = bounds

    optimizer = ps.single.GlobalBestPSO(n_particles=n_particles,
                                        dimensions=dimensions,
                                        options=options,
                                        ftol=ftol,
                                        **kwargs)

    cost, pos = optimizer.optimize(objfcn, iters=iters, **args)

    if verbosity > 0:
        # Plot cost history:
        plot_cost_history(cost_history=optimizer.cost_history)

    # create output dictionary:
    res = {
        'x_final': pos,
        'cost': cost,
        'iters': iters,
        'n_particles': n_particles,
        'bounds': bounds,
        'ftol': ftol,
        'options': options,
        'optimizer': optimizer
    }

    return res
Example #10
0
 def plotCost(self):
     plot_cost_history(cost_history=self.optimize.cost_history)
     plt.show()
# #Main
# %%time
# # Initialize swarm
# options = {'c1': 0.5, 'c2': 0.3, 'w':0.9}
# in_dimen = env.observation_space.shape[0] 
# out_dimen = env.action_space.shape[0]
# # Call instance of PSO0
# dimensions = (in_dimen * 20) + 20 + (20*20) +20 +(20*20) + 20 + (20 * out_dimen) + out_dimen
# optimizer = ps.single.GlobalBestPSO(n_particles=100, dimensions=dimensions, options=options)
# 
# # Perform optimization
# cost, pos = optimizer.optimize(f, iters=500)

from pyswarms.utils.plotters import plot_cost_history, plot_contour, plot_surface
import matplotlib.pyplot as plt
plot_cost_history(optimizer.cost_history)
plt.show()

0observation = env.reset()
totalReward = 0
for step in range(1000):
              env.render()
              action = forward_prop(pos,observation)
              observation, reward, done, info = env.step(action)
              totalReward += reward  
              print(totalReward)
              if done:
                observation = env.reset()
                break
env.close()
show_video()
Example #12
0
    def save(self,
             title=None,
             plot_fit=None,
             target=None,
             band=None,
             param=None,
             weight=None,
             cost_history=None,
             cost_history_particle=None,
             pso_param_history=None):
        if self.myid != 0:
            return

        if plot_fit is True:
            if title is not None:
                fout = 'BAND.' + title.strip() + '.pdf'
            else:
                fout = 'BAND.pdf'
            self.plot_fit(title=title.strip(), fout=fout)

        if target is True:
            if title is not None:
                tfileoutnm = 'band_structure_DFT.' + title.strip(
                ) + '.dat' + ' ' * (
                    132 - len('band_structure_DFT.' + title.strip() + '.dat'))
            else:
                tfileoutnm = 'band_structure_DFT.dat' + ' ' * (
                    132 - len('band_structure_DFT.dat'))
            pyfit.print_target(self.pinpt, self.pkpts, self.edft, self.pwght,
                               self.pgeom, tfileoutnm)

        if band is True:
            if title is not None:
                suffix = '.' + title.strip() + ' ' * (132 -
                                                      len(title.strip()) + 1)
            else:
                suffix = ' ' * 132
            use_overlap = self.ppram.flag_use_overlap
            pyfit.print_etba(self.pinpt, self.pkpts, self.etba, self.edft,
                             self.pwght, self.pgeom, suffix, use_overlap)

        if param is True:
            if title is not None:
                param_out = 'PARAM_FIT.new.' + title.strip() + '.dat'
            else:
                param_out = 'PARAM_FIT.new.dat'
            self.print_param(param_out=param_out)

        if weight is True:
            if title is not None:
                weight_out = 'WEIGHT.' + title.strip() + '.dat'
            else:
                weight_out = 'WEIGHT.dat'
            self.print_weight(weight_out=weight_out)

        if cost_history is True:
            if title is not None:
                cost_out_dat = 'COST_HISTORY.' + title.strip() + '.dat'
                cost_out_pdf = 'COST_HISTORY.' + title.strip() + '.pdf'
            else:
                cost_out_dat = 'COST_HISTORY.dat'
                cost_out_pdf = 'COST_HISTORY.pdf'
            if self.ppram.niter == 0:
                niter = self.pinpt.miter
            else:
                niter = self.ppram.niter

            plot_cost_history(self.cost_history[:niter], title=title.strip())
            plt.savefig(cost_out_pdf, bbox_inches='tight', pad_inches=0)

            cost_out = open(cost_out_dat, 'w+')
            for ii in range(niter):
                cost_out.write(" %d    %.9f \n" % (ii, self.cost_history[ii]))
            cost_out.close()

        if cost_history_particle is True:
            if title is not None:
                cost_out_dat = 'COST_HISTORY_particles.' + title.strip(
                ) + '.dat'
                cost_out_pdf = 'COST_HISTORY_particles.' + title.strip(
                ) + '.pdf'
            else:
                cost_out_dat = 'COST_HISTORY_particles.dat'
                cost_out_pdf = 'COST_HISTORY_particles.pdf'
            if self.ppram.niter == 0:
                niter = self.pinpt.miter
            else:
                niter = self.ppram.niter

            bestn = int(self.n_particles * 0.2)
            if (bestn > 5): bestn = 5
            self.plot_pso_cost_history(title=title.strip(),
                                       fout=cost_out_pdf,
                                       bestn=bestn)

            cost_out = open(cost_out_dat, 'w+')
            for jj in range(self.n_particles):
                cost_out.write("# Particle : %d  \n" % (jj))
                for ii in range(niter):
                    cost_out.write("%d  %.9f \n" %
                                   (ii, self.cost_history_particle[ii, jj]))
                cost_out.write("  \n")
            cost_out.close()

        if pso_param_history is True:
            if title is not None:
                param_out_dat = 'PARAM_best_particles.' + title.strip(
                ) + '.dat'
                param_out_pdf = 'PARAM_best_particles.' + title.strip(
                ) + '.pdf'
            else:
                param_out_dat = 'PARAM_best_particles.dat'
                param_out_pdf = 'PARAM_best_particles.pdf'
            if self.ppram.niter == 0:
                niter = self.pinpt.miter
            else:
                niter = self.ppram.niter

            bestn_ = int(self.n_particles * 0.2)
            if (bestn_ > 5):
                bestn = 5
            else:
                bestn = bestn_

            self.plot_pso_pbest(title=title.strip(),
                                fout=param_out_pdf,
                                bestn=bestn)

            best_nparticle_index = self.cost_history_particle[
                -1, :].argsort()[:bestn_]
            param_out = open(param_out_dat, 'w+')
            for i in range(bestn_):
                ii = best_nparticle_index[i]
                cost = self.cost_history_particle[-1, ii]
                param_out.write(
                    "# Best Particle : rank=%d , ID=%d, COST=%.9f  \n" %
                    (i, ii, cost))
                param_set = self.ppram.param
                for ip in range(self.ppram.nparam_free):
                    param_set[self.ppram.iparam_free[ip] -
                              1] = self.ppram.pso_pbest_history[-1, ii, ip]
                for j in range(self.ppram.nparam):
                    pj = self.select_param(param_set, j)
                    param_out.write("%5d  %20.9f   # %5d %20.9f\n" %
                                    (j + 1, pj, ii, cost))
                param_out.write("  \n")
            param_out.close()
Example #13
0
def test_plot_cost_history_error(bad_values):
    """Tests if plot_cost_history() raises an error given bad values"""
    with pytest.raises(TypeError):
        plot_cost_history(bad_values)
Example #14
0
def test_plot_cost_history_return_type(trained_optimizer, history):
    """Tests if plot_cost_history() returns a SubplotBase instance"""
    opt_params = vars(trained_optimizer)
    plot = plot_cost_history(opt_params[history])
    assert isinstance(plot, SubplotBase)
Example #15
0
SL, TP = [10, 10, 10, 10] , [20, 20, 20, 20]

Volumen= [200, 200, 200, 200]

decision = fn.f_decisiones(Operacion, SL,TP,Volumen)

backtest_train = fn.f_backtest(escenario,decision,capital_inicial)

miniback=fn.f_minimizar(backtest_train)

lb= [3,3,1,1,8,8,3,3,100000,100000,50000,50000]

ub= [10,10,3,3,20,20,6,6,500000,500000,200000,200000]

cost, df_decisiones_optimo, graph= fn.f_optimizacion(escenario,np.array(lb),np.array(ub),Operacion)

graph = plot_cost_history(cost_history=graph.cost_history)

df_backtest_optimo_train = fn.f_backtest(escenario, df_decisiones_optimo,capital_inicial)

df_escenarios_test =fn.f_escenarios_test(escenario)

df_backtest_test = fn.f_backtest(df_escenarios_test,decision,capital_inicial)

df_backtest_optimo_test= fn.f_backtest(df_escenarios_test, df_decisiones_optimo,capital_inicial)

vs.f_graph_train(backtest_train,df_backtest_optimo_train)

vs.f_graph_test(df_backtest_test,df_backtest_optimo_test)

 def plotCost(self):
     if self.isFit:
         plot_cost_history(cost_history=self.cost_history)
         plt.show()
     else:
         print('\nModels is not fitted\n')