Basic PSO Algorithm Implementation (Java)

Source: Internet
Author: User
Tags cos pow

I. Algorithmic flow

STEP1: Initializes a group of particles (50 particles), including the immediate position and velocity;

STEP2: Calculate the fitness of each particle fitness;

STEP3: For each particle, its fitness is compared with the best position (local) Pbest, if it is better, it will be the best position in the current pbest;

STEP4: For each particle, it will adapt its value to the best position of the population gbest to compare, if it is better, it is the best position gbest;

STEP5: Update all particle locations and velocities;

STEP6: Turn STEP2 If the end condition is not reached.

Two. Experiment Setup

(1) Number of particles particle_num=20;

(2) Number of iterations n=50;

(3) inertia factor w=1.4;

(4) c1=c2=2;

(5) Maximum speed vmax=2.

Three. Experiment Notes

PSO Wiki: https://en.wikipedia.org/wiki/Particle_swarm_optimization

Objective function: Ackley ' s function in Https://en.wikipedia.org/wiki/Test_functions_for_optimization, Sphere function, and Rosenbrock function (both are minimum values)

Full code, see my GITHUB:HTTPS://GITHUB.COM/WQPOD2G/PSO.

Four. Java code

1.particle class

 PackageNju.iip;ImportJava.util.Random;/*** Particle class *@authormrpod2g **/ Public classParticle {//Number of dimensions     Public  intDimension = 2; //the position of the particle     Public Double[] X =New Double[Dimension]; //Local Best Location     Public Double[] Pbest =New Double[Dimension]; //Velocity of particles     Public Double[] V =New Double[Dimension]; //Max speed     Public DoubleVmax = 2; //Adaptive Values     Public DoubleFitness; /*** Calculate the adaptive value according to the current position *@returnnewfitness*/     Public Doublecalculatefitness () {//1.Ackley ' s function://Double newfitness = -20*math.pow (MATH.E, ( -0.2*math.sqrt (0.5* (x[0]*x[0]+x[1]*x[1))))-math.pow (MATH.E, (0.5* (            Math.Cos (2*math.pi*x[0]) +math.cos (2*math.pi*x[1]))) +math.e+20; //2.Sphere function//double newfitness = x[0]*x[0]+x[1]*x[1]; //3.Rosenbrock function        Doublenewfitness = 100* (Math.pow ((x[1]-x[0]*x[0)), 2) +math.pow ((x[0]-1), 2); returnnewfitness; }            /*** Initialize your location and pbest*/     Public voidInitialx () { for(inti=0;i<dimension;i++) {X[i]=NewRandom (). Nextint (100); Pbest[i]=X[i]; }    }        /*** Initialize your own speed*/     Public voidInitialv () { for(inti=0;i<dimension;i++) {            DoubleTMP =NewRandom (). nextdouble ();//Randomly generates a random fraction of a 0~1V[i] = tmp*4+ (-2); }    }    }

2.PSO Algorithm Implementation process

 PackageNju.iip;Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.Random;/*** PSO Algorithm Implementation *@authormrpod2g **/ Public classPSO {Private Static Double[] gbest;//Global Optimal location        Private Static Doublegbest_fitness = Double.max_value;//Fitness of the global optimal position        Private Static intParticle_num = 20;//Number of particles        Private Static intN = 50;//Number of iterations        Private Static intC1,C2 = 2; Private Static Doublew = 1.4;//Inertia factor        Private StaticList<particle> particles =NewArraylist<particle> ();//particle swarm        /*** Initialization of all particles*/     Public Static voidInitialparticles () { for(inti=0;i<particle_num;i++) {particle particle=Newparticle ();            Particle.initialx ();            Particle.initialv (); Particle.fitness=particle.calculatefitness ();        Particles.add (particle); }    }        /*** Update Gbest*/     Public Static voidupdategbest () {DoubleFitness =Double.max_value; intindex = 0;  for(inti=0;i<particle_num;i++) {            if(Particles.get (i) .fitness<Fitness) {Index=i; Fitness=Particles.get (i). Fitness; }        }        if(fitness<gbest_fitness) {gbest=particles.get (Index). Pbest.clone (); Gbest_fitness=Fitness; }    }        /*** With the speed of each new particle*/     Public Static voidUpdatev () { for(particle particle:particles) { for(inti=0;i<particle.dimension;i++) {                Doublev = w*particle. V[i]+c1*rand () * (particle.pbest[i]-particle. X[i]) +c2*rand () * (gbest[i]-particle.                X[i]); if(v>particle. Vmax) v=particle.                Vmax; Else if(v<-particle. Vmax) v= -particle.                Vmax; Particle. V[i]= V;//Update VI            }        }    }        /*** Update the position and pbest of each particle*/     Public Static voidUpdatex () { for(particle particle:particles) { for(inti=0;i<particle.dimension;i++) {particle. X[i]= particle. X[i] +particle.            V[i]; }            DoubleNewfitness = Particle.calculatefitness ();//New Adaptive Values//if the new adaptation value is smaller than the original, the new fitness and Pbest            if(newfitness<particle.fitness) {particle.pbest=particle.                X.clone (); Particle.fitness=newfitness; }        }    }        /*** Algorithm main flow*/     Public Static voidprocess () {intn = 0;        Initialparticles ();        Updategbest ();  while(n++<N) {Updatev ();            Updatex ();            Updategbest (); SYSTEM.OUT.PRINTLN (n+ ". Current gbest: (" +gbest[0]+ "," +gbest[1]+ ") fitness=" +gbest_fitness); }    }        /*** Returns a random number of 0~1 *@return     */     Public Static Doublerand () {return NewRandom (). nextdouble (); }         Public Static voidMain (string[] args) {process (); }}

Basic PSO Algorithm Implementation (Java)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.