Challenge

Week 4.1 - Genetic Algorithm

AIM: To study about Genetic Algorithm and to calculate the global maxima of stalagmite function using Genetic Algorithm 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:

A Genetic Algorithm (GA) is a metaheuristic inspired by the process of natural selection that belongs to the larger class of evolutionary algorithms (EA). Genetic algorithms are commonly used to generate high-quality solutions to optimization and search problems by relying on biologically inspired operators such as mutation, crossover and selection. Some examples of GA applications include optimizing decision trees for better performance, automatically solve puzzles, hyperparameter optimization, etc.

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 form 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 these 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 parent 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 factors such as time limit, fitness limit, generations, function tolerance, constraint tolerance, etc.

The flowchart for Genetic Algorithm is given below,

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,Aeq,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, IntCon, options)

where,

nonlcon Nonlinear constraints

IntCon = Integer Values

options = Optimization options

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

Stalagmite Function

A stalagmite function generally refers to the function with which we are generating values over a stalagmite kind of surface for finding out the local and global maxima and minima of that particular given function.

Stalagmite function is a mathematical model which helps to generate local minima and maxima. It is a three dimensional 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 stalagmite 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.0667)^2/0.64]`

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

`thereforef_(x,y)=f_(1,x)xxf_(1,y)xxf_(2,x)xxf_(2,y)`

PROGRAM:

First in order to define stalagmite function, we need to write a function for stalagmite.

% Define Stalagmite function

function [f] = stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);

term1 = (sin((5.1*pi*x)+0.5))^6;
term2 = (sin((5.1*pi*y)+0.5))^6;
term3 = exp(-4*log(2)*((x-0.0667)^2)/0.64);
term4 = exp(-4*log(2)*((y-0.0667)^2)/0.64);

f = -(term1*term2*term3*term4);
end

Procedure for the Stalagmite function

  1. Write the function to perform the stalagmite function.
  2. Intializing the inputs for 'x' and 'y' with input_vector(1) and input_vector(2).
  3. Divide the equation with four differnt terms and name them as term1, term2, term3 and term4.
  4. For calculating the stalagmite function multiply all terms. [f=-(term1*term2*term3*term4)].
  5. The negative sign in the function will invert the stalagmite plot which will eventually give the function mamima.

Now, we can write the code for Genetic algorithm for the stalagmite function.

% Genetic Algorithm for the stalagmite function

clear all
close all
clc

% Defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50;

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

% Evaluating the 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

% Creating a three dimensional surface
figure(1)
surfc(xx,yy,-f)
xlabel('X Value')
ylabel('Y Value')

% Making the surface look more smoother
shading interp
[inputs,fval] = ga(@stalagmite,2)

% Study 1: Statistical Behaviour
tic
for i = 1:num_cases
    [inputs,fopt(i)] = ga(@stalagmite,2);
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end

study1_time = toc

figure(2)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('Statistical Behaviour with Unbound inputs')
subplot(2,1,2)
plot(fopt)
xlabel('No. of Iterations')
ylabel('Function Maximum')

% Study 2: Statistical behaviour with upper and lower boundaries

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

study2_time = toc
figure(3)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('Statistical Behaviour with Upper and Lower Bounds')
subplot(2,1,2)
plot(fopt)
xlabel('No. of Iterations')
ylabel('Function Maximum')

% Study 3: Statistical Behaviour With Increasing Iterations
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',300);

tic

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

study3_time = toc
figure(4)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','MarkerSize',5,'MarkerFaceColor','r')
title('Statistical Behaviour with Increasing Iterations')
subplot(2,1,2)
plot(fopt)
xlabel('No. of Iterations')
ylabel('Function Maximum')

Procedure for the Genetic algorithm for the stalagmite function

  1. The code starts with clear all, close all and clc.
  2. The 'x' array and 'y' array is defined using 'linspace' command to create 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 num_cases = 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 inputs and optimum max value. The stalagmite function is called in 'ga' syntax and number of variables 'nvars' 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 'surfc' 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 colour. 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. To get same value each time, we need to restrict the program within specific bounds namely upper bound and lower bound. The procedure for coding and plottind this procedure is same as Study 1. 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:

Statistical behaviour with increasing iterations: The graph shows 'Function maximum vs No. of iterations' results that the value of optimum function 'fopt' is approximately equal to 1.

Study1- Statistical Behaviour:

In above plot, it can be observed 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.

Study2- 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.

Study-3 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 stalagmite 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.06683 and y=0.06683.

Workspace Values:

ERRORS:

  • No major errors were thrown in command window while coding.
  • No complicated errors occured while running the MATLAB program.

REFERENCES:

  1. https://en.wikipedia.org/wiki/Genetic_algorithm
  2. https://in.mathworks.com/discovery/genetic-algorithm.html
  3. https://in.mathworks.com/help/gads/constrained-minimization-using-ga.html
  4. https://in.mathworks.com/help/gads/how-the-genetic-algorithm-works.html
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.