Challenge

To optimise the Stalagmite function and find the global maxima of the function using Genetic Algorithm in MATLAB

AIM: To write a code in MATLAB to optimise the Stalagmite function and find the global maxima of the function.

THEORY:

*The following outline summarizes how the genetic algorithm works:

  1. The algorithm begins by creating a random initial population.
  2. The algorithm then creates a sequence of new populations. At each step, the algorithm uses the individuals in the current generation to create the next population. To create the new population, the algorithm performs the following steps:
    1. Scores each member of the current population by computing its fitness value. These values are called the raw fitness scores.
    2. Scales the raw fitness scores to convert them into a more usable range of values. These scaled values are called expectation values.
    3. Selects members, called parents, based on their expectation.
    4. Some of the individuals in the current population that have lower fitness are chosen as elite. These elite individuals are passed to the next population.
    5. Produces children from the parents. Children are produced either by making random changes to a single parent—mutation—or by combining the vector entries of a pair of parents—crossover.
    6. Replaces the current population with the children to form the next generation.
  3. The algorithm stops when a stopping criteria is met. Stopping conditions are generations, time limit, fitness limit, etc.

*Syntax for Genetic Algorithm :

  1. x = ga(fun,nvars)

It finds a local unconstrained minimum, x, to the objective function, fun. nvars is the dimension (number of design variables) of fun.

  1. x= ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon) or x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options)

requires that the variables listed in IntCon take integer values.

*The Stalagmite function as follows:

*Stopping criteria for a Genetic Algorithm:

The genetic algorithm uses the following conditions to determine when to stop:

  • Generations — The algorithm stops when the number of generations reaches the value of Generations.

  • Time limit — The algorithm stops after running for an amount of time in seconds equal to Time limit.

  • Fitness limit — The algorithm stops when the value of the fitness function for the best point in the current population is less than or equal to Fitness limit.

  • Stall generations — The algorithm stops when the average relative change in the fitness function value over Stall generations is less than Function tolerance.

  • Stall time limit — The algorithm stops if there is no improvement in the objective function during an interval of time in seconds equal to Stall time limit.

  • Stall test — The stall condition is either average change or geometric weighted. For geometric weighted, the weighting function is 1/2n, where n is the number of generations prior to the current. Both stall conditions apply to the relative change in the fitness function over Stall generations.

  • Function tolerance — The algorithm runs until the average relative change in the fitness function value over Stall generations is less than Function tolerance.

  • Constraint tolerance — The Constraint tolerance is not used as stopping criterion. It is used to determine the feasibility with respect to nonlinear constraints. Also, max(sqrt(eps),ConstraintTolerance) determines feasibility with respect to linear constraints.

*Significance of running multiple iterations:

This is because after successive iterations, the population evolves toward an optimal solution.

*Significance of different cases:

In situation 1, we evaluate all possible global maxima for all the iterations using a loop. We plotted two plots in same figure using subplot() command. The Surfc() command is used for graph between xx, yy and (-f). The values in figure 1 are unbounded values. In situation 2, we put an upper bound and lower bound on ga() function and again plot the two plots that we did in situation 1. In situation 3, we increase GA iterations. This is because after successive iterations, the population evolves toward an optimal solution. Now, we again plotted the same plots.

CODE:

Main code:

clear all
close all
clc

x=linspace(0,1,150);
y=linspace(0,1,150);
[xx, yy]=meshgrid(x,y);                   %generating the matrices

for i=1:length(xx)
    for j=1:length(yy)
        inputvector(1)=xx(i,j);
        inputvector(2)=yy(i,j);
        f(i,j)=stalagmite(inputvector);  %calling the user-defined function stalagmite()
    end
end

n=150;

tic                                               %for calculating the time
% situation 1:statistical behaviour
for i=1:n
    [inputvector,foutput(i)]=ga(@stalagmite,2);   %calling the inbuilt function ga()
    xoutput(i)=inputvector(1);
    youtput(i)=inputvector(2);
end
time_situation1=toc;

figure(1)
subplot(2,1,1)
surfc(xx,yy,-f)                           %drawing he surface; the negative sign is given because the ga() function always calculates the minimum value of the function but here we have to find out the max value of function

shading interp                            %for making the surface smooth and grid-free
hold on
plot3(xoutput,youtput,-foutput,'marker','*','markersize',4,'markerfacecolor','k')
title('statistical behaviour')
subplot(2,1,2)
plot(-foutput)
xlabel('No of iterations')
ylabel('Mximum value of function')

tic
%situation 2 : statistical behaviour with the upper bound and lower bound
for i=1:n
    [inputvector,foutput(i)]= ga(@stalagmite,2,[],[],[],[],[0;0],[0.3;0.3],[],[]);
    xoutput(i)=inputvector(1);
    youtput(i)=inputvector(2);
end
time_situation2=toc;

figure(2)
subplot(2,1,1)
surfc(x,y,-f)
shading interp
hold on
plot3(xoutput,youtput,-foutput,'marker','*','markersize',4,'markerfacecolor','k')
title('statistical behaviour with upper bound and lower bound')
subplot(2,1,2)
plot(-foutput)
xlabel('No of iterations')
ylabel('Mximum value of function')

tic
%situation 3 : increasing no of iterations
k=optimoptions('ga');
k=optimoptions(k,'populationsize',250);
for i=1:n
[inputvector,foutput(i)]= ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],k);
    xoutput(i)=inputvector(1);
    youtput(i)=inputvector(2);
end
time_situation3=toc;

figure(3)
subplot(2,1,1)
surfc(x,y,-f)
shading interp
hold on
plot3(xoutput,youtput,-foutput,'marker','*','markersize',5,'markerfacecolor','k')
title('increasing no of iterations')
subplot(2,1,2)
plot(-foutput)
xlabel('no of iterations')
ylabel('maximum value of the function')

Function:

function [f] = stalagmite(i)
     f1x=[sin(5.1*pi.*i(1)+0.5)]^6;                 %term 1
     f2x=exp(-4*log(2)*(i(1)-0.0667).^2/0.64);      %term 2
     f1y=[sin(5.1*pi.*i(2)+0.5)]^6;                 %term 3
     f2y=exp(-4*log(2)*(i(2)-0.0667).^2/0.64);      %term 4
     
     f=f1x*f2x*f1y*f2y;                            %stalagmite function
end

OUTPUT:

plot-situation 1

plot 2- situation 2

plot 3- situation 3

EXPLANATION OF CODE AND OUTPUT:

In the main code, we have taken the values of x and y. Then the matrices are generated using the meshgrid() command. We get values of f for corresponding values of xx and yy with the help of the user-defined function stalagmite(). To optimise the stalagmite() function and find the global maxima of the function, we considered three situations – statistical behaviour, statistical behaviour with upper bound and lower bound, increasing number of iterations. This is because the GA randomly takes the values and Global Maxima can change according to that. In situation 1, we evaluate all possible global maxima for all the iterations using a loop. We plotted two plots in same figure using subplot() command. The Surfc() command is used for graph between xx, yy and (-f). The values in figure 1 are unbounded values. In situation 2, we put an upper bound and lower bound on ga() function and again plot the two plots that we did in situation 1. In situation 3, we increase GA iterations. This is because after successive iterations, the population evolves toward an optimal solution. Now, we again plotted the same plots.

In the function stalagmite(), we defined the function. I have shown four terms separately for the convenience .This is the function which we will optimise using Genetic Algorithm and find the Global Maxima of it.

In the output, I have plotted the graphs for all three studies (as well as graph for maximum of function vs number of iterations). Title, axes labels and legends are shown for each figure. The values in figure 1 are unbounded values. In situation 2, we put an upper bound and lower bound on ga() function and again plot the two plots that we did in situation 1. In situation 3, we increase GA iterations. We can see the maximum value of the Stalagmite function from the three figures.

ERROR:

Error 1. Following error was displayed. The plots were not proper.

Error 1

STEPS TAKEN TO OVERCOME THE ERROR:

The inbuilt function ga() of MATLAB is designed to find the minimum value of the function but here we have to find out the maximum value of the function. Thus, I put negative sign with f while calling the function surface(). In stalagmite() function , I put a negative sign with the value of f.This resolved my error.

RESULT: A code in MATLAB to optimise the Stalagmite function and find the global maxima of the function is created.

REFERENCE:

https://in.mathworks.com/help/gads/how-the-genetic-algorithm-works.html

https://in.mathworks.com/help/gads/ga.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.