Challenge

Week 4.1 - Genetic Algorithm

AIM : To study about Genetic Algorithem and to calculate the global maxima of stalagmite function using Genetic Algorithem in MATLAB.

OBJECTIVE :

  • To study about Genetic Algorithm and Stalagmite function.
  • To write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
  • To plot graphs based on the studies done for Genetic Algorithm.

THEORY:

Concept of Genetic Algorithm-

The Genetic Algorithm works on the process of natural selection where the fittest individuals are selected for reproduction in order to produce offspring of the next generation.it is a method for solving both constrained and unconstrained optimization problems that is based on natural selection. The algorithm begins by creating a random initial population of individual selections and it keeps on modifying this population repeatedly creating a sequence of new population. The algorithm uses the individuals in the current generation to create the next population. The genetic algorithm selects individuals at random from the current population to be parents and uses them to produce the children for the next generation. Over successive generations, the population evolves toward an optimal solution.

The genetic algorithm uses three main types of rules at each step to create the next generation from the current population:

  • Selection rules select the individuals called parents,that contribute to the population at the next generation.
  • Crossover rules combine two parents to form children for the next generation.
  • Mutation rules apply random changes to individual parents to from children.

The basic steps in creating a genetic algorithm is as follows,

  1. The algorithm creates a random initial population at beginning.
  2. Then to create new population,the algorithm scores each member of the current population by computing its fitness value and converts them into a more usable range of values.
  3. Then based on there new values the algorithm selects members,called as parents.
  4. Then the algorithm produces children from the parents. children are produced either by making random changes to a single parents which is mutation or by combining the vector entries of a pair of parents which is crossover.
  5. In this way the algorithm replaces the current population with the children to form the next generation.
  6. The algorithm stops when it reaches any one of the specified factors such as limit,fitness limit,generations,function tolerance,constraint tolerance,etc.

The flowchart for Genetic Algorithm is given below,

What is a Stalamite Function?

Stalagmite function is a mathematical model which helps to generate local minima and maxima.It is a three dimentional function and the way the function is designed is that it has a lot of local maxima or minima and one global maxima or minima. The name stalgmite is actually a type of rock formation that arises from the floor of a cave due to the accumulation of material deposited on the floor from ceiling drippings.

The stalagmite function is given as,

`f_(1,x) = [sin(5.1pix+0.5)]^6`

`f_(1,y) = [sin(5.1piy+0.5)]^6`

`f_(2,x) = exp[-4ln(2)*(x-0.0067)^2/0.64]`

`f_(2,y) = exp[-4ln(2)*(y-0.0067)^2/0.64]`

:`f(x,y) = f_(1,x)*f_(1,y)*f_(2,x)*f_(2,y)`

Syntax for defining 'ga' (Genetic Algorithm) in matlab -

The 'ga' syntax in matlab is used to find the minimum of function using genetic algorithm. There are several ways to define the 'ga' function depending on the problem being solved. The syntax used for this study is shown below.

  • x = ga(fun,nvars)

where,

x = optimal solution/variables;

fun = Objective function;

nvars = Number of variables;

Sometimes '[x,fval]' is used instead of 'x' where 'fval' gives objective function value at the solution

  • x = ga(fun,nvars,A,B,Beq,lb,ub)

where,

A, B = Linear inequality constraints

Aeq,Beq = Linear equality constraints

If there are no linear equalities and inequalities,then A,B Aeq,Beq are set to '[]'.

  • x = ga(fun,nvars,A,B,Aeq,Beq,lb,ub,nonlcon,lntCon,options)

where,

nonlcon = Nonlinear constraints

lntCon = Integer Values

options = Optimization options

If there are no nonlinear constraints and integer values, the nonlcon and IntCon are set to '[]'.

MATLAB Program :

First in order to define stalagmite function,we need to write a different script defining the stalagmite function.

%Define stalamite Function
function [f] = stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);

t1 = (sin((5.1*pi*x)+0.5))^6;
t2 = (sin((5.1*pi*y)+0.5))^6;
t3 = exp(-4*log(2)*((x-0.0667)^2)/0.64);
t4 = exp(-4*log(2)*((y-0.0667)^2)/0.64);

f = -(t1*t2*t3*t4);
end

The negative sign in the function will invert the stalagmite plot which will eventually give the function maxima.

Now we can proceed for coding the Genetic Algorithm for this stalagmite function.

clear all
close all 
clc

%Define our search space
x = linspace(0,0.6,150);          %x array
y = linspace(0,0.6,150);          %y array
n = 50;                           %number of cases

%Creating a 2D mesh
[xx yy] = meshgrid(x,y);

%Evaluatiuon a stalagmite function
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
%study 1 :statistical Behaviour

tic
for i=1:n
    [inputs,fopt(i)] = ga(@stalagmite,2);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end
study1_time = toc

figure(1)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
xlabel('X-axis')
ylabel('Y-axis')
title('Statistical Behaviour with Unbound inputs')
plot3(xopt,yopt,-fopt,'marker','o','markerSize',5,'markerfacecolor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('No. of Iterations')
ylabel('Function maximum')

%Study2 : Statistical behaviour with upper and lower bounds

tic
for i = 1:n
    [inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end
study2_time = toc

figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
xlabel('X-axis')
ylabel('Y-axis')
title('Statistical Behaviour with upper and lower bounds')
plot3(xopt,yopt,-fopt,'marker','o','markerSize',5,'markerfacecolor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('No. of Iterations')
ylabel('Function maximum')

%study3 : Statistical Behaviour with increasing iterations of GA

options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',300);

tic
for i = 1:n
    [inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end
study3_time = toc

figure(3)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
xlabel('X-axis')
ylabel('Y-axis')
title('Statistical Behaviour with increasing iterations')
plot3(xopt,yopt,-fopt,'marker','o','markerSize',5,'markerfacecolor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('No. of Iterations')
ylabel('Function maximum')

Here in this code,

  1. The code stars with clear all,close all and clc where,
  • 'clear all' command is used to close the data stored in the workspace.
  • 'close all' command is used to close all data plots and figures.
  • 'clc' command is used to clear the command window.

2. Then the ' x' array and 'y' array is defined using 'linspace' command to creat values at 150 equal intervals.

3. A 2D mesh of x and y array is created by using 'meshgrid' command and the number of iterations or cases that the code should perform is defined. This is given by n = 50.

4. To evaluate the stalagmite function, 'for' loop is used where 'i' is initialized and for every value of 'i' another 'for' loop is used to initialize 'j'.

5. The input vector values of 'xx' and 'yy' are defined and the stalagmite function for these input vector is defined. This will form a basic stalagmite function and we can plot it separately if needed.

6. After preparing the inputs needed for the function,next step is to obtain the results for 3 cases of the genetic algorithm. In first case or study,the maximum value of function is found out with no restrictions, no bounds and no limits.

7. This is done using 'for' loop where we use 'ga' syntax to give values for is called in 'ga' syntax and number of variables 'nars' are 2.

8.To know the time that is taken to solve the loop for 50 iterations, 'tic' and 'toc' command is used before and after the loop respectively.

9.Then the function created in the loop is plotted by using 'surf' command for 'xx,yy and function output'.To neglect the gridlines on the surface and obtain a smooth and clean plot,'shading interp,command is used. The 'subplot(2,1,1)' is used to plot multiple plots on same figure which also divides figure in grid of 2x1 and axes to be placed at 1.

10.The 'plot3' command plots the 3D points at 'xopt,yopt and optimum value of function' with 'o' shaped and red color. The labels and title are then provided. Now in the same figure,the values of optimum function 'fopt' are plotted for 50 iterations.

11.The results of the above case will be different for each time we run the program with in specific bounds namely upper bound and lower bound. The procedure for coding and plotting this procedure is same as study. The only difference is in the 'ga' syntax. This time the algorithm is provided lower limits and upper limits as [0;0] and [1;1] respectively.

12.After plotting the results for study 2 or the bounded case,it is observed that the results are not same every time the program terminates. A solution to this problem is to increase the number of cases or iterations.

13.So for Study 3,the number of iterations are increased to 300.

So for this study, the syntax, "options = optimoptions('SolverName','Name','Value')" is used which returns with named parameter 'populations' with the altered values '300'.

14. The syntax for 'ga' contains 'option' term and the rest of the code is same as for Study 1 and 2.

RESULTS :

Study 1 - Statistical Behavior.

In above plot,it can be obeserved how the random sampling of the genetic algorithm generates a new optimum value for the function every time the code is run.Although this falls in line with the definition of Genetic Algorithm. Large number of red dots shows values of co-ordinates of x,y varies each time iteration runs.

Study 2 - Statistical Behaviour with upper and lower bounds.

The above results show the convergence of x and y values. The number of red dots are less compared to previous plot. This is the result of providing upper and lower bounds to the function.

Study3 - Statistical Behaviour with increasing iterations of GA.

In this study,the number of iterations is increased to 300 to converge and find the global maxima of the function.Here we can see that there is only one red dot on the stalagmite4 function and that is the required global maxima point.

On rotating the plot, we can clearly see the stalagmite function along with the global maxima value as x = 0.0668314 and y = 0.0668472.

Also the graph of 'Function maximum vs No.of Iterations' results that the value of optimum function 'fopt' is approximately equal to 1.

Workspace Values -

ERRORS :

*Np major errors faced while coding.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.