Week 4.1 - Genetic Algorithm
1. OBJECTIVE - To write a code in MMATLAB to optimize the stalagmite function & to find the global maxima of the function.
WHAT ARE GENETIC ALGORITHMS?
A genetic algorithm is a search heuristic that is inspired by Charles Darwin’s theory of natural evolution. This algorithm reflects the process of natural selection where the fittest individuals are selected for reproduction in order to produce offspring of the next generation.
Process of natural selection
The process of natural selection starts with the selection of fittest individuals from a population. They produce offspring which inherit the characteristics of the parents and will be added to the next generation. If parents have better fitness, their offspring will be better than parents and have a better chance at surviving. This process keeps on iterating and at the end, a generation with the fittest individuals will be found.
This notion can be applied for a search problem. We consider a set of solutions for a problem and select the set of best ones out of them.
Five phases are considered in a genetic algorithm.
- Initial population
- Fitness function
- Selection
- Crossover
- Mutation
1.Initial population
The process begins with a set of individuals which is called a Population. Each individual is a solution to the problem you want to solve.
An individual is characterized by a set of parameters (variables) known as Genes. Genes are joined into a string to form a Chromosome (solution).
In a genetic algorithm, the set of genes of an individual is represented using a string, in terms of an alphabet. Usually, binary values are used (string of 1s and 0s). We say that we encode the genes in a chromosome.
2.Fitness function
The fitness function determines how fit an individual is (the ability of an individual to compete with other individuals). It gives a fitness score to each individual. The probability that an individual will be selected for reproduction is based on its fitness score.
3.Selection
The idea of selection phase is to select the fittest individuals and let them pass their genes to the next generation.
Two pairs of individuals (parents) are selected based on their fitness scores. Individuals with high fitness have more chance to be selected for reproduction.
4.Crossover
Crossover is the most significant phase in a genetic algorithm. For each pair of parents to be mated, a crossover point is chosen at random from within the genes.
5.Mutation
In certain new offspring formed, some of their genes can be subjected to a mutation with a low random probability. This implies that some of the bits in the bit string can be flipped.
Syntax for genetic algorithm
Description
finds a local unconstrained minimum, x = ga(fun,nvars)x, to the objective function, fun. nvars is the dimension (number of design variables) of fun.
Note
Passing Extra Parameters explains how to pass extra parameters to the objective function and nonlinear constraint functions, if necessary.
subjects the minimization to the constraints defined in x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon)nonlcon. The function nonlcon accepts x and returns vectors C and Ceq, representing the nonlinear inequalities and equalities respectively. ga minimizes the fun such that C(x) ≤ 0 and Ceq(x) = 0. (Set lb=[] and ub=[] if no bounds exist.)
or x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon) requires that the variables listed in x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon,options)intcon take integer values.
Note
When there are integer constraints, ga does not accept nonlinear equality constraints, only nonlinear inequality constraints.
finds the minimum for x = ga(problem)problem, a structure described in problem.
main code:
clear all
close all
clc
x=linspace(0,0.6,10);
y=linspace(0,0.6,10);
num_space=50;
[xx yy] = meshgrid(x,y);
for i=1:length(xx)
for j=1:length(yy);
input_vector(1)=xx(i,j);
input_vector(2)=yy(i,j);
f(i,j)=stalagmite(input_vector);
end
end
%study1 --unbounded
tic
for i=1:num_space;
[results,fopt(i)]=ga(@stalagmite,2);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time1=toc
figure(1)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
%study 2 -bounded
tic
for i=1:num_space
[results,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time2=toc
figure(2)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
%study3-increased initial population
tic
options=optimoptions('ga');
options=optimoptions(options,'populationsize',250);
for i=1:num_space;
[results,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time3=toc;
figure(3)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
stalagmite function code :
function A=stalagmite(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*x+0.5)).^6;
f2=exp((-4*log(2))*((x-0.0667).^2)/0.64);
f3=(sin(5.1*pi*y+0.5)).^6;
f4=exp((-4*log(2))*((y-0.0667).^2)/0.64);
A=-(f1*f2*f3*f4);
end
result :
STUDY 1

study time = 2.7969 sec
here , we can see the optium value went outside of x and y & failed to get the global maxima.
STUDY 2

study time = 2.9437 sec
Here, we could not get the exact optimum values.
STUDY 3

study time = 10.5642 sec
Here , the time of the execution is more. but we can find the correct maxima for the stalagmite function.
so by increasing the population , we can get accurate maximas.
EXPLANATION :
clear all
close all
clc
%inputs
x=linspace(0,0.6,10);
y=linspace(0,0.6,10);
num_space=50;
first we initialises the values of x & y taking 10 values between the interval 0 & 0.6.
we consider no: of iteration num_space = 50.
%forming 2D array using for loop
[xx yy] = meshgrid(x,y);
for i=1:length(xx)
for j=1:length(yy);
input_vector(1)=xx(i,j);
input_vector(2)=yy(i,j);
f(i,j)=stalagmite(input_vector);
end
end
since we need to plot a 3D surface plot we take the 2D array of x and y using meshgrid command and store them in input_vector array, so that it can be used as an argument to call the function stalagmite.
Then stalagmite function is created.here we take the output as -f.so that it gives us the maxima.
function A=stalagmite(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*x+0.5)).^6;
f2=exp((-4*log(2))*((x-0.0667).^2)/0.64);
f3=(sin(5.1*pi*y+0.5)).^6;
f4=exp((-4*log(2))*((y-0.0667).^2)/0.64);
A=-(f1*f2*f3*f4);
end
first study :
In first study, no : of iteration = num_space and we use the genetic algorithm function to calculate the maxima of the function. then the outputs from the stalagmite functions is stored in the result(1) & results(2) which contain the maximas & fopt which contain the value at which the maxima is obtained.
Also, the 'ga' is initiated with random population.
%study1 --unbounded
tic
for i=1:num_space;
[results,fopt(i)]=ga(@stalagmite,2);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time1=toc
figure(1)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
Here, a 3D plot is created using surf(x,y,-f).
Also plots the fopt function vs iteration graph to visualise the optium value at each iteration.
To get the time taken to complete cycle, 'tic' command is used & 'toc' command is used to measure the time.
second study :
In this study, the lower and upper bounds of x and y are specified. and 'ga' is initiated with random population.
%study 2 -bounded
tic
for i=1:num_space
[results,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time2=toc
figure(2)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
Here, a 3D plot is created using surf(x,y,-f).
Also plots the fopt funcction vs iteration graph to visualise the optium value at each iteration.
To get the time taken to complete cycle, 'tic' command is used & 'toc' command is used to measure the time.
Third study : In this case study, we will increase our initial population to 250.
%study3-increased initial population
tic
options=optimoptions('ga');
options=optimoptions(options,'populationsize',250);
for i=1:num_space;
[results,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time3=toc;
figure(3)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
Here, 'optimoption' command is used to increase the population to 250.
Then a 3D plot is created using surf(x,y,-f).
Also plots the fopt funcction vs iteration graph to visualise the optium value at each iteration.
To get the time taken to complete cycle, 'tic' command is used & 'toc' command is used to measure the time.