package org.cloudbus.cloudsim.codes.pso;

/**
 * ClassName PSO
 * Description
 * Create by HW
 * Date 2021/8/13 10:15
 */
public class PSO {

    /**
     * 粒子群
     */
    Particle[] pars;
    double global_best;//全局最优解
    int pcount;//粒子的数量
    /**
     * 粒子群初始化
     * @param n 粒子的数量
     */
    public void init(int n) {
        pcount = n;
        global_best = -1e6;
        int index = -1;
        pars = new Particle[pcount];
        //类的静态成员的初始化
        Particle.c1 = 2;
        Particle.c2 = 2;
        Particle.w = 0.8;
        Particle.dims = 3;
        for (int i = 0; i < pcount; ++i) {
            pars[i] = new Particle();
            pars[i].initial(3);
            pars[i].evaluate();
            if (global_best < pars[i].fitness) {
                global_best = pars[i].fitness;
                index = i;
            }
        }
        Particle.gbest = new double[Particle.dims];
        for (int i = 0; i < 3; ++i) {
            Particle.gbest[i] = pars[index].pos[i];
        }
    }
    /**
     * 粒子群的运行
     */
    public void run() {
        int runtimes = 500;
        int index;
        while (runtimes > 0) {
            index = -1;
            //每个粒子更新位置和适应值
            for (int i = 0; i < pcount; ++i) {
                pars[i].updatev();
                pars[i].evaluate();
                if (global_best < pars[i].fitness) {
                    global_best = pars[i].fitness;
                    index = i;
                }
            }
            //发现更好的解
            if (index != -1) {
                for (int i = 0; i < 3; ++i) {
                    Particle.gbest[i] = pars[index].pos[i];
                }
            }
            --runtimes;
        }
    }
    /**
     * 显示程序求解结果
     */
    public void showresult() {
        System.out.println("程序求得的最优解是" + global_best);
        System.out.println("每一维的值是");
        for (int i = 0; i < Particle.dims; ++i) {
            System.out.println(Particle.gbest[i]);
        }
    }
}
