100% found this document useful (1 vote)
57 views3 pages

MATLAB PSO Code for Optimization

The document provides MATLAB code for particle swarm optimization (PSO) to solve constrained optimization problems. The code includes [1] an objective function and constraint definitions, [2] PSO initialization and algorithm code, and [3] a main program to run multiple PSO trials. The code initializes particle positions and velocities randomly, then iteratively updates each particle's position based on its own experience and the swarm's experience to minimize the objective function while satisfying constraints. The best solution found over multiple runs is reported along with the number of iterations required for convergence.

Uploaded by

Korbi Amira
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
57 views3 pages

MATLAB PSO Code for Optimization

The document provides MATLAB code for particle swarm optimization (PSO) to solve constrained optimization problems. The code includes [1] an objective function and constraint definitions, [2] PSO initialization and algorithm code, and [3] a main program to run multiple PSO trials. The code initializes particle positions and velocities randomly, then iteratively updates each particle's position based on its own experience and the swarm's experience to minimize the objective function while satisfying constraints. The best solution found over multiple runs is reported along with the number of iterations required for convergence.

Uploaded by

Korbi Amira
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ResearchGate, March 2016

Codes in MATLAB for Particle Swarm Optimization

Mahamad Nabab Alam, Research Scholar

Particle swarm optimization (PSO) codes in MATLAB suitable for solving constrained optimization problem

Save the following codes in MATLAB script file (*.m) and save as ofun.m.
----------------------------------------------------------------------------------------------------------------------------------start
function f=ofun(x)

% objective function (minimization)


of=10*(x(1)-1)^2+20*(x(2)-2)^2+30*(x(3)-3)^2;

% constraints (all constraints must be converted into <=0 type)


% if there is no constraints then comments all c0 lines below

c0=[];
c0(1)=x(1)+x(2)+x(3)-5; % <=0 type constraints
c0(2)=x(1)^2+2*x(2)-x(3); % <=0 type constraints

% defining penalty for each constraint


for i=1:length(c0)
if c0(i)>0
c(i)=1;
else
c(i)=0;
end
end
penalty=10000; % penalty on each constraint violation
f=of+penalty*sum(c); % fitness function
-----------------------------------------------------------------------------------------------------------------------------------end

Save the following main program codes in MATLAB script file (*.m) as run_pso.m (any name can be used) and
run.

----------------------------------------------------------------------------------------------------------------------------------start
tic
clc
clear all
close all
rng default

LB=[0 0 0]; %lower bounds of variables


UB=[10 10 10]; %upper bounds of variables

% pso parameters values


m=3; % number of variables
n=100; % population size
wmax=0.9; % inertia weight
wmin=0.4; % inertia weight
c1=2; % acceleration factor
c2=2; % acceleration factor

% pso main program----------------------------------------------------start


maxite=1000; % set maximum number of iteration

1
ResearchGate, March 2016

maxrun=10; % set maximum number of runs need to be


for run=1:maxrun
run
% pso initialization----------------------------------------------start
for i=1:n
for j=1:m
x0(i,j)=round(LB(j)+rand()*(UB(j)-LB(j)));
end
end
x=x0; % initial population
v=0.1*x0; % initial velocity
for i=1:n
f0(i,1)=ofun(x0(i,:));
end
[fmin0,index0]=min(f0);
pbest=x0; % initial pbest
gbest=x0(index0,:); % initial gbest
% pso initialization------------------------------------------------end

% pso algorithm---------------------------------------------------start
ite=1;
tolerance=1;
while ite<=maxite && tolerance>10^-12

w=wmax-(wmax-wmin)*ite/maxite; % update inertial weight

% pso velocity updates


for i=1:n
for j=1:m
v(i,j)=w*v(i,j)+c1*rand()*(pbest(i,j)-x(i,j))...
+c2*rand()*(gbest(1,j)-x(i,j));
end
end

% pso position update


for i=1:n
for j=1:m
x(i,j)=x(i,j)+v(i,j);
end
end

% handling boundary violations


for i=1:n
for j=1:m
if x(i,j)<LB(j)
x(i,j)=LB(j);
elseif x(i,j)>UB(j)
x(i,j)=UB(j);
end
end
end

% evaluating fitness
for i=1:n
f(i,1)=ofun(x(i,:));
end

% updating pbest and fitness


for i=1:n
if f(i,1)<f0(i,1)

2
ResearchGate, March 2016

pbest(i,:)=x(i,:);
f0(i,1)=f(i,1);
end
end

[fmin,index]=min(f0); % finding out the best particle


ffmin(ite,run)=fmin; % storing best fitness
ffite(run)=ite; % storing iteration count

% updating gbest and best fitness


if fmin<fmin0
gbest=pbest(index,:);
fmin0=fmin;
end

% calculating tolerance
if ite>100;
tolerance=abs(ffmin(ite-100,run)-fmin0);
end

% displaying iterative results


if ite==1
disp(sprintf('Iteration Best particle Objective fun'));
end
disp(sprintf('%8g %8g %8.4f',ite,index,fmin0));
ite=ite+1;
end
% pso algorithm-----------------------------------------------------end
gbest;
fvalue=10*(gbest(1)-1)^2+20*(gbest(2)-2)^2+30*(gbest(3)-3)^2;
fff(run)=fvalue;
rgbest(run,:)=gbest;
disp(sprintf('--------------------------------------'));
end
% pso main program------------------------------------------------------end
disp(sprintf('\n'));
disp(sprintf('*********************************************************'));
disp(sprintf('Final Results-----------------------------'));
[bestfun,bestrun]=min(fff)
best_variables=rgbest(bestrun,:)
disp(sprintf('*********************************************************'));
toc

% PSO convergence characteristic


plot(ffmin(1:ffite(bestrun),bestrun),'-k');
xlabel('Iteration');
ylabel('Fitness function value');
title('PSO convergence characteristic')
%##########################################################################
-----------------------------------------------------------------------------------------------------------------------------------end

Enjoy with PSO;


******************************************************************************************

Common questions

Powered by AI

The inertia weight in the PSO algorithm is used to balance the exploration and exploitation abilities of the swarm by controlling the influence of a particle's previous velocity on its new velocity. It is initially set to a maximum value (wmax) and decreases linearly to a minimum value (wmin) as the iterations progress. This is done according to the formula w = wmax - (wmax - wmin) * ite / maxite, where ite represents the current iteration number. This dynamic adjustment enables the swarm to explore a wider search space in the beginning and gradually focus on exploiting the best solutions towards the end of the optimization process .

The initial population of particles in PSO is generated randomly within the defined lower (LB) and upper bounds (UB) for each parameter. This is done by calculating initial positions as x0(i,j) = round(LB(j) + rand()*(UB(j) - LB(j))), where rand() generates random values. This random initialization is crucial as it ensures a diverse set of starting points, providing an ample exploration of the search space at the outset, which enhances the algorithm's ability to avoid local optima and find a global solution .

PSO handles boundary violations during the particle update phase by implementing a boundary-checking routine after updating the particle's positions. If any particle's position exceeds the predefined lower (LB) or upper bounds (UB) for any dimension, the position is automatically reset to the corresponding boundary value. This ensures that all particle positions remain within the feasible search space, preventing any invalid configurations and maintaining the integrity of the optimization process within preset constraints .

The PSO algorithm ensures convergence towards an optimal solution through several mechanisms: inertia weight adjustment, individual learning (pbest), and social learning (gbest). The gradual reduction of inertia weight focuses the search towards known high-quality regions as iterations progress. The fitness function evolution, which computes the minimized objective value while penalizing constraint violations, serves as an indicator of progress. A decrease in the best fitness function value stored across iterations suggests improvement towards convergence. Furthermore, the algorithm measures tolerance based on changes in the fitness values over a pre-specified number of iterations to determine and display convergence proximity .

In the PSO algorithm, the acceleration factors c1 and c2, commonly known as the cognitive and social coefficients respectively, regulate the convergence behavior of the swarm towards optimal solutions. The cognitive component (c1) weights the particle's individual experience by pulling it towards its own best-found position (pbest), while the social component (c2) influences the particle based on the best position found by the entire swarm (gbest). Both components are multiplied by random values to maintain stochasticity in the search process. By adjusting these factors, the algorithm balances personal exploration against cooperative behavior, aiding in both diversification and convergence .

The tolerance variable in the PSO iteration process acts as a convergence criterion. It measures the change in the best fitness value over a certain number of iterations to assess whether the algorithm is making significant progress. If the change between the fitness value at the current iteration and the value at prior step (typically away by a specified count) is small, indicating little improvement, the tolerance metric signals near-convergence. This allows the algorithm to terminate early if improvements fall below a defined threshold, preventing unnecessary computations and saving resources while ensuring solution adequacy .

In the Particle Swarm Optimization algorithm, the 'gbest' vector represents the global best solution found across the entire swarm up to the current iteration. It stores the position (parameter settings) that yielded the lowest objective function value. This global best solution influences the motion of all particles in the swarm, effectively directing them towards promising regions of the search space. The gbest vector is crucial for maintaining swarm convergence towards optimal or near-optimal solutions .

The penalty and fitness function in the PSO algorithm enable optimization under constraints by adjusting the objective function value whenever constraints are violated. Each constraint contributes a penalty to the objective value if not satisfied, transforming infeasible solutions into higher fitness values. This dual structure is beneficial as it guides particles away from constraint violations while encouraging convergence on feasible optimal solutions. The penalty application is integral in maintaining solution validity within constrained domains, balancing exploration for global optimization with adherence to constraints .

The PSO algorithm handles constraint violations by first checking if the constraints are satisfied, converting all constraints into a <= 0 form. If any constraints are violated (i.e., c0(i) > 0), the algorithm sets a penalty flag for that constraint. A penalty value of 10,000 is applied for each constraint violation, and this penalty is added to the objective function value to form the fitness function. This approach ensures that the algorithm penalizes solutions that violate constraints, guiding the optimization process towards feasible solutions .

In PSO, the velocity of each particle is updated based on inertia weight, cognitive component, and social component. The updated velocity is calculated using the formula v(i,j) = w*v(i,j) + c1*rand()*(pbest(i,j)-x(i,j)) + c2*rand()*(gbest(1,j)-x(i,j)), where 'w' is the inertia weight, 'c1' and 'c2' are the acceleration factors, and rand() are random numbers. The velocity update considers the particle's previous best position (pbest) and the swarm's best position (gbest). Subsequently, the position of each particle is updated by adding the new velocity to the current position, ensuring boundary constraints are respected. This update mechanism enables particles to explore the search space by adjusting their positions based on individual and collective experiences .

You might also like