# Particle Swarm Optimization in C++

The social behavior of fish schools and flocks of birds inspired the metaheuristic optimization technique known as Particle Swarm Optimization (PSO). Since Kennedy and Eberhart presented it in 1995, it has grown in prominence because of how easily and successfully it can solve a variety of optimization issues. In this post, we'll examine the fundamentals of PSO and its C++ implementation.

## Particle Swarm Optimization

PSO is a fundamentally population-based optimization method in which the ideal solution is found by a collection of possible solutions referred to as particles. These particles move around the search space. Every particle stays in the search space. It retains its location and velocity, symbolizing a possible solution to the optimization issue.

Particle behavior depends on two factors. The best-known position within the swarm is the global best, and the particle's own best-known position is the personal best. The algorithm updates these locations repeatedly as it goes along. Particles are led in their motion. They vary their velocities in relation to their past velocities and their distance from the personal best and the global best.

## Key Components of PSO

Several components of PSO are as follows:

• Particles: Every particle in the swarm is a possible way to solve the optimization issue. Each particle is usually represented as a vector of real values in a multidimensional search space.
• Position and Velocity: Each particle tracks its position, velocity, and direction inside the search space at all times. Vectors indicate location and velocity.
• Fitness Function: A particle's location inside the search space is assessed for quality using a fitness function. It measures the degree to which a solution approaches the ideal answer. The fitness function is particular to the situation at hand and has to consider the optimization problem.
• Personal Best: We track the greatest position ever held by each particle. The word "personal best" refers to the particle's greatest location found thus far in the search space.
• The Best in the world (gbest). The swarm follows any particle that finds the optimal place on a global scale. It's the best thing the swarm has collectively figured out thus far.
• Weight of Inertia: The algorithm's capacity for exploration and exploitation is modified by the inertia weight parameter. It regulates how the particle's prior velocity affects its current velocity.

## The PSO Algorithm's steps

The PSO algorithm takes the following steps:

• Initialization: Randomly spread out the particle positions and velocities over the search space. The particles' initial placements ought to be returned to their ideal locations.
• Assessment: Use the fitness function to find out how fit each particle is at its current position.
• Update Personal Best: When the particle's current position has a greater fitness value, refresh the particle's optimal location.
• Update Global Best: Find the particle with the highest fitness value among all the particles. After that, modify the global best position based on that discovery.
• Update Velocities: Use the particle's global best location and historical velocity to update the velocity using the position that works best for you.
• Update locations: By using the velocities of the particles as a reference. Revisit their whereabouts.
• Steps 2–6 should be repeated until a termination requirement is satisfied, such as reaching a maximum number of iterations or coming up with a workable solution.

## PSO Implementation in C++

We must define classes or structures to represent particles and the swarm in order to implement PSO in C++ Functions to begin the swarm. Assess fitness. Update locations and velocities. Choosing the optimal solutions is also required. Here is a simple C++

`#include <iostream>#include <vector>#include <cmath>#include <cstdlib>#include <ctime>using namespace std;struct Prtcl {    vector<double> pos;    vector<double> vel;    vector<double> pbest;    double fit;    Prtcl(int dim) {        pos.resize(dim);        vel.resize(dim);        pbest.resize(dim);    }};class PSO {private:    int swarmSz;    int dim;    int maxIters;    double cogCoeff, socCoeff;    vector<Prtcl> swarm;    vector<double> gbest;public:    PSO(int swarmSz, int dim, int maxIters, double cogCoeff, double socCoeff)        : swarmSz(swarmSz), dim(dim), maxIters(maxIters), cogCoeff(cogCoeff), socCoeff(socCoeff) {}    double computeFitness(vector<double>& pos) {        double sum = 0.0;        for (double x : pos) {            sum += x * x;        }        return sum;    }    void initSwarm() {        swarm.clear();        for (int i = 0; i < swarmSz; ++i) {            Prtcl prtcl(dim);            for (int j = 0; j < dim; ++j) {                prtcl.pos[j] = (rand() % 200 - 100) / 10.0;                prtcl.vel[j] = 0.0;                prtcl.pbest[j] = prtcl.pos[j];            }            prtcl.fit = computeFitness(prtcl.pos);            swarm.push_back(prtcl);        }    }    void updatePrtcls() {        for (Prtcl& prtcl : swarm) {            for (int j = 0; j < dim; ++j) {                double r1 = ((double) rand() / RAND_MAX);                double r2 = ((double) rand() / RAND_MAX);                prtcl.vel[j] = prtcl.vel[j] +                    cogCoeff * r1 * (prtcl.pbest[j] - prtcl.pos[j]) +                    socCoeff * r2 * (gbest[j] - prtcl.pos[j]);                prtcl.pos[j] = prtcl.pos[j] + prtcl.vel[j];            }            double newFit = computeFitness(prtcl.pos);            if (newFit < prtcl.fit) {                prtcl.fit = newFit;                prtcl.pbest = prtcl.pos;            }            if (newFit < computeFitness(gbest)) {                gbest = prtcl.pos;            }        }    }    vector<double> execute() {        initSwarm();        gbest = swarm[0].pos;        for (int iter = 0; iter < maxIters; ++iter) {            updatePrtcls();        }        return gbest;    }};int main() {    srand(time(NULL));    int swarmSz = 35;    int dim = 12;    int maxIters = 1500;    double cogCoeff = 1.8;    double socCoeff = 2.1;    PSO pso(swarmSz, dim, maxIters, cogCoeff, socCoeff);    vector<double> solution = pso.execute();    cout << "Optimal solution identified:" << endl;    for (double x : solution) {        cout << x << " ";    }    cout << endl;    return 0;}`

Output: